diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec31c8370b3451fc30798f3c79e9f52de86c11cd --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,68 @@ +# yaml-language-server: $schema=https://golangci-lint.run/jsonschema/golangci.jsonschema.json +version: "2" +linters: + default: none + enable: + - bodyclose + - errcheck + - govet + - ineffassign + - misspell + - nolintlint + - sloglint + - staticcheck + - unconvert + # FIXME: re-enable following linters + #- unparam + #- unused + - whitespace + #- wsl + settings: + misspell: + locale: US + nolintlint: + require-specific: true + revive: + confidence: 0 + staticcheck: + checks: + - "all" + - "-QF1008" + - "-SA1019" # https://staticcheck.dev/docs/checks/#SA1019 + # FIXME: re-enable the following checks + - "-ST1003" + - "-ST1016" + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - collector/benthos/internal + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gci + - gofmt + - gofumpt + - goimports + settings: + gci: + sections: + - standard + - default + - prefix(github.com/openmeterio/openmeter) + goimports: + local-prefixes: + - github.com/openmeterio/openmeter + exclusions: + generated: lax + paths: + - collector/benthos/internal + - third_party$ + - builtin$ + - examples$ diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f86248345ca10c2191eede8da1248d75ecf97d33 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,45 @@ +# This is an example .goreleaser.yml file with some sensible defaults. +# Make sure to check the documentation at https://goreleaser.com +project_name: openmeter + +dist: build/dist + +gomod: + proxy: true + +before: + hooks: + - go mod tidy +builds: + - env: + - CGO_ENABLED=0 + main: . + goos: + - linux + - windows + - darwin + +archives: + - format: tar.gz + # this name template makes the OS and Arch compatible with the results of uname. + name_template: >- + {{ .ProjectName }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{ .Arch }}{{ end }} + {{- if .Arm }}v{{ .Arm }}{{ end }} + # use zip for windows archives + format_overrides: + - goos: windows + format: zip +checksum: + name_template: "checksums.txt" +snapshot: + name_template: "{{ incpatch .Version }}-next" +changelog: + sort: asc + filters: + exclude: + - "^docs:" + - "^test:" diff --git a/.grype/config.yaml b/.grype/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5263ce871810e1940ebb36aa7737731829cc529a --- /dev/null +++ b/.grype/config.yaml @@ -0,0 +1,5 @@ + +ignore: + # Nats server admin api authorization bypass: https://github.com/advisories/ghsa-fhg8-qxh5-7q3w + # This is not an issue, as we never start a nats server in our codebase + - vulnerability: GHSA-fhg8-qxh5-7q3w diff --git a/.hfignore b/.hfignore new file mode 100644 index 0000000000000000000000000000000000000000..cd8e61e4c1b24a593cf31f2d77fc93faaeb01dd8 --- /dev/null +++ b/.hfignore @@ -0,0 +1,40 @@ +.git/ +.devenv/ +.direnv/ +.env.local +.pre-commit-config.yaml +build/ +config.yaml +tmp/ +.tmp.* +.DS_Store +go.work +go.work.sum +__debug_bin* +openmeter.log +.gocache +.gomodcache +.claude/ +CLAUDE.local.md +api/v3/templates/chi-middleware.tmpl +.codegraph/ +node_modules/ +dist/ +.agents/ +.vscode/ +.github/ +.spectral.yaml +.syft.yaml +.fossa.yaml +.editorconfig +.coderabbit.yaml +.golangci.yaml +.golangci-fast.yaml +.goreleaser.yaml +.mcp.json +.semgrepignore +atlas.hcl +flake.lock +flake.nix +justfile +Makefile diff --git a/.mcp.json b/.mcp.json new file mode 100644 index 0000000000000000000000000000000000000000..53da2d8e33b140a038bdd752652b7e65d0f6eaf0 --- /dev/null +++ b/.mcp.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "codegraph": { + "type": "stdio", + "command": "codegraph", + "args": ["serve", "--mcp"] + } + } +} diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000000000000000000000000000000000000..f7a56c9ec21d70bf8663e0f8144ba2c152c40995 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +v26.4.0 diff --git a/.semgrepignore b/.semgrepignore new file mode 100644 index 0000000000000000000000000000000000000000..68e353ded2bad136b0fb95e6177ec283b28af5d6 --- /dev/null +++ b/.semgrepignore @@ -0,0 +1,9 @@ +api/client/python/src/openmeter/_serialization.py +**/*_test.go + +# These are only included due to bugous //nosemgrep support in current version, please remove them once the semgrep has been upgraded + +openmeter/billing/service/seq.go +collector/benthos/input/otel_log.go +openmeter/productcatalog/feature/connector.go +openmeter/watermill/driver/kafka/broker.go diff --git a/.spectral.yaml b/.spectral.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5a0ed0f0f04c3cfd3534cf18c007fa6cbdc94f6e --- /dev/null +++ b/.spectral.yaml @@ -0,0 +1,9 @@ +extends: [[spectral:oas, recommended]] +rules: + info-contact: off + + # Disabled due to TypeSpec conversion + oas3-valid-schema-example: off + no-$ref-siblings: off + path-params: off + oas3-unused-component: off diff --git a/.syft.yaml b/.syft.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4c8875c10b63351b0a828a3253d1fb567de9a2a2 --- /dev/null +++ b/.syft.yaml @@ -0,0 +1,7 @@ +select-catalogers: + - -go-module-binary-cataloger + - -github-action-workflow-usage-cataloger + - -github-actions-usage-cataloger + +exclude: + - "./.devenv" diff --git a/.vscode/default.code-workspace b/.vscode/default.code-workspace new file mode 100644 index 0000000000000000000000000000000000000000..bc6ba11fb9ddcf91adb13151b08649ed1744e249 --- /dev/null +++ b/.vscode/default.code-workspace @@ -0,0 +1,12 @@ +{ + "folders": [ + { + "name": "root", + "path": "../" + }, + { + "name": "typespec", + "path": "../api/spec" + } + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000000000000000000000000000000000000..7561443854ec1e53763fa9284b804ae51c90afe4 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,102 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Server", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/server", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + "--stripe-disable-webhook-registration", + ] + }, + { + "name": "Launch Sink-Worker", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/sink-worker", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + // Let's prevent port collision with server + "--telemetry-address", + ":10001", + ] + }, + { + "name": "Launch Balance Worker", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/balance-worker", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + "--telemetry-address", + ":10002" + ] + }, + { + "name": "Launch Notification Service", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/notification-service", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + "--telemetry-address", + ":10003" + ] + }, + { + "name": "Launch recalculate entitlement snapshots", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/jobs", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + "entitlement", + "recalculate-balance-snapshots" + ] + }, + { + "name": "Launch billing-worker Service", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/billing-worker", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + "--telemetry-address", + ":10004", + // force foreground billing advancement strategy, or billing-worker will not start (this way the config can be set to queued to validate that in local dev mode) + "--billing-advancement-strategy=foreground", + ] + }, + { + "name": "Launch periodic jobs", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${workspaceFolder}/cmd/jobs", + "args": [ + "--config", + "${workspaceFolder}/config.yaml", + "billing", + "subscriptionsync", + "list" + ] + }, + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..89299a337fa608f94470f5a12ab2a2d4e01cc387 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,32 @@ +{ + "[helm]": { + "editor.formatOnSave": false + }, + "go.testEnvVars": { + "TZ": "UTC", + "POSTGRES_HOST": "127.0.0.1", + "OPENMETER_ADDRESS": "http://127.0.0.1:38888", + // Useful when the schema is evolving during development (currently only supported + // by billing) + // "TEST_DISABLE_ATLAS": "true" + }, + "gopls": { + "formatting.gofumpt": true + }, + "go.lintTool": "golangci-lint", + "go.lintFlags": [ + "--fast", + "--fix", + "-c", + ".golangci.yaml" + ], + "files.exclude": { + "**/node_modules": false + }, + "typespec.tsp-server.path": "${workspaceFolder}/api/spec/node_modules/@typespec/compiler", + // dynamic forces confluent-kafka-go to build against local librdkafka + // wireinject is kept for gopls so it can analyse wire.go injection files + "go.buildTags": "wireinject,dynamic", + // Tests must NOT include wireinject — it causes wire stubs to run instead of wire_gen.go + "go.testTags": "dynamic" +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..8facb8364619d56b8de4028c181c7a1bd9a00319 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,323 @@ +# OpenMeter + +OpenMeter is a usage metering and billing platform for AI and DevTool companies, built in Go. + +## Quick Reference + +Use the `Makefile` for all common tasks. A `justfile` also exists but is seldom used. +OpenMeter is a metering and billing platform with usage based pricing and access control. + +## Tips for working with the codebase + +If during your work anything confuses you or something isn't trivial for you, please augment AGENTS.md with your findings so next time it will be easier for you. AGENTS.md files are for you to edit and update as you go so you can interact with the codebase the most effectively. + +Development commands are run via `Makefile`, it contains all commonly used commands during development. A `justfile` is also present but seldom used. Use the Makefile commands for common tasks like running tests, generating code, linting, etc. +The committed `.nvmrc` is the GitHub Actions source of truth for Node-based jobs on GitHub-hosted runners. Keep it aligned with the Nix `.#ci` shell's `node -v`; `flake.nix` refreshes it in `enterShell`, and CI validates the file against the Nix shell before running builds. + +## AGENTS.md maintenance + +- Treat this file as long-lived project guidance for all agents and contributors. +- Treat AGENTS.md as the repo-local source of truth. Do not bypass coding style, workflow, testing, or documentation guidance in this file. If a requested change appears to conflict with AGENTS.md, ask the human developer/reviewer to confirm the exception before proceeding, and make the exception explicit in the handoff. +- Prefer durable wording over time-based wording (avoid labels like "recent", "latest", "today"). +- Keep entries actionable and specific (what to do, where, and why), not conversational history. +- Capture universal truths and cross-cutting coding conventions here when they become repeated practice or reviewer expectation. Do not leave them only in chat or pull request comments. +- Capture subsystem-specific guidance in the closest applicable nested `AGENTS.md` when the guidance should always apply to a subtree, such as `api/spec/AGENTS.md` for TypeSpec and SDK guidance. Use skills for reusable workflows or domain procedures that agents opt into for a task. Skills must stay usable by both Claude and Codex: write them as plain repo guidance, keep `.agents/skills` as the source of truth, and avoid assistant-specific assumptions unless a workflow truly requires them. +- When adding new guidance, fold it into the most relevant section and remove/merge stale or duplicate notes. + +## Testing + +| Task | Command | +|------|---------| +| Start dependencies | `make up` | +| Stop dependencies | `make down` | +| Run API server (hot reload) | `make server` | +| Run all tests | `make test` (root module only; excludes `e2e/`, its own module) | +| Run e2e tests | `make etoe` | +| Generate all code | `make generate-all` | +| Generate Go code only | `make generate` (runs `go generate ./...`) | +| Generate API + SDKs | `make gen-api` | +| Lint all | `make lint` | +| Lint Go only | `make lint-go` | +| Format code | `make fmt` | +| Tidy modules | `make mod` (root + `collector` + `e2e`) | +| Build all binaries | `make build` | + +## Architecture + +**Entry points:** `cmd/server`, `cmd/billing-worker`, `cmd/balance-worker`, `cmd/sink-worker`, `cmd/notification-service`, `cmd/jobs` + +Core business logic is in `openmeter/`, shared utilities in `pkg/`, API layer in `api/`. + +**Stack:** Go + PostgreSQL (Ent ORM) + Kafka + ClickHouse. API defined in TypeSpec, generated to OpenAPI. + +Domain packages under `openmeter/` follow a layered service/adapter pattern. See the `/service` skill for full details. + +`cmd/server/main.go` now migrates the database before creating the default namespace. Register namespace handlers before `initNamespace(...)` if they must provision the default namespace during startup. + +**Module layout:** the repo is three separate Go modules. The root module (`github.com/openmeterio/openmeter`) holds all production code (`cmd/`, `openmeter/`, `pkg/`, etc.). `api/v3/client` is the standalone, publishable v3 Go SDK module. `e2e/` is a third, never-published, test-only module that imports both — it pins itself to the working tree of each via `replace github.com/openmeterio/openmeter => ../` and `replace .../api/v3/client => ../api/v3/client`, so e2e always tests local code regardless of what's tagged. The root module must never `require` the SDK module: a `require` on an untagged nested module resolves to an unresolvable `v0.0.0` for anyone outside this repo (the `replace` directive that makes it resolve locally is invisible downstream), so any code that needs the SDK — today, only `e2e/` — has to live in its own module rather than the root one. Because of this, root `go build ./...` / `go test ./...` / `go vet ./...` no longer see `e2e/` at all; use `make etoe` (runs it against a live server) or `go test -C e2e ./...` / `go vet -C e2e ./...` (compiles it standalone, no server needed) instead. `make lint-go` and `make mod` already cover all three modules. For editor/gopls support across all three, run `go work init . ./api/v3/client ./e2e` locally — `go.work`/`go.work.sum` are gitignored and must never be committed. + +### Project Layout + +``` +cmd/ # Service entrypoints +openmeter/ # Core business logic (billing, customer, entitlement, meter, etc.) +openmeter/ent/schema/ # Ent entity definitions (source of truth for DB schema) +openmeter/ent/db/ # Generated ent code (DO NOT EDIT) +api/ # API specs, generated code, SDKs +api/spec/ # TypeSpec API definitions (source of truth for API) +pkg/ # Shared utility packages +tools/migrate/ # Migration tooling and SQL migration files +e2e/ # End-to-end tests +deploy/ # Helm charts +docs/ # Documentation and ADRs +``` + +## Code Generation + +All generated files have `// Code generated by X, DO NOT EDIT.` headers — never edit them manually: + + +| Generated artifact | Source | Regenerate with | +|---|---|---| +| `api/openapi.yaml`, `api/openapi.cloud.yaml` | TypeSpec in `api/spec/` | `make gen-api` | +| `api/client/javascript/`, `api/client/go/` | OpenAPI spec | `make gen-api` | +| `api/v3/client/` (v3 Go SDK, standalone module) | TypeSpec in `api/spec/` via `@openmeter/typespec-go` | `make gen-api` | +| `api/api.gen.go`, `api/v3/api.gen.go` | OpenAPI spec via oapi-codegen | `make gen-api` | +| `api/client/go/client.gen.go` | OpenAPI spec | `make gen-api` | +| `**/ent/db/` | Ent schema in `openmeter/ent/schema/` | `make generate` | +| `**/wire_gen.go` | Wire providers in `**/wire.go` | `make generate` | +| `**/convert.gen.go` | Goverter converter interfaces (`**/convert.go`) | `make generate` | +| `billing/derived.gen.go` | Goderive annotations | `make generate` | +| `tools/migrate/migrations/` | Ent schema diff | `atlas migrate --env local diff ` | + +**Workflow for changing the API:** + +1. Edit TypeSpec files in `api/spec/` +2. Run `make gen-api` to regenerate OpenAPI spec and SDKs +3. Run `make generate` to regenerate Go server/client code + +The TypeSpec JS client emitted from `api/spec/packages/aip` now lands in `api/spec/packages/aip-client-javascript/`. The emitter regenerates `src/`, `README.md`, and five conformance test files (`tests/client.spec.ts`, `tests/meters.spec.ts`, `tests/errors.spec.ts`, `tests/nesting.spec.ts`, `tests/internal.spec.ts`); every regenerated file carries a `Code generated by @openmeter/typespec-typescript. DO NOT EDIT.` header — treat files without that header as hand-written. `package.json` is **stable, hand-maintained, and committed** (the emitter's `writeOutput` only writes the paths it lists, so the manifest survives regeneration). The test suite is vitest + `@fetch-mock/vitest`; keep hand-written tests and helpers in `tests/` (never `src/`), and put test-runner dependencies/scripts in the `api/spec/package.json` workspace root rather than the client package manifest. Static publish metadata (`name`, `license`, `homepage`, `repository`) lives directly in the client `package.json`; only the per-release `version` is injected at publish time. Operations marked `x-internal` or `x-private` in the TypeSpec source are emitted but quarantined under `client.internal..` (`src/sdk/internal.ts`, an `Internal` aggregate with `Internal` facade classes; internal ops share their group's `funcs/` and `models/operations/` modules, a group whose ops are all internal gets no public facade, and the `Internal` class is deliberately not re-exported from the package root — the name belongs to the Internal Server Error model). Removing an operation from the spec leaves stale generated files behind — the emitter never deletes outputs, so `git rm` them (and `rm` the gitignored `*.assert.ts` companions, which `git rm` cannot clean up on collaborators' checkouts). + +The emitted `api/spec/packages/aip-client-javascript/src/sdk/sdk.ts` exposes aggregated sub-client getters on the `OpenMeter` class (e.g. `events`, `meters`, `customers`, `entitlements`, `subscriptions`, `billing`, `features`, `plans`, `addons`, `planAddons`, `tax`, `defaults`). Access operations through those getters, e.g. `sdk.meters.list()`, `sdk.customers.create(...)`, `sdk.plans.create(...)`. These grouped-client methods throw `HTTPError` on failure; the same operations are also available as tree-shakeable standalone functions under `src/funcs/` that return a `Result` instead of throwing. + +**Workflow for changing Go types/DI:** + +1. Edit the source files (ent schema, wire.go, converter interfaces) +2. Run `make generate` (or `go generate ./...`) + +## Database Migrations + +Uses [ent](https://entgo.io) for schema definition and [Atlas](https://atlasgo.io/) for migration generation. Migrations are in `tools/migrate/migrations/` using golang-migrate format. + +**Schema files:** `openmeter/ent/schema/*.go` + +**Workflow for schema changes:** + +1. Edit the ent schema in `openmeter/ent/schema/` +2. Run `make generate` to regenerate ent code in `openmeter/ent/db/` +3. Generate migration: `atlas migrate --env local diff ` + - This creates timestamped `.up.sql` / `.down.sql` files in `tools/migrate/migrations/` + - Also updates `tools/migrate/migrations/atlas.sum` +4. Versioned migrations run automatically on startup when `postgres.autoMigrate` is set to `migration`; runtime Ent migration is not supported + +**Ent view caveat:** in this repo's current Ent/Atlas setup, schemas declared with `ent.View` can generate query code under `openmeter/ent/db/`, but they do not appear in `openmeter/ent/db/migrate/schema.go` or the generated `migrate.Tables` list. If `atlas migrate --env local diff ...` reports no changes for a new view, verify whether the view exists in generated migration metadata before debugging Atlas; view DDL may need an explicit SQL migration until generator support is added. + +**Atlas config:** `atlas.hcl` — schema source is `ent://openmeter/ent/schema`, migrations dir is `file://tools/migrate/migrations`. + +**Local Postgres:** `postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable` + +Runtime Ent schema migration is not supported. `postgres.autoMigrate: ent` must fail validation; use `migration`, `migration-job`, or `false`. `openmeter-jobs migrate adopt-ent` contains a frozen compatibility bridge for databases created by Ent before migration baseline `20260709134422`; it stops at that baseline, after which `openmeter-jobs migrate` performs the normal target-version upgrade. Keep the frozen descriptors and reconciliation scripts under `tools/migrate/legacyent` independent from current Ent generation so later schema changes cannot alter the adoption baseline. Ent and Atlas can derive different names for equivalent indexes and constraints, so reconciliation must preserve the canonical Atlas names and `TestLegacyEntAdoptionSchemaParity` must continue comparing the adopted database with a from-scratch Atlas database. + +## Testing + +Tests require PostgreSQL running locally. Start it with `docker compose up -d postgres`. + +Keep domain test helpers under `openmeter/.../testutils` independent from `app/common`. Build test dependencies from the underlying package constructors (repos, adapters, services, `lockr`) instead of importing the application wiring layer, or unrelated wiring additions can create test-only import cycles. + +For usage-based billing lifecycle tests, prefer driving behavior through `charges.Service.Create`, `AdvanceCharges`, and `ApplyPatches` rather than calling lower-level charge adapters directly. To model late-arriving or newly visible usage, use `MockStreamingConnector` events with explicit `StoredAt` values (or `SetSimpleEvents`) so the test exercises the real stored-at cutoff logic in finalization. + +For OpenMeter Go tests that touch the database, explicitly set `POSTGRES_HOST=127.0.0.1`. Without it, many suites will skip during setup even if PostgreSQL is running and the repo environment is otherwise loaded correctly. + +Use the repo's Nix CI dev shell when `go`, `gofmt`, or other toolchain binaries are missing from the ambient shell. The CI and local-compatible invocation pattern is: + +```bash +nix develop --impure .#ci -c +``` + +Always invoke `nix develop` with the repo root as the working directory (use absolute paths in `` instead of `cd`-ing first). The devenv `enterShell` writes CWD-relative state: run from a subdirectory it drops `.devenv/`, `.nvmrc`, and `.pre-commit-config.yaml` there (which then fail `prettier --check` in lint) and reinstalls the git pre-commit hook with that subdirectory's config path baked in, breaking later commits until a root-CWD `nix develop` run repairs it. + +Codex's default shell may not auto-load `.envrc`, so `direnv`-managed tools like `go` can be missing even when the repo is configured correctly. In that case, run commands through `nix develop --impure .#ci -c ...` explicitly instead of assuming the ambient shell reflects the flake environment. `direnv exec . ` is also a valid one-off fallback when `direnv` is installed and the repo has already been allowed. + +When invoking commands through Codex tools, prefer direct command execution. Do not wrap commands in `sh -lc`, `bash -lc`, or other helper shells when the command can be run directly. For environment variables, prefer `env KEY=value ` or `KEY=value ` over shell-wrapped forms. This keeps failures attributable to the actual toolchain/runtime being tested. + +In tests, prefer `t.Context()` when a `testing.T` or `testing.TB` is available instead of introducing `context.Background()`. This keeps cancellation and test-scoped lifecycle tied to the test harness. + +Prefer one consistent test harness style over mixed ad hoc structures. Use production-backed paths, such as rating-backed or service-backed fixtures, when the real path can express the scenario; keep hand-assembled fixtures for cases that cannot be produced realistically. If a behavior is a suite-wide rule, hardcode it into the shared harness instead of exposing it as per-test knobs. + +Avoid redundant test helpers and duplicate setup paths. Prefer parameterizing one helper over maintaining near-identical helpers, use literal helper names that state exactly what they do, and inline single-use helpers that only wrap setup, conversion, or assertions even when the test becomes longer. Add a test helper only when it is used by at least two tests in the same package or when the helper name captures non-obvious domain semantics that would otherwise be easy to miss. Clean up dead test helpers immediately after refactors. + +For service and lifecycle subtests, start each subtest body with concise intent comments when the scenario is non-trivial: + +```go +// given: +// - ... +// when: +// - ... +// then: +// - ... +``` + +When using `clock.FreezeTime(...)` in tests, immediately pair it with `defer clock.UnFreeze()` in the same scope so later assertions or subtests do not inherit frozen time accidentally. + +When asserting `alpacadecimal.Decimal` equality in tests, prefer `require.Equal(t, expectedFloat64, actual.InexactFloat64())` over boolean assertions like `require.True(t, expected.Equal(actual))` when precision requirements allow it. Prefer simple `float64(5)`-style literals over verbose decimal construction for expected values. Inline one-off expected balance structs at the assertion site; name expected balances only when reused or when the name carries useful phase semantics across subtests. + +After each meaningful test-related change, run focused `go vet` and focused `go test` for the touched package. + +Examples: + +```bash +nix develop --impure .#ci -c gofmt -w openmeter/ledger/historical/entry.go +nix develop --impure .#ci -c make lint-go +nix develop --impure .#ci -c env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic ./openmeter/ledger/historical/... +``` + +| Command | Description | +|---------|-------------| +| `make test` | Run all tests (parallel: `-p 128 -parallel 16`) | +| `make test-nocache` | Run tests bypassing cache | +| `make test-all` | Run tests including Svix/Redis dependencies | +| `make test-go-sdk` | Build, vet, and test the v3 Go SDK module (`api/v3/client`) | +| `make etoe` | Run e2e tests (requires docker compose dependencies) | + +**Running a single package directly:** + +```bash +POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -v ./openmeter/billing/... +``` + +Key flags: `-tags=dynamic` (required for confluent-kafka-go), `-p 128 -parallel 16` (used by Make). Set `POSTGRES_HOST=127.0.0.1` or tests requiring Postgres will be skipped. `e2e/` is its own module and its import graph never reaches confluent-kafka-go, so `-tags=dynamic` is not needed there — `go test -C e2e ./...` (or `TZ=UTC OPENMETER_ADDRESS=... go test -C e2e ./...`) is enough. + +See the `/test` skill for testing patterns, TestEnv setup, and examples. + +## Building + +```bash +make build # All binaries → build/ +make build-server # Just the server +``` + +All builds use `GO_BUILD_FLAGS=-tags=dynamic`. + +## Configuration + +- Copy `config.example.yaml` to `config.yaml` (done automatically by Make targets) +- Load the repository environment with `direnv`, or run commands with `direnv exec . `, so project-specific environment variables and tool configuration are applied consistently +- Key settings: `postgres.url`, `postgres.autoMigrate`, `billing`, `notification`, meter definitions +- `credits.enabled` needs explicit guarding at multiple layers: ledger-backed customer credit handlers in `api/v3/server`, customer ledger hooks, and namespace/default-account provisioning are wired separately and must each stay disabled when credits are off. +- When `credits.enabled` is `false`, `app/common` wires ledger account services/resolvers to noop implementations. Any ledger account backfill that must write real `ledger_accounts` / `ledger_customer_accounts` rows needs to construct concrete ledger account + resolver adapters directly instead of relying on the default DI outputs. +- Make targets for running services will warn if `config.yaml` is outdated vs `config.example.yaml` + +## Coding Conventions + +See the `/service` skill for service/adapter patterns, constructors, input types, errors, transactions, hooks, logging, multi-tenancy, and DI wiring. See the `/api` skill for HTTP handler patterns and ValidationIssue. See the `/ent` skill for Ent ORM patterns and Postgres type gotchas. See the `/ledger` skill for ledger package architecture, wiring, and testing. See the `/subscription` skill for subscription domain model, sync algorithm, patch system, workflow layer, and addon sub-system. See the `/notification` skill for notification event pipeline, Kafka consumers, Svix webhook delivery, reconciliation loop, and payload versioning. + +For TypeSpec-specific coding constraints, update `api/spec/AGENTS.md` instead of adding them here. + +### Documentation Constraints + +- When adding comments or docstrings, document intent and domain constraints that are only available from human author context, not facts a reader can infer by reading the codebase. Avoid comments that merely translate obvious conditions, such as saying that a branch runs when `servicePeriod > 0`. A good comment should be understandable without the author's chat context and should explain why the code deliberately includes or excludes a case. For fallback or guard comments, name the concrete input shape or lifecycle state, the invariant being protected, the chosen behavior, and what would go wrong if the guard or fallback were removed. Avoid vague phrases like "can still arrive" or "as needed". +- Add a docstring to domain helpers when the name compresses important business semantics that are easy to misread at call sites. Explain the observable business contract and why excluded cases are excluded, not the implementation mechanics. +- When refactoring or reverting code, preserve existing explanatory comments by default. Remove or rewrite a comment only when the code change makes it false, stale, or misleading. + +### Go Style Constraints + +- For Go string enum constants, name values as `` so the constant carries its enum type at the use site, for example `InvoiceStatusDraft` instead of `Draft`. +- Do not extract helper functions only to hide a couple of simple operations or short guard checks. If the helper would only wrap 2-4 lines and its name does not add meaningful domain or business intent, keep the code inline even when there is some duplication. Readers can inspect the function body to see what the code does; prefer function names that explain the domain reason for the call over names that merely restate the implementation steps. When you encounter a leftover pass-through wrapper that only calls another function without adding behavior, remove it and call the underlying function directly, even if it is outside the immediate change area. +- Do not hide non-trivial branching or domain translation inside local inline functions. If a closure performs type switching, validation, persistence mapping, or meaningful domain conversion, make it a named helper near the code that uses it so it is discoverable, testable, and grep-friendly. Reserve inline closures for tiny callbacks where the surrounding API requires a function literal and the logic is obvious at the call site. +- For `Validate() error` methods, prefer collecting all validation issues into `var errs []error` and returning `models.NewNillableGenericValidationError(errors.Join(errs...))` instead of returning on the first invalid field. Preserve field context with wrapped errors like `fmt.Errorf("field: %w", err)` and use plain `errors.New(...)` for simple local checks. +- Do not introduce `context.Background()` or `context.TODO()` to sidestep missing context propagation in application code. Either propagate the caller's context through the full call path, or remove the unused `context.Context` parameter from the API if the operation is purely local and does not need cancellation, deadlines, or request-scoped values. +- Never use `panic` in non-test code paths. If a new failure mode is possible, change the function signature to return an error and propagate it explicitly. +- In production constructors and initialization, do not use `slog.Default()` as a fallback dependency. Require a `*slog.Logger` in config/provider inputs and inject it explicitly. +- Prefer standard library `slices` and `maps` helpers for common collection operations, and use `github.com/samber/lo` when it makes pointer literals or collection transformations clearer than local wrappers or hand-written loops. See the `/samber-lo` skill for common OpenMeter use cases and caveats. Do not add local wrappers such as `ptr`, `loPtr`, `must`, or `loMust` when standard helpers or `lo` already cover the need. +- Use repo helper packages when they capture a common pattern better than ad hoc closures. For example, use `pkg/slicesx` for existing slice helpers (but prefer `samber/lo` and `slices` system packages if they fit), and use `pkg/syncx.OnceValues` for lazy context-aware database lookups that may be needed by multiple callbacks but should execute at most once. +- Keep helper functions honest and narrow. If a production helper is only called once and is just a short guard or a few straightforward lines, inline it unless the name carries meaningful domain semantics. Do not add helpers for trivial single-use struct literals, do not hide aggregate mutation inside construction helpers, and return the domain value a helper actually builds rather than a broader wrapper needed by one caller. +- For files and functions that convert between domain, API, and DB representations, use the `/go-types-conversion` skill. In prose, prefer `map` / `mapped` terminology for domain representation translation and avoid `project` / `projected` for that meaning; function names must still follow the skill's `FromAPI...`, `ToAPI...`, `FromDB...`, and `ToDB...` conventions. + +### Generation And Dependency Constraints + +- When `make generate` or `atlas migrate --env local diff ...` adds incidental `go.sum` entries, such as `tablewriter`, drop those `go.sum` changes unless the task explicitly requires a dependency change. + +## Key Dependencies + +| Category | Libraries | +|----------|-----------| +| DB | PostgreSQL (Ent ORM, Atlas migrations, pgx driver) | +| Analytics | ClickHouse | +| Events | Kafka (confluent-kafka-go) + Watermill | +| HTTP | Chi router + oapi-codegen | +| Invoicing | GOBL (invoice format) | +| Webhooks | Svix | +| Observability | OpenTelemetry | +| Config | Viper + Cobra | +| Utilities | samber/lo | + +## CodeGraph + +CodeGraph builds a semantic knowledge graph of the codebase (~1,800 Go files, ~36k symbols) for faster, smarter code exploration. The index lives in `.codegraph/codegraph.db` (gitignored). Generated files (`ent/db/`, `*_gen.go`, `wire_gen.go`, `*.gen.go`) are excluded. + +### If `.codegraph/` exists + +**Default to CodeGraph, not Grep/Glob/find.** CodeGraph understands symbols, call relationships, and file structure — those tools return string matches. On a ~1,800-file Go codebase the symbol-aware answer is almost always what you wanted. Fall back to Grep/Glob **only** when CodeGraph returns no results or the query is inherently textual (string literals, comments, log messages, SQL, YAML keys). + +**Never call `codegraph_explore` or `codegraph_context` in the main session.** These tools return large source code blocks that fill up main-session context fast. Instead, spawn an Explore agent for any exploration question (e.g., "how does billing sync work?", "where is entitlement reset implemented?"). + +When spawning Explore agents, include this instruction in the prompt: + +> This project has CodeGraph initialized (.codegraph/ exists). Use `codegraph_explore` as your PRIMARY exploration tool — it returns full source code sections from all relevant files in one call. +> +> **Rules:** +> 1. Follow the explore call budget in the `codegraph_explore` tool description — it scales automatically based on project size. +> 2. Do NOT re-read files that `codegraph_explore` already returned source code for. The source sections are complete and authoritative. +> 3. Only fall back to Grep/Glob/Read for files listed under "Additional relevant files" if you need more detail, or if CodeGraph returned no results. + +**The main session should use these lightweight tools directly** for targeted lookups before making edits: + +| Tool | Use for | Example | +|------|---------|---------| +| `codegraph_search` | Find symbols by name | `query: "BillingService"` | +| `codegraph_callers` | Who calls this function? | Before renaming or changing a signature | +| `codegraph_callees` | What does this function call? | Understanding a function's dependencies | +| `codegraph_impact` | Blast radius of a change | Before refactoring a shared type | +| `codegraph_node` | Single symbol details | Quick check on a struct or interface | +| `codegraph_files` | Project file tree | Faster than Glob for directory overviews | +| `codegraph_status` | Index health check | Verify the index is up to date | + +### Choosing CodeGraph vs Grep/Glob + +| Task | Prefer | Reason | +|------|--------|--------| +| "Where is `BillingService` defined?" | `codegraph_search` | Symbol lookup with location + signature | +| "Who calls `ListCustomers`?" | `codegraph_callers` | Call-graph edges, not text matches | +| "What does `Reconcile` call?" | `codegraph_callees` | Dependencies of a function | +| "Blast radius of changing this type?" | `codegraph_impact` | Transitive reverse-deps | +| "Show the `Filter` interface fields" | `codegraph_node` | Single-symbol detail without reading whole file | +| "List files under `api/v3/filters/`" | `codegraph_files` | Indexed tree; no disk walk | +| Find a string literal / log message / SQL fragment | `Grep` | Not a symbol | +| Find files by glob pattern (`**/*.tsp`) | `Glob` | CodeGraph indexes Go; non-Go globs go through Glob | +| Navigate a specific known path | `Read` | Direct reads are always fine | +| Running `find` on the shell | Don't | Use `codegraph_files` or `Glob` | +| Running `grep`/`rg` on the shell | Don't | Use `Grep` (or `codegraph_search` for symbols) | + +Rule of thumb: **if the target is a Go identifier, start with CodeGraph. If it's a string, start with Grep.** Never shell out to `grep`, `rg`, or `find` — the dedicated tools (`Grep`, `Glob`, `codegraph_*`) give better output and permission handling. + +### Keeping the index fresh + +At the start of work, refresh CodeGraph before exploring Go code. If `.codegraph/` exists, run `codegraph sync`; if it does not exist, run `codegraph init -i` without asking first. Run `codegraph index` for a full rebuild if the index seems stale or after branch switches. + +### If `.codegraph/` does NOT exist + +Initialize it with `codegraph init -i` before doing code exploration. It indexes the Go codebase quickly and keeps symbol-aware lookup available. + +## Skills + +Skills are created inside [.agents/skills](.agents/skills/) by default and then symlinked to [.claude/skills](.claude/skills). Make sure you always treat `.agents/skills` as the source of truth. Keep skill guidance compatible with both Claude and Codex; avoid instructions that assume only one agent runtime unless the skill is explicitly about that runtime. diff --git a/Agent.md b/Agent.md new file mode 100644 index 0000000000000000000000000000000000000000..ad6d7a8de703eff44e5268a83c0b9650d238bfca --- /dev/null +++ b/Agent.md @@ -0,0 +1,148 @@ +# Hugging Face Space Deployment Agent Guide + +This file outlines the deployment configuration, API exposure, and deployment workflow for OpenMeter on Hugging Face Spaces. + +## 1. Deployment Configuration + +### Target Space +- **Profile:** `Leon4gr45` +- **Space:** `openmeter` +- **Full Identifier:** `Leon4gr45/openmeter` +- **Frontend Port:** `7860` (mandatory for all Hugging Face Spaces) + +### Deployment Method +Choose the correct SDK based on the app type based on the codebase language: +- **Docker SDK** is used for OpenMeter (as a Go application). + +### HF Token +- The environment variable `HF_TOKEN` must be set to your Hugging Face Space token at execution time (never hardcode the token). +- All monitoring, upload, and log-streaming commands rely on this token. + +### Required Files +- `Dockerfile` (packaged to run with the mock server enabled for space readiness) +- `README.md` with Hugging Face YAML frontmatter specifying: + ```yaml + --- + title: Openmeter + sdk: docker + app_port: 7860 + --- + ``` +- `.hfignore` to exclude unnecessary files. +- `Agent.md` (this file, committed before deployment). + +--- + +## 2. API Exposure and Documentation + +### Mandatory Endpoints +Every deployment **must** expose: + +- **`/health`** + - Returns HTTP 200 `OK` (plain text or JSON) when the app is ready. + - Required for Hugging Face to transition the Space from *starting* → *running*. + +- **`/api-docs`** + - Documents **all** available API endpoints. + - Must be reachable at: + `https://Leon4gr45-openmeter.hf.space/api-docs` + +--- + +### Functional Endpoints + +The mock server exposed in this space implements the following critical OpenMeter functional endpoints (all of which are documented in `/api-docs` via `/api/swagger.json`): + +#### 1. Ingest Events +- **Method:** POST +- **Path:** `/api/v1/events` +- **Purpose:** Ingest event data in CloudEvents format. +- **Request Example:** + ```json + { + "specversion": "1.0", + "type": "request", + "id": "00001", + "time": "2026-07-07T00:00:00.001Z", + "source": "my-service", + "subject": "customer-1", + "data": { "method": "GET", "route": "/api/hello" } + } + ``` +- **Response Example:** + ```json + { + "status": "accepted" + } + ``` + +#### 2. List Meters +- **Method:** GET +- **Path:** `/api/v1/meters` +- **Purpose:** List all configured usage meters. +- **Request:** (None) +- **Response Example:** + ```json + [ + { + "id": "api_requests_total", + "slug": "api_requests_total", + "description": "API Requests", + "eventType": "request", + "aggregation": "COUNT" + }, + { + "id": "tokens_total", + "slug": "tokens_total", + "description": "AI Token Usage", + "eventType": "prompt", + "aggregation": "SUM" + } + ] + ``` + +#### 3. Query Meter Usage +- **Method:** GET +- **Path:** `/api/v1/meters/{meterIdOrSlug}/query` +- **Purpose:** Query usage data for a specific meter. +- **Request Parameters:** `windowSize=HOUR` +- **Response Example:** + ```json + { + "data": [ + { + "value": 150, + "windowStart": "2026-07-07T00:00:00Z", + "windowEnd": "2026-07-07T01:00:00Z" + } + ] + } + ``` + +--- + +## 3. Deployment Workflow + +Precondition: Check that the space is empty of files and delete any which are still in there and not belonging to the project to be uploaded. + +### Standard Deployment Command +After any code change, run: + +```bash +HF_TOKEN= hf upload Leon4gr45/openmeter . . --repo-type=space +``` + +### Scan build and run logs +Get build logs (SSE): +```bash +curl -N -H "Authorization: Bearer " "https://huggingface.co/api/spaces/Leon4gr45/openmeter/logs/build" +``` + +Get run logs (SSE) once the build logs succeed: +```bash +curl -N -H "Authorization: Bearer " "https://huggingface.co/api/spaces/Leon4gr45/openmeter/logs/run" +``` + +Cycle monitoring and deployment: +- Wait up to 300 seconds to see if the deployment has been successful. +- If not, check logs for errors, fix the issues in the codebase, redeploy, and monitor again in a cycle until the space is running and reacts successfully to API endpoints. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000000000000000000000000000000000..f5a12da66a2f5da0117156b54899ae9c28bb80f9 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# OpenMeter Development Guide + +See consolidated agents instructions in @AGENTS.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..10b45b15c65d9c3e17338018997c45ba9ddcb3c2 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,68 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, +we as contributors and maintainers pledge to make participation in our project +and our community a harassment-free experience for everyone, regardless of age, +body size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior +and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, +or reject comments, commits, code, wiki edits, issues, +and other contributions that are not aligned to this Code of Conduct, +or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, +and it also applies when an individual is representing the project or its community in public spaces. +Examples of representing a project or community include using an official project e-mail address, +posting via an official social media account, or acting as an appointed representative at an online or offline event. +Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [conduct@openmeter.io][conduct-email]. +All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. +The project team is obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary +or permanent repercussions as determined by other members of the project's leadership. + +[conduct-email]: mailto:conduct@openmeter.io + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..7ee0bd2d1cf23c3b255c3bb7c26da786ce5c0852 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# Contributing + +Thanks for your interest in contributing to OpenMeter! + +Here are a few general guidelines on contributing and reporting bugs that we ask you to review. +Following these guidelines helps to communicate that you respect the time of the contributors managing and developing this open source project. +In return, they should reciprocate that respect in addressing your issue, assessing changes, and helping you finalize your pull requests. +In that spirit of mutual respect, we endeavor to review incoming issues and pull requests within 10 days, +and will close any lingering issues or pull requests after 60 days of inactivity. + +Please note that all of your interactions in the project are subject to our [Code of Conduct](/CODE_OF_CONDUCT.md). +This includes creation of issues or pull requests, commenting on issues or pull requests, +and extends to all interactions in any real-time space e.g., Slack, Discord, etc. + +## Reporting issues + +Before reporting a new issue, please ensure that the issue was not already reported or fixed by searching through our issue tracker. + +When creating a new issue, please be sure to include a **title and clear description**, as much relevant information as possible, and, if possible, a test case. + +**If you discover a security bug, please do not report it through GitHub issues. Instead, please see security procedures in [SECURITY.md](/SECURITY.md).** + +## Sending pull requests + +Before sending a new pull request, take a look at existing pull requests and issues to see if the proposed change or fix has been discussed in the past, +or if the change was already implemented but not yet released. + +We expect new pull requests to include tests for any affected behavior, and, as we follow semantic versioning, +we may reserve breaking changes until the next major version release. + +### Ensuring All Requested Reviewers Approve + +By default, pull requests can often be merged once the minimum number of required approvals (e.g., from CODEOWNERS or branch protection rules) is met. However, sometimes you might explicitly request reviews from specific individuals because their input is crucial for that particular PR. + +To ensure that *all* individuals you've specifically requested using the GitHub "Reviewers" UI must approve before merging, follow these steps: + +1. **Request Reviews:** Use the standard GitHub interface on the pull request page to request reviews from the necessary individuals. +2. **Add Label:** Add the label `require-all-reviewers` to the pull request. + +When this label is present, an automated check named "Review Gatekeeper" will run. This check will only pass if **every single user** listed under the "Reviewers" section has submitted an **approving** review. This check is required for merging, preventing merges until all explicitly requested reviewers are satisfied. + +If the label is removed, the "Review Gatekeeper" check will be skipped. + +## Other ways to contribute + +We welcome anyone that wants to contribute to triage and reply to open issues to help troubleshoot and fix existing bugs. +Here is what you can do: + +- Help ensure that existing issues follows the recommendations from the _[Reporting Issues](#reporting-issues)_ section, + providing feedback to the issue's author on what might be missing. +- Review and update the existing content of our [documentation](https://openmeter.io) with up-to-date instructions and code samples. +- Review existing pull requests, and testing patches against real existing applications. +- Write a test, or add a missing test case to an existing test. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..37d0949970f51e070a58fba8878e4e3b8de9e771 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,98 @@ +FROM --platform=$BUILDPLATFORM tonistiigi/xx:1.9.0@sha256:c64defb9ed5a91eacb37f96ccc3d4cd72521c4bd18d5442905b95e2226b0e707 AS xx + +FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine3.23@sha256:18b460dd17542c2ba43299a633cf6ebfc1115101509531471d7cfce1019af083 AS builder + +COPY --link --from=xx / / + +RUN xx-apk add --update --no-cache ca-certificates make git curl clang lld + +ARG TARGETPLATFORM + +RUN xx-apk --update --no-cache add musl-dev gcc + +WORKDIR /src + +ARG GOPROXY + +ENV CGO_ENABLED=1 + +ENV GOCACHE=/go/cache +ENV GOMODCACHE=/go/pkg/mod + +COPY --link go.mod go.sum ./ + +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go mod download -x + +ARG VERSION + +COPY --link . . + +RUN chmod +x entrypoint.sh + +# See https://github.com/confluentinc/confluent-kafka-go#librdkafka +# See https://github.com/confluentinc/confluent-kafka-go#static-builds-on-linux +# Build server binary (default) +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go build -ldflags "-linkmode external -extldflags \"-static\" -X main.version=${VERSION}" -tags musl -o /usr/local/bin/openmeter ./cmd/server + +RUN xx-verify /usr/local/bin/openmeter + +# Build sink-worker binary +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go build -ldflags "-linkmode external -extldflags \"-static\" -X main.version=${VERSION}" -tags musl -o /usr/local/bin/openmeter-sink-worker ./cmd/sink-worker + +RUN xx-verify /usr/local/bin/openmeter-sink-worker + +# Build balance-worker binary +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go build -ldflags "-linkmode external -extldflags \"-static\" -X main.version=${VERSION}" -tags musl -o /usr/local/bin/openmeter-balance-worker ./cmd/balance-worker + +RUN xx-verify /usr/local/bin/openmeter-balance-worker + +# Build notification-service binary +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go build -ldflags "-linkmode external -extldflags \"-static\" -X main.version=${VERSION}" -tags musl -o /usr/local/bin/openmeter-notification-service ./cmd/notification-service + +RUN xx-verify /usr/local/bin/openmeter-notification-service + +# Build billing-worker binary +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go build -ldflags "-linkmode external -extldflags \"-static\" -X main.version=${VERSION}" -tags musl -o /usr/local/bin/openmeter-billing-worker ./cmd/billing-worker + +RUN xx-verify /usr/local/bin/openmeter-billing-worker + +# Build periodic jobs binary +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/go/cache \ + xx-go build -ldflags "-linkmode external -extldflags \"-static\" -X main.version=${VERSION}" -tags musl -o /usr/local/bin/openmeter-jobs ./cmd/jobs + +RUN xx-verify /usr/local/bin/openmeter-jobs + +FROM alpine:3.24.1@sha256:28bd5fe8b56d1bd048e5babf5b10710ebe0bae67db86916198a6eec434943f8b + +ENV MOCK_SERVER=true +ENV PORT=7860 + +RUN apk add --update --no-cache ca-certificates tzdata bash + +SHELL ["/bin/bash", "-c"] + +COPY --link --from=builder /usr/local/bin/openmeter /usr/local/bin/ +COPY --link --from=builder /usr/local/bin/openmeter-sink-worker /usr/local/bin/ +COPY --link --from=builder /usr/local/bin/openmeter-balance-worker /usr/local/bin/ +COPY --link --from=builder /usr/local/bin/openmeter-notification-service /usr/local/bin/ +COPY --link --from=builder /usr/local/bin/openmeter-billing-worker /usr/local/bin/ +COPY --link --from=builder /usr/local/bin/openmeter-jobs /usr/local/bin/ +COPY --link --from=builder /src/go.* /usr/local/src/openmeter/ +COPY --link --from=builder /src/entrypoint.sh /entrypoint.sh + +ENTRYPOINT ["/entrypoint.sh"] + +CMD openmeter diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..88d844f864a0cfb32dac528e4abda7dbea6cff3d --- /dev/null +++ b/Makefile @@ -0,0 +1,356 @@ +# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html + +ROOT_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) + +# Docker-local svix secret, only used for testing +SVIX_JWT_SECRET = DUMMY_JWT_SECRET + +# dynamic forces confluent-kafka-go to build against local librdkafka +GO_BUILD_FLAGS = -tags=dynamic +GO_TEST_PACKAGE_PARALLELISM ?= 128 +GO_TEST_FLAGS = -p ${GO_TEST_PACKAGE_PARALLELISM} -parallel 16 ${GO_BUILD_FLAGS} +GOTESTSUM_FLAGS ?= --format pkgname-and-test-fails --hide-summary=skipped +GO_LINT_PATH ?= ./... + +.PHONY: up +up: ## Start the dependencies via docker compose. `export COMPOSE_PROFILES=dev,redis,...` + $(call print-target) + docker compose up -d + +.PHONY: down +down: ## Stop the dependencies via docker compose + $(call print-target) + docker compose down --remove-orphans --volumes + +.PHONY: patch-oapi-templates +patch-oapi-templates: ## Patch oapi-codegen chi-middleware template with custom filter parsing + $(call print-target) + @go mod download github.com/oapi-codegen/oapi-codegen/v2 + @OAPI_MOD_DIR=$$(go list -m -f '{{.Dir}}' github.com/oapi-codegen/oapi-codegen/v2) && \ + if [ -z "$$OAPI_MOD_DIR" ]; then echo "error: could not locate oapi-codegen/v2 module dir"; exit 1; fi && \ + cp "$$OAPI_MOD_DIR/pkg/codegen/templates/chi/chi-middleware.tmpl" api/v3/templates/chi-middleware.tmpl && \ + chmod u+w api/v3/templates/chi-middleware.tmpl && \ + patch -p1 -d api/v3/templates < api/v3/templates/chi-middleware.tmpl.patch + +.PHONY: update-openapi +update-openapi: patch-oapi-templates ## Update OpenAPI spec + $(call print-target) + $(MAKE) -C api/spec generate + go generate ./api/... + +.PHONY: generate-javascript-sdk +generate-javascript-sdk: ## Generate JavaScript SDK + $(call print-target) + $(MAKE) -C api/client/javascript generate + +.PHONY: gen-api +gen-api: update-openapi generate-javascript-sdk ## Generate API and SDKs + $(call print-target) + +.PHONY: generate-all +generate-all: update-openapi generate-javascript-sdk ## Execute all code generators + $(call print-target) + go generate ./... + +.PHONY: migrate-check +migrate-check: migrate-check-schema migrate-check-diff migrate-check-lint migrate-check-validate ## Validate migrations + +.PHONY: migrate-check-schema +migrate-check-schema: ## Ensure ent schema is in sync with generated code + $(call print-target) + go generate -x ./openmeter/ent/... + @if ! git diff --quiet -- openmeter/ent || [ -n "$$(git ls-files --others --exclude-standard -- openmeter/ent)" ]; then \ + git --no-pager diff -- openmeter/ent; \ + git ls-files --others --exclude-standard -- openmeter/ent; \ + echo "!!! schema is not in sync with generated code — run 'go generate ./openmeter/ent/...' and commit the changes !!!"; \ + exit 1; \ + fi + +.PHONY: migrate-check-diff +migrate-check-diff: ## Ensure migrations are in sync with schema (runs atlas migrate diff against a clean target) + $(call print-target) + atlas migrate --env local diff migrate-check >/dev/null + @if ! git diff --quiet -- tools/migrate/migrations || [ -n "$$(git ls-files --others --exclude-standard -- tools/migrate/migrations)" ]; then \ + git --no-pager diff -- tools/migrate/migrations; \ + git ls-files --others --exclude-standard -- tools/migrate/migrations; \ + echo "!!! migrations are not in sync with schema — run 'atlas migrate --env local diff ' and commit the generated files !!!"; \ + exit 1; \ + fi + +.PHONY: migrate-check-lint +migrate-check-lint: ## Lint the last 10 migrations + $(call print-target) + atlas migrate --env local lint --latest 10 + +.PHONY: migrate-check-validate +migrate-check-validate: ## Validate migration checksums + $(call print-target) + atlas migrate --env local validate + +.PHONY: generate-sqlc-testdata +generate-sqlc-testdata: ## Generate SQLC testdata for a specific version (make generate-sqlc-testdata VERSION=20240826120919) + $(call print-target) + @if [ -z "$(VERSION)" ]; then echo "Usage: make generate-sqlc-testdata VERSION="; exit 1; fi + VERSION=$(VERSION) ./tools/migrate/generate-sqlc-testdata.sh + +.PHONY: generate +generate: patch-oapi-templates ## Generate code + $(call print-target) + go generate ./... + +.PHONY: generate-view-sql +generate-view-sql: ## Generate SQL for ent.View schemas + $(call print-target) + go run ./tools/migrate/cmd/viewgen + +.PHONY: build-dir +build-dir: + @mkdir -p build + +.PHONY: build +build: build-server build-sink-worker build-benthos-collector build-balance-worker build-billing-worker build-notification-service build-jobs ## Build all binaries + +COLLECTOR_DIR := $(ROOT_DIR)/collector +COLLECTOR_RELEASE_OUTPUT_DIR := $(ROOT_DIR)/build/release/benthos-collector_$(GOOS)_$(GOARCH) + +collector-release-output-dir: + $(if $(GOOS),,$(error GOOS is not set)) + $(if $(GOARCH),,$(error GOARCH is not set)) + @mkdir -p $(COLLECTOR_RELEASE_OUTPUT_DIR) + +# Cross-compile the benthos-collector binary for release archives. +# Usage: make build-benthos-collector-release GOOS=linux GOARCH=amd64 VERSION=v1.2.3 +# Produces build/release/benthos-collector__/benthos (+ README.md, LICENSE) +.PHONY: build-benthos-collector-release +build-benthos-collector-release: | collector-release-output-dir ## Cross-compile benthos-collector for release (set GOOS/GOARCH/VERSION) + $(call print-target) + $(if $(GOOS),,$(error GOOS is not set)) + $(if $(GOARCH),,$(error GOARCH is not set)) + @rm -rf "$(COLLECTOR_RELEASE_OUTPUT_DIR)"/* && \ + CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) \ + go build -C $(COLLECTOR_DIR) -trimpath \ + -ldflags "-s -w -X main.version=$(or $(VERSION),unknown)" \ + -o "$(COLLECTOR_RELEASE_OUTPUT_DIR)/benthos" ./cmd && \ + cp README.md LICENSE "$(COLLECTOR_RELEASE_OUTPUT_DIR)/" + +COLLECTOR_RELEASE_NAME := benthos-collector_$(GOOS)_$(GOARCH) + +# Produces build/release/benthos-collector__.tar.gz from the directory above. +.PHONY: archive-benthos-collector-release +archive-benthos-collector-release: ## Archive the cross-compiled benthos-collector (set GOOS/GOARCH) + $(call print-target) + $(if $(GOOS),,$(error GOOS is not set)) + $(if $(GOARCH),,$(error GOARCH is not set)) + @tar -C build/release -czf "build/release/$(COLLECTOR_RELEASE_NAME).tar.gz" "$(COLLECTOR_RELEASE_NAME)" + +.PHONY: build-server +build-server: | build-dir ## Build server binary + $(call print-target) + go build -o build/server ${GO_BUILD_FLAGS} ./cmd/server + +.PHONY: build-sink-worker +build-sink-worker: | build-dir ## Build sink-worker binary + $(call print-target) + go build -o build/sink-worker ${GO_BUILD_FLAGS} ./cmd/sink-worker + +.PHONY: build-benthos-collector +build-benthos-collector: | build-dir ## Build benthos collector binary + $(call print-target) + go build -C $(COLLECTOR_DIR) -o ../build/benthos-collector ${GO_BUILD_FLAGS} ./cmd + +.PHONY: build-balance-worker +build-balance-worker: | build-dir ## Build balance-worker binary + $(call print-target) + go build -o build/balance-worker ${GO_BUILD_FLAGS} ./cmd/balance-worker + +.PHONY: build-billing-worker +build-billing-worker: | build-dir ## Build billing-worker binary + $(call print-target) + go build -o build/billing-worker ${GO_BUILD_FLAGS} ./cmd/billing-worker + +.PHONY: build-notification-service +build-notification-service: | build-dir ## Build notification-service binary + $(call print-target) + go build -o build/notification-service ${GO_BUILD_FLAGS} ./cmd/notification-service + +.PHONY: build-jobs +build-jobs: | build-dir ## Build jobs binary + $(call print-target) + go build -o build/jobs ${GO_BUILD_FLAGS} ./cmd/jobs + +config.yaml: + cp config.example.yaml config.yaml + +.PHONY: server +server: ## Run sink-worker + @ if [ config.yaml -ot config.example.yaml ]; then diff -u config.yaml config.example.yaml || (echo "!!! The configuration example changed. Please update your config.yaml file accordingly (or at least touch it). !!!" && false); fi + $(call print-target) + air -c ./cmd/server/.air.toml + +.PHONY: sink-worker +sink-worker: ## Run sink-worker + @ if [ config.yaml -ot config.example.yaml ]; then diff -u config.yaml config.example.yaml || (echo "!!! The configuration example changed. Please update your config.yaml file accordingly (or at least touch it). !!!" && false); fi + $(call print-target) + air -c ./cmd/sink-worker/.air.toml + +.PHONY: balance-worker +balance-worker: ## Run balance-worker + @ if [ config.yaml -ot config.example.yaml ]; then diff -u config.yaml config.example.yaml || (echo "!!! The configuration example changed. Please update your config.yaml file accordingly (or at least touch it). !!!" && false); fi + $(call print-target) + air -c ./cmd/balance-worker/.air.toml + +.PHONY: billing-worker +billing-worker: ## Run billing-worker + @ if [ config.yaml -ot config.example.yaml ]; then diff -u config.yaml config.example.yaml || (echo "!!! The configuration example changed. Please update your config.yaml file accordingly (or at least touch it). !!!" && false); fi + $(call print-target) + air -c ./cmd/billing-worker/.air.toml + +.PHONY: notification-service +notification-service: ## Run notification-service + @ if [ config.yaml -ot config.example.yaml ]; then diff -u config.yaml config.example.yaml || (echo "!!! The configuration example changed. Please update your config.yaml file accordingly (or at least touch it). !!!" && false); fi + $(call print-target) + air -c ./cmd/notification-service/.air.toml + +.PHONY: llm-cost-sync +llm-cost-sync: ## Sync LLM cost prices from external sources + $(call print-target) + go run ./cmd/jobs llm-cost sync + +.PHONY: etoe +etoe: ## Run e2e tests + $(call print-target) + $(MAKE) -C e2e test-local + +.PHONY: etoe-slow +etoe-slow: ## Run e2e tests with slow tests enabled + $(call print-target) + export RUN_SLOW_TESTS=1 + $(MAKE) -C e2e test-local + + +.PHONY: test +test: ## Run tests + $(call print-target) + PGPASSWORD=postgres psql -h 127.0.0.1 -U postgres postgres -c "SELECT version();" || (echo "!!! Postgres is not running. Please start it with 'docker compose up -d postgres' !!!" && false) + POSTGRES_HOST=127.0.0.1 gotestsum $(GOTESTSUM_FLAGS) -- $(GO_TEST_FLAGS) ./... + +.PHONY: test-nocache +test-nocache: ## Run tests without cache + $(call print-target) + PGPASSWORD=postgres psql -h 127.0.0.1 -U postgres postgres -c "SELECT version();" || (echo "!!! Postgres is not running. Please start it with 'docker compose up -d postgres' !!!" && false) + POSTGRES_HOST=127.0.0.1 gotestsum $(GOTESTSUM_FLAGS) -- $(GO_TEST_FLAGS) -count=1 ./... + +.PHONY: test-all +test-all: ## Run tests with svix dependencies, bypassing the test cache + $(call print-target) + docker compose up -d postgres svix redis + ./tools/wait-for-compose.sh postgres svix redis + SVIX_HOST="localhost" SVIX_JWT_SECRET="$(SVIX_JWT_SECRET)" gotestsum $(GOTESTSUM_FLAGS) -- $(GO_TEST_FLAGS) -count=1 ./... + +.PHONY: test-go-sdk +test-go-sdk: ## Build, vet, and test the v3 Go SDK module (api/v3/client) + $(call print-target) + cd api/v3/client && go build ./... && go vet ./... && gotestsum $(GOTESTSUM_FLAGS) -- ./... + +.PHONY: lint +lint: lint-go lint-api-spec lint-openapi lint-helm ## Run linters + $(call print-target) + +.PHONY: lint-api-spec +lint-api-spec: ## Lint OpenAPI spec + $(call print-target) + $(MAKE) -C api/spec lint + +.PHONY: test-api-spec +test-api-spec: ## Run AIP TypeScript SDK and emitter tests + $(call print-target) + $(MAKE) -C api/spec test + +.PHONY: lint-openapi +lint-openapi: ## Lint OpenAPI spec + $(call print-target) + spectral lint api/openapi.yaml api/openapi.cloud.yaml api/v3/openapi.yaml + +.PHONY: lint-helm +lint-helm: ## Lint Helm charts + $(call print-target) + helm lint deploy/charts/openmeter + helm lint deploy/charts/benthos-collector + +# Package a helm chart for release. +# Usage: make package-helm-chart CHART=openmeter VERSION=v1.2.3 +# Produces build/helm/-.tgz +.PHONY: package-helm-chart +package-helm-chart: ## Package a helm chart for release (set CHART and VERSION) + $(call print-target) + @if [ -z "$(CHART)" ] || [ -z "$(VERSION)" ]; then echo "ERROR: CHART and VERSION are required"; exit 1; fi + @chart_dir="deploy/charts/$(CHART)" && \ + version_no_v="$(VERSION:v%=%)" && \ + mkdir -p build/helm && \ + helm-docs --log-level info -s file -c "$$chart_dir" \ + -t "deploy/charts/template.md" -t "$$chart_dir/README.tmpl.md" && \ + helm dependency update "$$chart_dir" && \ + helm package "$$chart_dir" \ + --version "$$version_no_v" \ + --app-version "$(VERSION)" \ + --destination build/helm + +.PHONY: lint-go +lint-go: ## Lint Go code + $(call print-target) + golangci-lint run -v $(GO_LINT_PATH) + cd api/v3/client && golangci-lint run -v ./... + go vet -C e2e ./... + cd e2e && golangci-lint run -v ./... + +.PHONY: lint-go-fast +lint-go-fast: ## Lint Go bug-finding checks (set GO_LINT_PATH=./openmeter/ledger/...) + $(call print-target) + golangci-lint run -v --config .golangci-fast.yaml $(GO_LINT_PATH) + +.PHONY: lint-go-style +lint-go-style: ## Lint Go formatting and import order + $(call print-target) + golangci-lint fmt -v -d $(GO_LINT_PATH) + +.PHONY: lint-go-head +lint-go-head: ## Lint Go code since last commit + $(call print-target) + golangci-lint run --new-from-rev=HEAD~1 + +.PHONY: ci +ci: ## Run CI checks + $(call print-target) + $(MAKE) generate-all + $(MAKE) -j 10 lint test etoe + +.PHONY: fmt +fmt: ## Format code + $(call print-target) + golangci-lint run --fix + +.PHONY: mod +mod: ## go mod tidy + $(call print-target) + go mod tidy + go mod tidy -C collector + go mod tidy -C api/v3/client + go mod tidy -C e2e + +.PHONY: seed +seed: ## Seed OpenMeter with test data + $(call print-target) + benthos -c etc/seed/seed.yaml + +.PHONY: help +.DEFAULT_GOAL := help +help: + @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' + +# Variable outputting/exporting rules +var-%: ; @echo $($*) +varexport-%: ; @echo $*=$($*) + +define print-target + @printf "Executing target: \033[36m$@\033[0m\n" +endef diff --git a/README.md b/README.md index 4a699beef95067551e224ed6f16338d067ed8cfd..599efb75ff53e93cefe0b0059b97316348644e74 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,163 @@ --- title: Openmeter -emoji: 🏃 -colorFrom: blue -colorTo: red sdk: docker -pinned: false +app_port: 7860 --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +
+ +![OpenMeter logo](assets/logo.png) + +# OpenMeter + +The open-source metering and billing platform +for AI, agentic and DevTool monetization. + +[Docs](https://openmeter.io/docs) | +[Hosted](https://cloud.konghq.com/register?utm_campaign=metering_and_billing) | +[Blog](https://openmeter.io/blog) | +[Contributing](CONTRIBUTING.md) + +[![GitHub Release](https://img.shields.io/github/v/release/openmeterio/openmeter?style=flat-square)](https://github.com/openmeterio/openmeter/releases/latest) +[![CI Status](https://img.shields.io/github/actions/workflow/status/openmeterio/openmeter/ci.yaml?style=flat-square)](https://github.com/openmeterio/openmeter/actions/workflows/ci.yaml) +[![Go Report Card](https://goreportcard.com/badge/github.com/openmeterio/openmeter?style=flat-square)](https://goreportcard.com/report/github.com/openmeterio/openmeter) +![GitHub Stars](https://img.shields.io/github/stars/openmeterio/openmeter?style=flat-square) + +
+ +--- + +OpenMeter is a real-time metering and billing engine that +helps you track usage, enforce limits, manage subscriptions, +and automate invoicing — all in one platform. Ingest events +via a simple API, define meters with flexible aggregations, +and connect usage data to billing, entitlements, and +customer-facing dashboards. + +## Features + +- **Usage Metering** — Ingest events in + [CloudEvents](https://cloudevents.io) format, define meters + with flexible aggregations (SUM, COUNT, AVG, MIN, MAX), + and query usage in real time. +- **Usage-Based Billing** — Generate invoices from metered + usage. Supports tiered, graduated, and flat-fee pricing + with automated invoice lifecycle management. +- **Usage Limits and Entitlements** — Enforce usage quotas + per feature with real-time balance tracking, boolean + feature flags, and grace periods. +- **Product Catalog** — Define plans, add-ons, features, and + rate cards. Manage subscriptions with mid-cycle changes, + prorating, and alignment. +- **Prepaid Credits** — Support paid or promotional credit grants + with priority-based burn-down and expiration. +- **Customer Portal** — Token-based self-service dashboards + so your customers can see their own usage. +- **Notifications** — Webhook-based alerts with configurable + rules and channels for usage thresholds and billing events. +- **LLM Cost Tracking** — First-class support for metering + AI token usage and computing model-specific costs. + +## Getting Started + +### Cloud + +The fastest way to start. +[Start for free](https://cloud.konghq.com/register?utm_campaign=metering_and_billing) +and begin metering and billing in minutes — +no infrastructure to manage. + +### Self-Hosted + +Run OpenMeter locally with Docker Compose: + +```sh +git clone git@github.com:openmeterio/openmeter.git +cd openmeter/quickstart +docker compose up -d +``` + +Then ingest your first event: + +```sh +curl -X POST http://localhost:48888/api/v1/events \ + -H 'Content-Type: application/cloudevents+json' \ + --data-raw '{ + "specversion": "1.0", + "type": "request", + "id": "00001", + "time": "2026-07-07T00:00:00.001Z", + "source": "my-service", + "subject": "customer-1", + "data": { "method": "GET", "route": "/api/hello" } + }' +``` + +Query your usage: + +```sh +curl 'http://localhost:48888/api/v1/meters/api_requests_total/query?windowSize=HOUR' | jq +``` + +See the full [quickstart guide](/quickstart) for more details. + +### Deploy to Production + +Deploy to Kubernetes using our +[Helm chart](https://openmeter.io/docs/deploy/kubernetes). + +## SDKs + +| Language | Package | Source | +|----------------------|--------------------------------------------------------------------------------|----------------------------------------------------| +| Go | [openmeter](https://pkg.go.dev/github.com/openmeterio/openmeter/api/client/go) | [api/client/go](/api/client/go) | +| JavaScript / Node.js | [@openmeter/sdk](https://www.npmjs.com/package/@openmeter/sdk) | [api/client/javascript](/api/client/javascript) | +| Python | [openmeter](https://pypi.org/project/openmeter) | [api/client/python](/api/client/python) | + +Don't see your language? Use the +[OpenAPI spec](https://github.com/openmeterio/openmeter/blob/main/api/openapi.yaml) +directly or +[request an SDK](https://github.com/openmeterio/openmeter/issues/new?assignees=&labels=area%2Fapi%2Ckind%2Ffeature&projects=&template=feature_request.yaml). + +## Architecture + +OpenMeter is built in Go with a stack optimized for +high-volume event ingestion and real-time aggregation: + +| Component | Role | +|--------------------------|----------------------------------------------------------| +| **PostgreSQL** (Ent ORM) | Billing, subscriptions, entitlements, product catalog | +| **ClickHouse** | Real-time usage aggregation and analytics | +| **Kafka** | Event streaming and ingestion pipeline | +| **TypeSpec** | API-first design — OpenAPI spec and SDKs from TypeSpec | + +## Community + +We'd love to have you involved: + +- **[Contributing](CONTRIBUTING.md)** — Start here if you + want to contribute code. +- **[Code of Conduct](CODE_OF_CONDUCT.md)** — Our community + guidelines. +- **[Blog](https://openmeter.io/blog)** — Product updates + and engineering deep dives. + +## Development + +Prerequisites: [Nix](https://nixos.org/download.html) and +[direnv](https://direnv.net/docs/installation.html) are +recommended. See [CONTRIBUTING.md](CONTRIBUTING.md) for +detailed setup instructions. + +```sh +make up # Start dependencies (Postgres, Kafka, ClickHouse) +make server # Run the API server with hot reload +make test # Run tests +make lint # Run linters +``` + +## License + +Licensed under [Apache 2.0](LICENSE). + +[![FOSSA Status](https://app.fossa.com/api/projects/custom%2B38090%2Fgithub.com%2Fopenmeterio%2Fopenmeter.svg?type=large)](https://app.fossa.com/projects/custom%2B38090%2Fgithub.com%2Fopenmeterio%2Fopenmeter?ref=badge_large) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..b81b2f7f69c2e3d2b21575f2276b6ef11b3bc01f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,29 @@ +# Security Policies and Procedures + +This document outlines security procedures and general policies for OpenMeter. + +- [Reporting a vulnerability](#reporting-a-vulnerability) +- [Disclosure policy](#disclosure-policy) + +## Reporting a vulnerability + +The OpenMeter team and community take all security issues seriously. Thank you for improving the security of our projects. +We appreciate your efforts and responsible disclosure and will make every effort to acknowledge your contributions. + +**Report security issues using GitHub's [vulnerability reporting feature](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing/privately-reporting-a-security-vulnerability).** + +_Alternatively, you can send an email to `security@openmeter.io`._ + +Somebody from the OpenMeter team will acknowledge your report within 48 hours, +and will follow up with a more detailed response after that indicating the next steps in handling your report. +After the initial reply to your report, the team will endeavor to keep you informed of the progress towards a fix and full announcement, +and may ask for additional information or guidance. + +## Disclosure policy + +When the team receives a vulnerability report, they will assign it to a primary handler. +This person will coordinate the fix and release process, involving the following steps: + +- Confirm the problem and determine the affected versions. +- Audit code to find any potential similar problems. +- Prepare fixes for all releases still under maintenance. These fixes will be released as quickly as possible. diff --git a/api/api.gen.go b/api/api.gen.go new file mode 100644 index 0000000000000000000000000000000000000000..f4d8c83dd5bbdc9d80bffb53844a75a830173b2a --- /dev/null +++ b/api/api.gen.go @@ -0,0 +1,24150 @@ +// Package api provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.6.1-0.20260403235458-a76544bd16ff DO NOT EDIT. +package api + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/cloudevents/sdk-go/v2/event" + "github.com/getkin/kin-openapi/openapi3" + "github.com/go-chi/chi/v5" + "github.com/oapi-codegen/runtime" + "github.com/openmeterio/openmeter/pkg/models" +) + +const ( + PortalTokenAuthScopes portalTokenAuthContextKey = "PortalTokenAuth.Scopes" +) + +// Defines values for AddonInstanceType. +const ( + AddonInstanceTypeMultiple AddonInstanceType = "multiple" + AddonInstanceTypeSingle AddonInstanceType = "single" +) + +// Valid indicates whether the value is a known member of the AddonInstanceType enum. +func (e AddonInstanceType) Valid() bool { + switch e { + case AddonInstanceTypeMultiple: + return true + case AddonInstanceTypeSingle: + return true + default: + return false + } +} + +// Defines values for AddonOrderBy. +const ( + AddonOrderByCreatedAt AddonOrderBy = "created_at" + AddonOrderById AddonOrderBy = "id" + AddonOrderByKey AddonOrderBy = "key" + AddonOrderByUpdatedAt AddonOrderBy = "updated_at" + AddonOrderByVersion AddonOrderBy = "version" +) + +// Valid indicates whether the value is a known member of the AddonOrderBy enum. +func (e AddonOrderBy) Valid() bool { + switch e { + case AddonOrderByCreatedAt: + return true + case AddonOrderById: + return true + case AddonOrderByKey: + return true + case AddonOrderByUpdatedAt: + return true + case AddonOrderByVersion: + return true + default: + return false + } +} + +// Defines values for AddonStatus. +const ( + AddonStatusActive AddonStatus = "active" + AddonStatusArchived AddonStatus = "archived" + AddonStatusDraft AddonStatus = "draft" +) + +// Valid indicates whether the value is a known member of the AddonStatus enum. +func (e AddonStatus) Valid() bool { + switch e { + case AddonStatusActive: + return true + case AddonStatusArchived: + return true + case AddonStatusDraft: + return true + default: + return false + } +} + +// Defines values for AppCapabilityType. +const ( + AppCapabilityTypeCalculateTax AppCapabilityType = "calculateTax" + AppCapabilityTypeCollectPayments AppCapabilityType = "collectPayments" + AppCapabilityTypeInvoiceCustomers AppCapabilityType = "invoiceCustomers" + AppCapabilityTypeReportEvents AppCapabilityType = "reportEvents" + AppCapabilityTypeReportUsage AppCapabilityType = "reportUsage" +) + +// Valid indicates whether the value is a known member of the AppCapabilityType enum. +func (e AppCapabilityType) Valid() bool { + switch e { + case AppCapabilityTypeCalculateTax: + return true + case AppCapabilityTypeCollectPayments: + return true + case AppCapabilityTypeInvoiceCustomers: + return true + case AppCapabilityTypeReportEvents: + return true + case AppCapabilityTypeReportUsage: + return true + default: + return false + } +} + +// Defines values for AppStatus. +const ( + AppStatusReady AppStatus = "ready" + AppStatusUnauthorized AppStatus = "unauthorized" +) + +// Valid indicates whether the value is a known member of the AppStatus enum. +func (e AppStatus) Valid() bool { + switch e { + case AppStatusReady: + return true + case AppStatusUnauthorized: + return true + default: + return false + } +} + +// Defines values for AppType. +const ( + AppTypeCustomInvoicing AppType = "custom_invoicing" + AppTypeSandbox AppType = "sandbox" + AppTypeStripe AppType = "stripe" +) + +// Valid indicates whether the value is a known member of the AppType enum. +func (e AppType) Valid() bool { + switch e { + case AppTypeCustomInvoicing: + return true + case AppTypeSandbox: + return true + case AppTypeStripe: + return true + default: + return false + } +} + +// Defines values for BillingCollectionAlignment. +const ( + BillingCollectionAlignmentAnchored BillingCollectionAlignment = "anchored" + BillingCollectionAlignmentSubscription BillingCollectionAlignment = "subscription" +) + +// Valid indicates whether the value is a known member of the BillingCollectionAlignment enum. +func (e BillingCollectionAlignment) Valid() bool { + switch e { + case BillingCollectionAlignmentAnchored: + return true + case BillingCollectionAlignmentSubscription: + return true + default: + return false + } +} + +// Defines values for BillingProfileCustomerOverrideExpand. +const ( + BillingProfileCustomerOverrideExpandApps BillingProfileCustomerOverrideExpand = "apps" + BillingProfileCustomerOverrideExpandCustomer BillingProfileCustomerOverrideExpand = "customer" +) + +// Valid indicates whether the value is a known member of the BillingProfileCustomerOverrideExpand enum. +func (e BillingProfileCustomerOverrideExpand) Valid() bool { + switch e { + case BillingProfileCustomerOverrideExpandApps: + return true + case BillingProfileCustomerOverrideExpandCustomer: + return true + default: + return false + } +} + +// Defines values for BillingProfileCustomerOverrideOrderBy. +const ( + BillingProfileCustomerOverrideOrderByCustomerCreatedAt BillingProfileCustomerOverrideOrderBy = "customerCreatedAt" + BillingProfileCustomerOverrideOrderByCustomerId BillingProfileCustomerOverrideOrderBy = "customerId" + BillingProfileCustomerOverrideOrderByCustomerKey BillingProfileCustomerOverrideOrderBy = "customerKey" + BillingProfileCustomerOverrideOrderByCustomerName BillingProfileCustomerOverrideOrderBy = "customerName" + BillingProfileCustomerOverrideOrderByCustomerPrimaryEmail BillingProfileCustomerOverrideOrderBy = "customerPrimaryEmail" +) + +// Valid indicates whether the value is a known member of the BillingProfileCustomerOverrideOrderBy enum. +func (e BillingProfileCustomerOverrideOrderBy) Valid() bool { + switch e { + case BillingProfileCustomerOverrideOrderByCustomerCreatedAt: + return true + case BillingProfileCustomerOverrideOrderByCustomerId: + return true + case BillingProfileCustomerOverrideOrderByCustomerKey: + return true + case BillingProfileCustomerOverrideOrderByCustomerName: + return true + case BillingProfileCustomerOverrideOrderByCustomerPrimaryEmail: + return true + default: + return false + } +} + +// Defines values for BillingProfileExpand. +const ( + BillingProfileExpandApps BillingProfileExpand = "apps" +) + +// Valid indicates whether the value is a known member of the BillingProfileExpand enum. +func (e BillingProfileExpand) Valid() bool { + switch e { + case BillingProfileExpandApps: + return true + default: + return false + } +} + +// Defines values for BillingProfileOrderBy. +const ( + BillingProfileOrderByCreatedAt BillingProfileOrderBy = "createdAt" + BillingProfileOrderByDefault BillingProfileOrderBy = "default" + BillingProfileOrderByName BillingProfileOrderBy = "name" + BillingProfileOrderByUpdatedAt BillingProfileOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the BillingProfileOrderBy enum. +func (e BillingProfileOrderBy) Valid() bool { + switch e { + case BillingProfileOrderByCreatedAt: + return true + case BillingProfileOrderByDefault: + return true + case BillingProfileOrderByName: + return true + case BillingProfileOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for BillingSettlementMode. +const ( + BillingSettlementModeCreditOnly BillingSettlementMode = "credit_only" + BillingSettlementModeCreditThenInvoice BillingSettlementMode = "credit_then_invoice" +) + +// Valid indicates whether the value is a known member of the BillingSettlementMode enum. +func (e BillingSettlementMode) Valid() bool { + switch e { + case BillingSettlementModeCreditOnly: + return true + case BillingSettlementModeCreditThenInvoice: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowAppReferenceType. +const ( + BillingWorkflowAppReferenceTypeAppId BillingWorkflowAppReferenceType = "app_id" + BillingWorkflowAppReferenceTypeAppType BillingWorkflowAppReferenceType = "app_type" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowAppReferenceType enum. +func (e BillingWorkflowAppReferenceType) Valid() bool { + switch e { + case BillingWorkflowAppReferenceTypeAppId: + return true + case BillingWorkflowAppReferenceTypeAppType: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowCollectionAlignmentAnchoredType. +const ( + BillingWorkflowCollectionAlignmentAnchoredTypeAnchored BillingWorkflowCollectionAlignmentAnchoredType = "anchored" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowCollectionAlignmentAnchoredType enum. +func (e BillingWorkflowCollectionAlignmentAnchoredType) Valid() bool { + switch e { + case BillingWorkflowCollectionAlignmentAnchoredTypeAnchored: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowCollectionAlignmentSubscriptionType. +const ( + BillingWorkflowCollectionAlignmentSubscriptionTypeSubscription BillingWorkflowCollectionAlignmentSubscriptionType = "subscription" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowCollectionAlignmentSubscriptionType enum. +func (e BillingWorkflowCollectionAlignmentSubscriptionType) Valid() bool { + switch e { + case BillingWorkflowCollectionAlignmentSubscriptionTypeSubscription: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowInvoicingSubscriptionEndProrationMode. +const ( + BillingWorkflowInvoicingSubscriptionEndProrationModeBillActualPeriod BillingWorkflowInvoicingSubscriptionEndProrationMode = "bill_actual_period" + BillingWorkflowInvoicingSubscriptionEndProrationModeBillFullPeriod BillingWorkflowInvoicingSubscriptionEndProrationMode = "bill_full_period" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowInvoicingSubscriptionEndProrationMode enum. +func (e BillingWorkflowInvoicingSubscriptionEndProrationMode) Valid() bool { + switch e { + case BillingWorkflowInvoicingSubscriptionEndProrationModeBillActualPeriod: + return true + case BillingWorkflowInvoicingSubscriptionEndProrationModeBillFullPeriod: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowLineResolution. +const ( + BillingWorkflowLineResolutionDay BillingWorkflowLineResolution = "day" + BillingWorkflowLineResolutionPeriod BillingWorkflowLineResolution = "period" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowLineResolution enum. +func (e BillingWorkflowLineResolution) Valid() bool { + switch e { + case BillingWorkflowLineResolutionDay: + return true + case BillingWorkflowLineResolutionPeriod: + return true + default: + return false + } +} + +// Defines values for CheckoutSessionUIMode. +const ( + CheckoutSessionUIModeEmbedded CheckoutSessionUIMode = "embedded" + CheckoutSessionUIModeHosted CheckoutSessionUIMode = "hosted" +) + +// Valid indicates whether the value is a known member of the CheckoutSessionUIMode enum. +func (e CheckoutSessionUIMode) Valid() bool { + switch e { + case CheckoutSessionUIModeEmbedded: + return true + case CheckoutSessionUIModeHosted: + return true + default: + return false + } +} + +// Defines values for CollectionMethod. +const ( + CollectionMethodChargeAutomatically CollectionMethod = "charge_automatically" + CollectionMethodSendInvoice CollectionMethod = "send_invoice" +) + +// Valid indicates whether the value is a known member of the CollectionMethod enum. +func (e CollectionMethod) Valid() bool { + switch e { + case CollectionMethodChargeAutomatically: + return true + case CollectionMethodSendInvoice: + return true + default: + return false + } +} + +// Defines values for CreateCheckoutSessionTaxIdCollectionRequired. +const ( + CreateCheckoutSessionTaxIdCollectionRequiredIfSupported CreateCheckoutSessionTaxIdCollectionRequired = "if_supported" + CreateCheckoutSessionTaxIdCollectionRequiredNever CreateCheckoutSessionTaxIdCollectionRequired = "never" +) + +// Valid indicates whether the value is a known member of the CreateCheckoutSessionTaxIdCollectionRequired enum. +func (e CreateCheckoutSessionTaxIdCollectionRequired) Valid() bool { + switch e { + case CreateCheckoutSessionTaxIdCollectionRequiredIfSupported: + return true + case CreateCheckoutSessionTaxIdCollectionRequiredNever: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionBillingAddressCollection. +const ( + CreateStripeCheckoutSessionBillingAddressCollectionAuto CreateStripeCheckoutSessionBillingAddressCollection = "auto" + CreateStripeCheckoutSessionBillingAddressCollectionRequired CreateStripeCheckoutSessionBillingAddressCollection = "required" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionBillingAddressCollection enum. +func (e CreateStripeCheckoutSessionBillingAddressCollection) Valid() bool { + switch e { + case CreateStripeCheckoutSessionBillingAddressCollectionAuto: + return true + case CreateStripeCheckoutSessionBillingAddressCollectionRequired: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition. +const ( + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionAuto CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "auto" + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionHidden CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "hidden" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition enum. +func (e CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition) Valid() bool { + switch e { + case CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionAuto: + return true + case CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionHidden: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionConsentCollectionPromotions. +const ( + CreateStripeCheckoutSessionConsentCollectionPromotionsAuto CreateStripeCheckoutSessionConsentCollectionPromotions = "auto" + CreateStripeCheckoutSessionConsentCollectionPromotionsNone CreateStripeCheckoutSessionConsentCollectionPromotions = "none" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionConsentCollectionPromotions enum. +func (e CreateStripeCheckoutSessionConsentCollectionPromotions) Valid() bool { + switch e { + case CreateStripeCheckoutSessionConsentCollectionPromotionsAuto: + return true + case CreateStripeCheckoutSessionConsentCollectionPromotionsNone: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionConsentCollectionTermsOfService. +const ( + CreateStripeCheckoutSessionConsentCollectionTermsOfServiceNone CreateStripeCheckoutSessionConsentCollectionTermsOfService = "none" + CreateStripeCheckoutSessionConsentCollectionTermsOfServiceRequired CreateStripeCheckoutSessionConsentCollectionTermsOfService = "required" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionConsentCollectionTermsOfService enum. +func (e CreateStripeCheckoutSessionConsentCollectionTermsOfService) Valid() bool { + switch e { + case CreateStripeCheckoutSessionConsentCollectionTermsOfServiceNone: + return true + case CreateStripeCheckoutSessionConsentCollectionTermsOfServiceRequired: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionCustomerUpdateBehavior. +const ( + CreateStripeCheckoutSessionCustomerUpdateBehaviorAuto CreateStripeCheckoutSessionCustomerUpdateBehavior = "auto" + CreateStripeCheckoutSessionCustomerUpdateBehaviorNever CreateStripeCheckoutSessionCustomerUpdateBehavior = "never" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionCustomerUpdateBehavior enum. +func (e CreateStripeCheckoutSessionCustomerUpdateBehavior) Valid() bool { + switch e { + case CreateStripeCheckoutSessionCustomerUpdateBehaviorAuto: + return true + case CreateStripeCheckoutSessionCustomerUpdateBehaviorNever: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionRedirectOnCompletion. +const ( + CreateStripeCheckoutSessionRedirectOnCompletionAlways CreateStripeCheckoutSessionRedirectOnCompletion = "always" + CreateStripeCheckoutSessionRedirectOnCompletionIfRequired CreateStripeCheckoutSessionRedirectOnCompletion = "if_required" + CreateStripeCheckoutSessionRedirectOnCompletionNever CreateStripeCheckoutSessionRedirectOnCompletion = "never" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionRedirectOnCompletion enum. +func (e CreateStripeCheckoutSessionRedirectOnCompletion) Valid() bool { + switch e { + case CreateStripeCheckoutSessionRedirectOnCompletionAlways: + return true + case CreateStripeCheckoutSessionRedirectOnCompletionIfRequired: + return true + case CreateStripeCheckoutSessionRedirectOnCompletionNever: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingAppType. +const ( + CustomInvoicingAppTypeCustomInvoicing CustomInvoicingAppType = "custom_invoicing" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingAppType enum. +func (e CustomInvoicingAppType) Valid() bool { + switch e { + case CustomInvoicingAppTypeCustomInvoicing: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingAppReplaceUpdateType. +const ( + CustomInvoicingAppReplaceUpdateTypeCustomInvoicing CustomInvoicingAppReplaceUpdateType = "custom_invoicing" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingAppReplaceUpdateType enum. +func (e CustomInvoicingAppReplaceUpdateType) Valid() bool { + switch e { + case CustomInvoicingAppReplaceUpdateTypeCustomInvoicing: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingCustomerAppDataType. +const ( + CustomInvoicingCustomerAppDataTypeCustomInvoicing CustomInvoicingCustomerAppDataType = "custom_invoicing" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingCustomerAppDataType enum. +func (e CustomInvoicingCustomerAppDataType) Valid() bool { + switch e { + case CustomInvoicingCustomerAppDataTypeCustomInvoicing: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingPaymentTrigger. +const ( + CustomInvoicingPaymentTriggerActionRequired CustomInvoicingPaymentTrigger = "action_required" + CustomInvoicingPaymentTriggerPaid CustomInvoicingPaymentTrigger = "paid" + CustomInvoicingPaymentTriggerPaymentFailed CustomInvoicingPaymentTrigger = "payment_failed" + CustomInvoicingPaymentTriggerPaymentOverdue CustomInvoicingPaymentTrigger = "payment_overdue" + CustomInvoicingPaymentTriggerPaymentUncollectible CustomInvoicingPaymentTrigger = "payment_uncollectible" + CustomInvoicingPaymentTriggerVoid CustomInvoicingPaymentTrigger = "void" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingPaymentTrigger enum. +func (e CustomInvoicingPaymentTrigger) Valid() bool { + switch e { + case CustomInvoicingPaymentTriggerActionRequired: + return true + case CustomInvoicingPaymentTriggerPaid: + return true + case CustomInvoicingPaymentTriggerPaymentFailed: + return true + case CustomInvoicingPaymentTriggerPaymentOverdue: + return true + case CustomInvoicingPaymentTriggerPaymentUncollectible: + return true + case CustomInvoicingPaymentTriggerVoid: + return true + default: + return false + } +} + +// Defines values for CustomerExpand. +const ( + CustomerExpandSubscriptions CustomerExpand = "subscriptions" +) + +// Valid indicates whether the value is a known member of the CustomerExpand enum. +func (e CustomerExpand) Valid() bool { + switch e { + case CustomerExpandSubscriptions: + return true + default: + return false + } +} + +// Defines values for CustomerOrderBy. +const ( + CustomerOrderByCreatedAt CustomerOrderBy = "createdAt" + CustomerOrderById CustomerOrderBy = "id" + CustomerOrderByName CustomerOrderBy = "name" +) + +// Valid indicates whether the value is a known member of the CustomerOrderBy enum. +func (e CustomerOrderBy) Valid() bool { + switch e { + case CustomerOrderByCreatedAt: + return true + case CustomerOrderById: + return true + case CustomerOrderByName: + return true + default: + return false + } +} + +// Defines values for CustomerSubscriptionOrderBy. +const ( + CustomerSubscriptionOrderByActiveFrom CustomerSubscriptionOrderBy = "activeFrom" + CustomerSubscriptionOrderByActiveTo CustomerSubscriptionOrderBy = "activeTo" +) + +// Valid indicates whether the value is a known member of the CustomerSubscriptionOrderBy enum. +func (e CustomerSubscriptionOrderBy) Valid() bool { + switch e { + case CustomerSubscriptionOrderByActiveFrom: + return true + case CustomerSubscriptionOrderByActiveTo: + return true + default: + return false + } +} + +// Defines values for DiscountReasonMaximumSpendType. +const ( + DiscountReasonMaximumSpendTypeMaximumSpend DiscountReasonMaximumSpendType = "maximum_spend" +) + +// Valid indicates whether the value is a known member of the DiscountReasonMaximumSpendType enum. +func (e DiscountReasonMaximumSpendType) Valid() bool { + switch e { + case DiscountReasonMaximumSpendTypeMaximumSpend: + return true + default: + return false + } +} + +// Defines values for DiscountReasonRatecardPercentageType. +const ( + DiscountReasonRatecardPercentageTypeRatecardPercentage DiscountReasonRatecardPercentageType = "ratecard_percentage" +) + +// Valid indicates whether the value is a known member of the DiscountReasonRatecardPercentageType enum. +func (e DiscountReasonRatecardPercentageType) Valid() bool { + switch e { + case DiscountReasonRatecardPercentageTypeRatecardPercentage: + return true + default: + return false + } +} + +// Defines values for DiscountReasonRatecardUsageType. +const ( + DiscountReasonRatecardUsageTypeRatecardUsage DiscountReasonRatecardUsageType = "ratecard_usage" +) + +// Valid indicates whether the value is a known member of the DiscountReasonRatecardUsageType enum. +func (e DiscountReasonRatecardUsageType) Valid() bool { + switch e { + case DiscountReasonRatecardUsageTypeRatecardUsage: + return true + default: + return false + } +} + +// Defines values for DiscountReasonType. +const ( + DiscountReasonTypeMaximumSpend DiscountReasonType = "maximum_spend" + DiscountReasonTypeRatecardPercentage DiscountReasonType = "ratecard_percentage" + DiscountReasonTypeRatecardUsage DiscountReasonType = "ratecard_usage" +) + +// Valid indicates whether the value is a known member of the DiscountReasonType enum. +func (e DiscountReasonType) Valid() bool { + switch e { + case DiscountReasonTypeMaximumSpend: + return true + case DiscountReasonTypeRatecardPercentage: + return true + case DiscountReasonTypeRatecardUsage: + return true + default: + return false + } +} + +// Defines values for DynamicPriceType. +const ( + DynamicPriceTypeDynamic DynamicPriceType = "dynamic" +) + +// Valid indicates whether the value is a known member of the DynamicPriceType enum. +func (e DynamicPriceType) Valid() bool { + switch e { + case DynamicPriceTypeDynamic: + return true + default: + return false + } +} + +// Defines values for DynamicPriceWithCommitmentsType. +const ( + DynamicPriceWithCommitmentsTypeDynamic DynamicPriceWithCommitmentsType = "dynamic" +) + +// Valid indicates whether the value is a known member of the DynamicPriceWithCommitmentsType enum. +func (e DynamicPriceWithCommitmentsType) Valid() bool { + switch e { + case DynamicPriceWithCommitmentsTypeDynamic: + return true + default: + return false + } +} + +// Defines values for EditOp. +const ( + EditOpAddItem EditOp = "add_item" + EditOpAddPhase EditOp = "add_phase" + EditOpRemoveItem EditOp = "remove_item" + EditOpRemovePhase EditOp = "remove_phase" + EditOpStretchPhase EditOp = "stretch_phase" + EditOpUnscheduleEdit EditOp = "unschedule_edit" +) + +// Valid indicates whether the value is a known member of the EditOp enum. +func (e EditOp) Valid() bool { + switch e { + case EditOpAddItem: + return true + case EditOpAddPhase: + return true + case EditOpRemoveItem: + return true + case EditOpRemovePhase: + return true + case EditOpStretchPhase: + return true + case EditOpUnscheduleEdit: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionAddItemOp. +const ( + EditSubscriptionAddItemOpAddItem EditSubscriptionAddItemOp = "add_item" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionAddItemOp enum. +func (e EditSubscriptionAddItemOp) Valid() bool { + switch e { + case EditSubscriptionAddItemOpAddItem: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionAddPhaseOp. +const ( + EditSubscriptionAddPhaseOpAddPhase EditSubscriptionAddPhaseOp = "add_phase" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionAddPhaseOp enum. +func (e EditSubscriptionAddPhaseOp) Valid() bool { + switch e { + case EditSubscriptionAddPhaseOpAddPhase: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionRemoveItemOp. +const ( + EditSubscriptionRemoveItemOpRemoveItem EditSubscriptionRemoveItemOp = "remove_item" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionRemoveItemOp enum. +func (e EditSubscriptionRemoveItemOp) Valid() bool { + switch e { + case EditSubscriptionRemoveItemOpRemoveItem: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionRemovePhaseOp. +const ( + EditSubscriptionRemovePhaseOpRemovePhase EditSubscriptionRemovePhaseOp = "remove_phase" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionRemovePhaseOp enum. +func (e EditSubscriptionRemovePhaseOp) Valid() bool { + switch e { + case EditSubscriptionRemovePhaseOpRemovePhase: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionStretchPhaseOp. +const ( + EditSubscriptionStretchPhaseOpStretchPhase EditSubscriptionStretchPhaseOp = "stretch_phase" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionStretchPhaseOp enum. +func (e EditSubscriptionStretchPhaseOp) Valid() bool { + switch e { + case EditSubscriptionStretchPhaseOpStretchPhase: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionUnscheduleEditOp. +const ( + EditSubscriptionUnscheduleEditOpUnscheduleEdit EditSubscriptionUnscheduleEditOp = "unschedule_edit" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionUnscheduleEditOp enum. +func (e EditSubscriptionUnscheduleEditOp) Valid() bool { + switch e { + case EditSubscriptionUnscheduleEditOpUnscheduleEdit: + return true + default: + return false + } +} + +// Defines values for EntitlementBooleanType. +const ( + EntitlementBooleanTypeBoolean EntitlementBooleanType = "boolean" +) + +// Valid indicates whether the value is a known member of the EntitlementBooleanType enum. +func (e EntitlementBooleanType) Valid() bool { + switch e { + case EntitlementBooleanTypeBoolean: + return true + default: + return false + } +} + +// Defines values for EntitlementBooleanCreateInputsType. +const ( + EntitlementBooleanCreateInputsTypeBoolean EntitlementBooleanCreateInputsType = "boolean" +) + +// Valid indicates whether the value is a known member of the EntitlementBooleanCreateInputsType enum. +func (e EntitlementBooleanCreateInputsType) Valid() bool { + switch e { + case EntitlementBooleanCreateInputsTypeBoolean: + return true + default: + return false + } +} + +// Defines values for EntitlementBooleanV2Type. +const ( + EntitlementBooleanV2TypeBoolean EntitlementBooleanV2Type = "boolean" +) + +// Valid indicates whether the value is a known member of the EntitlementBooleanV2Type enum. +func (e EntitlementBooleanV2Type) Valid() bool { + switch e { + case EntitlementBooleanV2TypeBoolean: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredType. +const ( + EntitlementMeteredTypeMetered EntitlementMeteredType = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredType enum. +func (e EntitlementMeteredType) Valid() bool { + switch e { + case EntitlementMeteredTypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredCreateInputsType. +const ( + EntitlementMeteredCreateInputsTypeMetered EntitlementMeteredCreateInputsType = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredCreateInputsType enum. +func (e EntitlementMeteredCreateInputsType) Valid() bool { + switch e { + case EntitlementMeteredCreateInputsTypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredV2Type. +const ( + EntitlementMeteredV2TypeMetered EntitlementMeteredV2Type = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredV2Type enum. +func (e EntitlementMeteredV2Type) Valid() bool { + switch e { + case EntitlementMeteredV2TypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredV2CreateInputsType. +const ( + EntitlementMeteredV2CreateInputsTypeMetered EntitlementMeteredV2CreateInputsType = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredV2CreateInputsType enum. +func (e EntitlementMeteredV2CreateInputsType) Valid() bool { + switch e { + case EntitlementMeteredV2CreateInputsTypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementOrderBy. +const ( + EntitlementOrderByCreatedAt EntitlementOrderBy = "createdAt" + EntitlementOrderByUpdatedAt EntitlementOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the EntitlementOrderBy enum. +func (e EntitlementOrderBy) Valid() bool { + switch e { + case EntitlementOrderByCreatedAt: + return true + case EntitlementOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for EntitlementStaticType. +const ( + EntitlementStaticTypeStatic EntitlementStaticType = "static" +) + +// Valid indicates whether the value is a known member of the EntitlementStaticType enum. +func (e EntitlementStaticType) Valid() bool { + switch e { + case EntitlementStaticTypeStatic: + return true + default: + return false + } +} + +// Defines values for EntitlementStaticCreateInputsType. +const ( + EntitlementStaticCreateInputsTypeStatic EntitlementStaticCreateInputsType = "static" +) + +// Valid indicates whether the value is a known member of the EntitlementStaticCreateInputsType enum. +func (e EntitlementStaticCreateInputsType) Valid() bool { + switch e { + case EntitlementStaticCreateInputsTypeStatic: + return true + default: + return false + } +} + +// Defines values for EntitlementStaticV2Type. +const ( + EntitlementStaticV2TypeStatic EntitlementStaticV2Type = "static" +) + +// Valid indicates whether the value is a known member of the EntitlementStaticV2Type enum. +func (e EntitlementStaticV2Type) Valid() bool { + switch e { + case EntitlementStaticV2TypeStatic: + return true + default: + return false + } +} + +// Defines values for ExpirationDuration. +const ( + ExpirationDurationDAY ExpirationDuration = "DAY" + ExpirationDurationHOUR ExpirationDuration = "HOUR" + ExpirationDurationMONTH ExpirationDuration = "MONTH" + ExpirationDurationWEEK ExpirationDuration = "WEEK" + ExpirationDurationYEAR ExpirationDuration = "YEAR" +) + +// Valid indicates whether the value is a known member of the ExpirationDuration enum. +func (e ExpirationDuration) Valid() bool { + switch e { + case ExpirationDurationDAY: + return true + case ExpirationDurationHOUR: + return true + case ExpirationDurationMONTH: + return true + case ExpirationDurationWEEK: + return true + case ExpirationDurationYEAR: + return true + default: + return false + } +} + +// Defines values for FeatureLLMUnitCostType. +const ( + FeatureLLMUnitCostTypeLlm FeatureLLMUnitCostType = "llm" +) + +// Valid indicates whether the value is a known member of the FeatureLLMUnitCostType enum. +func (e FeatureLLMUnitCostType) Valid() bool { + switch e { + case FeatureLLMUnitCostTypeLlm: + return true + default: + return false + } +} + +// Defines values for FeatureManualUnitCostType. +const ( + FeatureManualUnitCostTypeManual FeatureManualUnitCostType = "manual" +) + +// Valid indicates whether the value is a known member of the FeatureManualUnitCostType enum. +func (e FeatureManualUnitCostType) Valid() bool { + switch e { + case FeatureManualUnitCostTypeManual: + return true + default: + return false + } +} + +// Defines values for FeatureOrderBy. +const ( + FeatureOrderByCreatedAt FeatureOrderBy = "createdAt" + FeatureOrderById FeatureOrderBy = "id" + FeatureOrderByKey FeatureOrderBy = "key" + FeatureOrderByName FeatureOrderBy = "name" + FeatureOrderByUpdatedAt FeatureOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the FeatureOrderBy enum. +func (e FeatureOrderBy) Valid() bool { + switch e { + case FeatureOrderByCreatedAt: + return true + case FeatureOrderById: + return true + case FeatureOrderByKey: + return true + case FeatureOrderByName: + return true + case FeatureOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for FeatureUnitCostType. +const ( + FeatureUnitCostTypeLlm FeatureUnitCostType = "llm" + FeatureUnitCostTypeManual FeatureUnitCostType = "manual" +) + +// Valid indicates whether the value is a known member of the FeatureUnitCostType enum. +func (e FeatureUnitCostType) Valid() bool { + switch e { + case FeatureUnitCostTypeLlm: + return true + case FeatureUnitCostTypeManual: + return true + default: + return false + } +} + +// Defines values for FlatPriceType. +const ( + FlatPriceTypeFlat FlatPriceType = "flat" +) + +// Valid indicates whether the value is a known member of the FlatPriceType enum. +func (e FlatPriceType) Valid() bool { + switch e { + case FlatPriceTypeFlat: + return true + default: + return false + } +} + +// Defines values for FlatPriceWithPaymentTermType. +const ( + FlatPriceWithPaymentTermTypeFlat FlatPriceWithPaymentTermType = "flat" +) + +// Valid indicates whether the value is a known member of the FlatPriceWithPaymentTermType enum. +func (e FlatPriceWithPaymentTermType) Valid() bool { + switch e { + case FlatPriceWithPaymentTermTypeFlat: + return true + default: + return false + } +} + +// Defines values for GrantOrderBy. +const ( + GrantOrderByCreatedAt GrantOrderBy = "createdAt" + GrantOrderById GrantOrderBy = "id" + GrantOrderByUpdatedAt GrantOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the GrantOrderBy enum. +func (e GrantOrderBy) Valid() bool { + switch e { + case GrantOrderByCreatedAt: + return true + case GrantOrderById: + return true + case GrantOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for InstallMethod. +const ( + InstallMethodNoCredentialsRequired InstallMethod = "no_credentials_required" + InstallMethodWithApiKey InstallMethod = "with_api_key" + InstallMethodWithOauth2 InstallMethod = "with_oauth2" +) + +// Valid indicates whether the value is a known member of the InstallMethod enum. +func (e InstallMethod) Valid() bool { + switch e { + case InstallMethodNoCredentialsRequired: + return true + case InstallMethodWithApiKey: + return true + case InstallMethodWithOauth2: + return true + default: + return false + } +} + +// Defines values for InvoiceDetailedLineType. +const ( + InvoiceDetailedLineTypeFlatFee InvoiceDetailedLineType = "flat_fee" +) + +// Valid indicates whether the value is a known member of the InvoiceDetailedLineType enum. +func (e InvoiceDetailedLineType) Valid() bool { + switch e { + case InvoiceDetailedLineTypeFlatFee: + return true + default: + return false + } +} + +// Defines values for InvoiceDetailedLineCostCategory. +const ( + InvoiceDetailedLineCostCategoryCommitment InvoiceDetailedLineCostCategory = "commitment" + InvoiceDetailedLineCostCategoryRegular InvoiceDetailedLineCostCategory = "regular" +) + +// Valid indicates whether the value is a known member of the InvoiceDetailedLineCostCategory enum. +func (e InvoiceDetailedLineCostCategory) Valid() bool { + switch e { + case InvoiceDetailedLineCostCategoryCommitment: + return true + case InvoiceDetailedLineCostCategoryRegular: + return true + default: + return false + } +} + +// Defines values for InvoiceDocumentRefType. +const ( + InvoiceDocumentRefTypeCreditNoteOriginalInvoice InvoiceDocumentRefType = "credit_note_original_invoice" +) + +// Valid indicates whether the value is a known member of the InvoiceDocumentRefType enum. +func (e InvoiceDocumentRefType) Valid() bool { + switch e { + case InvoiceDocumentRefTypeCreditNoteOriginalInvoice: + return true + default: + return false + } +} + +// Defines values for InvoiceExpand. +const ( + InvoiceExpandLines InvoiceExpand = "lines" + InvoiceExpandPreceding InvoiceExpand = "preceding" + InvoiceExpandWorkflowApps InvoiceExpand = "workflow.apps" +) + +// Valid indicates whether the value is a known member of the InvoiceExpand enum. +func (e InvoiceExpand) Valid() bool { + switch e { + case InvoiceExpandLines: + return true + case InvoiceExpandPreceding: + return true + case InvoiceExpandWorkflowApps: + return true + default: + return false + } +} + +// Defines values for InvoiceLineType. +const ( + InvoiceLineTypeUsageBased InvoiceLineType = "usage_based" +) + +// Valid indicates whether the value is a known member of the InvoiceLineType enum. +func (e InvoiceLineType) Valid() bool { + switch e { + case InvoiceLineTypeUsageBased: + return true + default: + return false + } +} + +// Defines values for InvoiceLineManagedBy. +const ( + InvoiceLineManagedByManual InvoiceLineManagedBy = "manual" + InvoiceLineManagedBySubscription InvoiceLineManagedBy = "subscription" + InvoiceLineManagedBySystem InvoiceLineManagedBy = "system" +) + +// Valid indicates whether the value is a known member of the InvoiceLineManagedBy enum. +func (e InvoiceLineManagedBy) Valid() bool { + switch e { + case InvoiceLineManagedByManual: + return true + case InvoiceLineManagedBySubscription: + return true + case InvoiceLineManagedBySystem: + return true + default: + return false + } +} + +// Defines values for InvoiceLineStatus. +const ( + InvoiceLineStatusDetailed InvoiceLineStatus = "detailed" + InvoiceLineStatusSplit InvoiceLineStatus = "split" + InvoiceLineStatusValid InvoiceLineStatus = "valid" +) + +// Valid indicates whether the value is a known member of the InvoiceLineStatus enum. +func (e InvoiceLineStatus) Valid() bool { + switch e { + case InvoiceLineStatusDetailed: + return true + case InvoiceLineStatusSplit: + return true + case InvoiceLineStatusValid: + return true + default: + return false + } +} + +// Defines values for InvoiceLineTaxBehavior. +const ( + InvoiceLineTaxBehaviorExclusive InvoiceLineTaxBehavior = "exclusive" + InvoiceLineTaxBehaviorInclusive InvoiceLineTaxBehavior = "inclusive" +) + +// Valid indicates whether the value is a known member of the InvoiceLineTaxBehavior enum. +func (e InvoiceLineTaxBehavior) Valid() bool { + switch e { + case InvoiceLineTaxBehaviorExclusive: + return true + case InvoiceLineTaxBehaviorInclusive: + return true + default: + return false + } +} + +// Defines values for InvoiceLineTypes. +const ( + InvoiceLineTypesFlatFee InvoiceLineTypes = "flat_fee" + InvoiceLineTypesUsageBased InvoiceLineTypes = "usage_based" +) + +// Valid indicates whether the value is a known member of the InvoiceLineTypes enum. +func (e InvoiceLineTypes) Valid() bool { + switch e { + case InvoiceLineTypesFlatFee: + return true + case InvoiceLineTypesUsageBased: + return true + default: + return false + } +} + +// Defines values for InvoiceOrderBy. +const ( + InvoiceOrderByCreatedAt InvoiceOrderBy = "createdAt" + InvoiceOrderByCustomerName InvoiceOrderBy = "customer.name" + InvoiceOrderByIssuedAt InvoiceOrderBy = "issuedAt" + InvoiceOrderByPeriodStart InvoiceOrderBy = "periodStart" + InvoiceOrderByStatus InvoiceOrderBy = "status" + InvoiceOrderByUpdatedAt InvoiceOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the InvoiceOrderBy enum. +func (e InvoiceOrderBy) Valid() bool { + switch e { + case InvoiceOrderByCreatedAt: + return true + case InvoiceOrderByCustomerName: + return true + case InvoiceOrderByIssuedAt: + return true + case InvoiceOrderByPeriodStart: + return true + case InvoiceOrderByStatus: + return true + case InvoiceOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for InvoiceStatus. +const ( + InvoiceStatusDraft InvoiceStatus = "draft" + InvoiceStatusGathering InvoiceStatus = "gathering" + InvoiceStatusIssued InvoiceStatus = "issued" + InvoiceStatusIssuing InvoiceStatus = "issuing" + InvoiceStatusOverdue InvoiceStatus = "overdue" + InvoiceStatusPaid InvoiceStatus = "paid" + InvoiceStatusPaymentProcessing InvoiceStatus = "payment_processing" + InvoiceStatusUncollectible InvoiceStatus = "uncollectible" + InvoiceStatusVoided InvoiceStatus = "voided" +) + +// Valid indicates whether the value is a known member of the InvoiceStatus enum. +func (e InvoiceStatus) Valid() bool { + switch e { + case InvoiceStatusDraft: + return true + case InvoiceStatusGathering: + return true + case InvoiceStatusIssued: + return true + case InvoiceStatusIssuing: + return true + case InvoiceStatusOverdue: + return true + case InvoiceStatusPaid: + return true + case InvoiceStatusPaymentProcessing: + return true + case InvoiceStatusUncollectible: + return true + case InvoiceStatusVoided: + return true + default: + return false + } +} + +// Defines values for InvoiceType. +const ( + InvoiceTypeCreditNote InvoiceType = "credit_note" + InvoiceTypeStandard InvoiceType = "standard" +) + +// Valid indicates whether the value is a known member of the InvoiceType enum. +func (e InvoiceType) Valid() bool { + switch e { + case InvoiceTypeCreditNote: + return true + case InvoiceTypeStandard: + return true + default: + return false + } +} + +// Defines values for MeasureUsageFromPreset. +const ( + MeasureUsageFromPresetCurrentPeriodStart MeasureUsageFromPreset = "CURRENT_PERIOD_START" + MeasureUsageFromPresetNow MeasureUsageFromPreset = "NOW" +) + +// Valid indicates whether the value is a known member of the MeasureUsageFromPreset enum. +func (e MeasureUsageFromPreset) Valid() bool { + switch e { + case MeasureUsageFromPresetCurrentPeriodStart: + return true + case MeasureUsageFromPresetNow: + return true + default: + return false + } +} + +// Defines values for MeterAggregation. +const ( + MeterAggregationAvg MeterAggregation = "AVG" + MeterAggregationCount MeterAggregation = "COUNT" + MeterAggregationLatest MeterAggregation = "LATEST" + MeterAggregationMax MeterAggregation = "MAX" + MeterAggregationMin MeterAggregation = "MIN" + MeterAggregationSum MeterAggregation = "SUM" + MeterAggregationUniqueCount MeterAggregation = "UNIQUE_COUNT" +) + +// Valid indicates whether the value is a known member of the MeterAggregation enum. +func (e MeterAggregation) Valid() bool { + switch e { + case MeterAggregationAvg: + return true + case MeterAggregationCount: + return true + case MeterAggregationLatest: + return true + case MeterAggregationMax: + return true + case MeterAggregationMin: + return true + case MeterAggregationSum: + return true + case MeterAggregationUniqueCount: + return true + default: + return false + } +} + +// Defines values for MeterOrderBy. +const ( + MeterOrderByAggregation MeterOrderBy = "aggregation" + MeterOrderByCreatedAt MeterOrderBy = "createdAt" + MeterOrderByKey MeterOrderBy = "key" + MeterOrderByName MeterOrderBy = "name" + MeterOrderByUpdatedAt MeterOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the MeterOrderBy enum. +func (e MeterOrderBy) Valid() bool { + switch e { + case MeterOrderByAggregation: + return true + case MeterOrderByCreatedAt: + return true + case MeterOrderByKey: + return true + case MeterOrderByName: + return true + case MeterOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for NotificationChannelOrderBy. +const ( + NotificationChannelOrderByCreatedAt NotificationChannelOrderBy = "createdAt" + NotificationChannelOrderById NotificationChannelOrderBy = "id" + NotificationChannelOrderByType NotificationChannelOrderBy = "type" + NotificationChannelOrderByUpdatedAt NotificationChannelOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the NotificationChannelOrderBy enum. +func (e NotificationChannelOrderBy) Valid() bool { + switch e { + case NotificationChannelOrderByCreatedAt: + return true + case NotificationChannelOrderById: + return true + case NotificationChannelOrderByType: + return true + case NotificationChannelOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for NotificationChannelType. +const ( + NotificationChannelTypeWebhook NotificationChannelType = "WEBHOOK" +) + +// Valid indicates whether the value is a known member of the NotificationChannelType enum. +func (e NotificationChannelType) Valid() bool { + switch e { + case NotificationChannelTypeWebhook: + return true + default: + return false + } +} + +// Defines values for NotificationChannelWebhookType. +const ( + NotificationChannelWebhookTypeWEBHOOK NotificationChannelWebhookType = "WEBHOOK" +) + +// Valid indicates whether the value is a known member of the NotificationChannelWebhookType enum. +func (e NotificationChannelWebhookType) Valid() bool { + switch e { + case NotificationChannelWebhookTypeWEBHOOK: + return true + default: + return false + } +} + +// Defines values for NotificationChannelWebhookCreateRequestType. +const ( + NotificationChannelWebhookCreateRequestTypeWEBHOOK NotificationChannelWebhookCreateRequestType = "WEBHOOK" +) + +// Valid indicates whether the value is a known member of the NotificationChannelWebhookCreateRequestType enum. +func (e NotificationChannelWebhookCreateRequestType) Valid() bool { + switch e { + case NotificationChannelWebhookCreateRequestTypeWEBHOOK: + return true + default: + return false + } +} + +// Defines values for NotificationEventBalanceThresholdPayloadType. +const ( + NotificationEventBalanceThresholdPayloadTypeEntitlementsBalanceThreshold NotificationEventBalanceThresholdPayloadType = "entitlements.balance.threshold" +) + +// Valid indicates whether the value is a known member of the NotificationEventBalanceThresholdPayloadType enum. +func (e NotificationEventBalanceThresholdPayloadType) Valid() bool { + switch e { + case NotificationEventBalanceThresholdPayloadTypeEntitlementsBalanceThreshold: + return true + default: + return false + } +} + +// Defines values for NotificationEventDeliveryStatusState. +const ( + NotificationEventDeliveryStatusStateFailed NotificationEventDeliveryStatusState = "FAILED" + NotificationEventDeliveryStatusStatePending NotificationEventDeliveryStatusState = "PENDING" + NotificationEventDeliveryStatusStateResending NotificationEventDeliveryStatusState = "RESENDING" + NotificationEventDeliveryStatusStateSending NotificationEventDeliveryStatusState = "SENDING" + NotificationEventDeliveryStatusStateSuccess NotificationEventDeliveryStatusState = "SUCCESS" +) + +// Valid indicates whether the value is a known member of the NotificationEventDeliveryStatusState enum. +func (e NotificationEventDeliveryStatusState) Valid() bool { + switch e { + case NotificationEventDeliveryStatusStateFailed: + return true + case NotificationEventDeliveryStatusStatePending: + return true + case NotificationEventDeliveryStatusStateResending: + return true + case NotificationEventDeliveryStatusStateSending: + return true + case NotificationEventDeliveryStatusStateSuccess: + return true + default: + return false + } +} + +// Defines values for NotificationEventInvoiceCreatedPayloadType. +const ( + NotificationEventInvoiceCreatedPayloadTypeInvoiceCreated NotificationEventInvoiceCreatedPayloadType = "invoice.created" +) + +// Valid indicates whether the value is a known member of the NotificationEventInvoiceCreatedPayloadType enum. +func (e NotificationEventInvoiceCreatedPayloadType) Valid() bool { + switch e { + case NotificationEventInvoiceCreatedPayloadTypeInvoiceCreated: + return true + default: + return false + } +} + +// Defines values for NotificationEventInvoiceUpdatedPayloadType. +const ( + NotificationEventInvoiceUpdatedPayloadTypeInvoiceUpdated NotificationEventInvoiceUpdatedPayloadType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationEventInvoiceUpdatedPayloadType enum. +func (e NotificationEventInvoiceUpdatedPayloadType) Valid() bool { + switch e { + case NotificationEventInvoiceUpdatedPayloadTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationEventOrderBy. +const ( + NotificationEventOrderByCreatedAt NotificationEventOrderBy = "createdAt" + NotificationEventOrderById NotificationEventOrderBy = "id" +) + +// Valid indicates whether the value is a known member of the NotificationEventOrderBy enum. +func (e NotificationEventOrderBy) Valid() bool { + switch e { + case NotificationEventOrderByCreatedAt: + return true + case NotificationEventOrderById: + return true + default: + return false + } +} + +// Defines values for NotificationEventResetPayloadType. +const ( + NotificationEventResetPayloadTypeEntitlementsReset NotificationEventResetPayloadType = "entitlements.reset" +) + +// Valid indicates whether the value is a known member of the NotificationEventResetPayloadType enum. +func (e NotificationEventResetPayloadType) Valid() bool { + switch e { + case NotificationEventResetPayloadTypeEntitlementsReset: + return true + default: + return false + } +} + +// Defines values for NotificationEventType. +const ( + NotificationEventTypeEntitlementsBalanceThreshold NotificationEventType = "entitlements.balance.threshold" + NotificationEventTypeEntitlementsReset NotificationEventType = "entitlements.reset" + NotificationEventTypeInvoiceCreated NotificationEventType = "invoice.created" + NotificationEventTypeInvoiceUpdated NotificationEventType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationEventType enum. +func (e NotificationEventType) Valid() bool { + switch e { + case NotificationEventTypeEntitlementsBalanceThreshold: + return true + case NotificationEventTypeEntitlementsReset: + return true + case NotificationEventTypeInvoiceCreated: + return true + case NotificationEventTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleBalanceThresholdType. +const ( + NotificationRuleBalanceThresholdTypeEntitlementsBalanceThreshold NotificationRuleBalanceThresholdType = "entitlements.balance.threshold" +) + +// Valid indicates whether the value is a known member of the NotificationRuleBalanceThresholdType enum. +func (e NotificationRuleBalanceThresholdType) Valid() bool { + switch e { + case NotificationRuleBalanceThresholdTypeEntitlementsBalanceThreshold: + return true + default: + return false + } +} + +// Defines values for NotificationRuleBalanceThresholdCreateRequestType. +const ( + NotificationRuleBalanceThresholdCreateRequestTypeEntitlementsBalanceThreshold NotificationRuleBalanceThresholdCreateRequestType = "entitlements.balance.threshold" +) + +// Valid indicates whether the value is a known member of the NotificationRuleBalanceThresholdCreateRequestType enum. +func (e NotificationRuleBalanceThresholdCreateRequestType) Valid() bool { + switch e { + case NotificationRuleBalanceThresholdCreateRequestTypeEntitlementsBalanceThreshold: + return true + default: + return false + } +} + +// Defines values for NotificationRuleBalanceThresholdValueType. +const ( + NotificationRuleBalanceThresholdValueTypeBalanceValue NotificationRuleBalanceThresholdValueType = "balance_value" + NotificationRuleBalanceThresholdValueTypeNumber NotificationRuleBalanceThresholdValueType = "NUMBER" + NotificationRuleBalanceThresholdValueTypePercent NotificationRuleBalanceThresholdValueType = "PERCENT" + NotificationRuleBalanceThresholdValueTypeUsagePercentage NotificationRuleBalanceThresholdValueType = "usage_percentage" + NotificationRuleBalanceThresholdValueTypeUsageValue NotificationRuleBalanceThresholdValueType = "usage_value" +) + +// Valid indicates whether the value is a known member of the NotificationRuleBalanceThresholdValueType enum. +func (e NotificationRuleBalanceThresholdValueType) Valid() bool { + switch e { + case NotificationRuleBalanceThresholdValueTypeBalanceValue: + return true + case NotificationRuleBalanceThresholdValueTypeNumber: + return true + case NotificationRuleBalanceThresholdValueTypePercent: + return true + case NotificationRuleBalanceThresholdValueTypeUsagePercentage: + return true + case NotificationRuleBalanceThresholdValueTypeUsageValue: + return true + default: + return false + } +} + +// Defines values for NotificationRuleEntitlementResetType. +const ( + NotificationRuleEntitlementResetTypeEntitlementsReset NotificationRuleEntitlementResetType = "entitlements.reset" +) + +// Valid indicates whether the value is a known member of the NotificationRuleEntitlementResetType enum. +func (e NotificationRuleEntitlementResetType) Valid() bool { + switch e { + case NotificationRuleEntitlementResetTypeEntitlementsReset: + return true + default: + return false + } +} + +// Defines values for NotificationRuleEntitlementResetCreateRequestType. +const ( + NotificationRuleEntitlementResetCreateRequestTypeEntitlementsReset NotificationRuleEntitlementResetCreateRequestType = "entitlements.reset" +) + +// Valid indicates whether the value is a known member of the NotificationRuleEntitlementResetCreateRequestType enum. +func (e NotificationRuleEntitlementResetCreateRequestType) Valid() bool { + switch e { + case NotificationRuleEntitlementResetCreateRequestTypeEntitlementsReset: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceCreatedType. +const ( + NotificationRuleInvoiceCreatedTypeInvoiceCreated NotificationRuleInvoiceCreatedType = "invoice.created" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceCreatedType enum. +func (e NotificationRuleInvoiceCreatedType) Valid() bool { + switch e { + case NotificationRuleInvoiceCreatedTypeInvoiceCreated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceCreatedCreateRequestType. +const ( + NotificationRuleInvoiceCreatedCreateRequestTypeInvoiceCreated NotificationRuleInvoiceCreatedCreateRequestType = "invoice.created" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceCreatedCreateRequestType enum. +func (e NotificationRuleInvoiceCreatedCreateRequestType) Valid() bool { + switch e { + case NotificationRuleInvoiceCreatedCreateRequestTypeInvoiceCreated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceUpdatedType. +const ( + NotificationRuleInvoiceUpdatedTypeInvoiceUpdated NotificationRuleInvoiceUpdatedType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceUpdatedType enum. +func (e NotificationRuleInvoiceUpdatedType) Valid() bool { + switch e { + case NotificationRuleInvoiceUpdatedTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceUpdatedCreateRequestType. +const ( + NotificationRuleInvoiceUpdatedCreateRequestTypeInvoiceUpdated NotificationRuleInvoiceUpdatedCreateRequestType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceUpdatedCreateRequestType enum. +func (e NotificationRuleInvoiceUpdatedCreateRequestType) Valid() bool { + switch e { + case NotificationRuleInvoiceUpdatedCreateRequestTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleOrderBy. +const ( + NotificationRuleOrderByCreatedAt NotificationRuleOrderBy = "createdAt" + NotificationRuleOrderById NotificationRuleOrderBy = "id" + NotificationRuleOrderByType NotificationRuleOrderBy = "type" + NotificationRuleOrderByUpdatedAt NotificationRuleOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the NotificationRuleOrderBy enum. +func (e NotificationRuleOrderBy) Valid() bool { + switch e { + case NotificationRuleOrderByCreatedAt: + return true + case NotificationRuleOrderById: + return true + case NotificationRuleOrderByType: + return true + case NotificationRuleOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for OAuth2AuthorizationCodeGrantErrorType. +const ( + OAuth2AuthorizationCodeGrantErrorTypeAccessDenied OAuth2AuthorizationCodeGrantErrorType = "access_denied" + OAuth2AuthorizationCodeGrantErrorTypeInvalidRequest OAuth2AuthorizationCodeGrantErrorType = "invalid_request" + OAuth2AuthorizationCodeGrantErrorTypeInvalidScope OAuth2AuthorizationCodeGrantErrorType = "invalid_scope" + OAuth2AuthorizationCodeGrantErrorTypeServerError OAuth2AuthorizationCodeGrantErrorType = "server_error" + OAuth2AuthorizationCodeGrantErrorTypeTemporarilyUnavailable OAuth2AuthorizationCodeGrantErrorType = "temporarily_unavailable" + OAuth2AuthorizationCodeGrantErrorTypeUnauthorizedClient OAuth2AuthorizationCodeGrantErrorType = "unauthorized_client" + OAuth2AuthorizationCodeGrantErrorTypeUnsupportedResponseType OAuth2AuthorizationCodeGrantErrorType = "unsupported_response_type" +) + +// Valid indicates whether the value is a known member of the OAuth2AuthorizationCodeGrantErrorType enum. +func (e OAuth2AuthorizationCodeGrantErrorType) Valid() bool { + switch e { + case OAuth2AuthorizationCodeGrantErrorTypeAccessDenied: + return true + case OAuth2AuthorizationCodeGrantErrorTypeInvalidRequest: + return true + case OAuth2AuthorizationCodeGrantErrorTypeInvalidScope: + return true + case OAuth2AuthorizationCodeGrantErrorTypeServerError: + return true + case OAuth2AuthorizationCodeGrantErrorTypeTemporarilyUnavailable: + return true + case OAuth2AuthorizationCodeGrantErrorTypeUnauthorizedClient: + return true + case OAuth2AuthorizationCodeGrantErrorTypeUnsupportedResponseType: + return true + default: + return false + } +} + +// Defines values for PackagePriceType. +const ( + PackagePriceTypePackage PackagePriceType = "package" +) + +// Valid indicates whether the value is a known member of the PackagePriceType enum. +func (e PackagePriceType) Valid() bool { + switch e { + case PackagePriceTypePackage: + return true + default: + return false + } +} + +// Defines values for PackagePriceWithCommitmentsType. +const ( + PackagePriceWithCommitmentsTypePackage PackagePriceWithCommitmentsType = "package" +) + +// Valid indicates whether the value is a known member of the PackagePriceWithCommitmentsType enum. +func (e PackagePriceWithCommitmentsType) Valid() bool { + switch e { + case PackagePriceWithCommitmentsTypePackage: + return true + default: + return false + } +} + +// Defines values for PaymentTermDueDateType. +const ( + PaymentTermDueDateTypeDueDate PaymentTermDueDateType = "due_date" +) + +// Valid indicates whether the value is a known member of the PaymentTermDueDateType enum. +func (e PaymentTermDueDateType) Valid() bool { + switch e { + case PaymentTermDueDateTypeDueDate: + return true + default: + return false + } +} + +// Defines values for PaymentTermInstantType. +const ( + PaymentTermInstantTypeInstant PaymentTermInstantType = "instant" +) + +// Valid indicates whether the value is a known member of the PaymentTermInstantType enum. +func (e PaymentTermInstantType) Valid() bool { + switch e { + case PaymentTermInstantTypeInstant: + return true + default: + return false + } +} + +// Defines values for PaymentTermType. +const ( + PaymentTermTypeDueDate PaymentTermType = "due_date" + PaymentTermTypeInstant PaymentTermType = "instant" +) + +// Valid indicates whether the value is a known member of the PaymentTermType enum. +func (e PaymentTermType) Valid() bool { + switch e { + case PaymentTermTypeDueDate: + return true + case PaymentTermTypeInstant: + return true + default: + return false + } +} + +// Defines values for PlanAddonOrderBy. +const ( + PlanAddonOrderByCreatedAt PlanAddonOrderBy = "created_at" + PlanAddonOrderById PlanAddonOrderBy = "id" + PlanAddonOrderByKey PlanAddonOrderBy = "key" + PlanAddonOrderByUpdatedAt PlanAddonOrderBy = "updated_at" + PlanAddonOrderByVersion PlanAddonOrderBy = "version" +) + +// Valid indicates whether the value is a known member of the PlanAddonOrderBy enum. +func (e PlanAddonOrderBy) Valid() bool { + switch e { + case PlanAddonOrderByCreatedAt: + return true + case PlanAddonOrderById: + return true + case PlanAddonOrderByKey: + return true + case PlanAddonOrderByUpdatedAt: + return true + case PlanAddonOrderByVersion: + return true + default: + return false + } +} + +// Defines values for PlanOrderBy. +const ( + PlanOrderByCreatedAt PlanOrderBy = "created_at" + PlanOrderById PlanOrderBy = "id" + PlanOrderByKey PlanOrderBy = "key" + PlanOrderByUpdatedAt PlanOrderBy = "updated_at" + PlanOrderByVersion PlanOrderBy = "version" +) + +// Valid indicates whether the value is a known member of the PlanOrderBy enum. +func (e PlanOrderBy) Valid() bool { + switch e { + case PlanOrderByCreatedAt: + return true + case PlanOrderById: + return true + case PlanOrderByKey: + return true + case PlanOrderByUpdatedAt: + return true + case PlanOrderByVersion: + return true + default: + return false + } +} + +// Defines values for PlanStatus. +const ( + PlanStatusActive PlanStatus = "active" + PlanStatusArchived PlanStatus = "archived" + PlanStatusDraft PlanStatus = "draft" + PlanStatusScheduled PlanStatus = "scheduled" +) + +// Valid indicates whether the value is a known member of the PlanStatus enum. +func (e PlanStatus) Valid() bool { + switch e { + case PlanStatusActive: + return true + case PlanStatusArchived: + return true + case PlanStatusDraft: + return true + case PlanStatusScheduled: + return true + default: + return false + } +} + +// Defines values for PricePaymentTerm. +const ( + PricePaymentTermInAdvance PricePaymentTerm = "in_advance" + PricePaymentTermInArrears PricePaymentTerm = "in_arrears" +) + +// Valid indicates whether the value is a known member of the PricePaymentTerm enum. +func (e PricePaymentTerm) Valid() bool { + switch e { + case PricePaymentTermInAdvance: + return true + case PricePaymentTermInArrears: + return true + default: + return false + } +} + +// Defines values for PriceType. +const ( + PriceTypeDynamic PriceType = "dynamic" + PriceTypeFlat PriceType = "flat" + PriceTypePackage PriceType = "package" + PriceTypeTiered PriceType = "tiered" + PriceTypeUnit PriceType = "unit" +) + +// Valid indicates whether the value is a known member of the PriceType enum. +func (e PriceType) Valid() bool { + switch e { + case PriceTypeDynamic: + return true + case PriceTypeFlat: + return true + case PriceTypePackage: + return true + case PriceTypeTiered: + return true + case PriceTypeUnit: + return true + default: + return false + } +} + +// Defines values for ProRatingMode. +const ( + ProRatingModeProratePrices ProRatingMode = "prorate_prices" +) + +// Valid indicates whether the value is a known member of the ProRatingMode enum. +func (e ProRatingMode) Valid() bool { + switch e { + case ProRatingModeProratePrices: + return true + default: + return false + } +} + +// Defines values for RateCardBooleanEntitlementType. +const ( + RateCardBooleanEntitlementTypeBoolean RateCardBooleanEntitlementType = "boolean" +) + +// Valid indicates whether the value is a known member of the RateCardBooleanEntitlementType enum. +func (e RateCardBooleanEntitlementType) Valid() bool { + switch e { + case RateCardBooleanEntitlementTypeBoolean: + return true + default: + return false + } +} + +// Defines values for RateCardFlatFeeType. +const ( + RateCardFlatFeeTypeFlatFee RateCardFlatFeeType = "flat_fee" +) + +// Valid indicates whether the value is a known member of the RateCardFlatFeeType enum. +func (e RateCardFlatFeeType) Valid() bool { + switch e { + case RateCardFlatFeeTypeFlatFee: + return true + default: + return false + } +} + +// Defines values for RateCardMeteredEntitlementType. +const ( + RateCardMeteredEntitlementTypeMetered RateCardMeteredEntitlementType = "metered" +) + +// Valid indicates whether the value is a known member of the RateCardMeteredEntitlementType enum. +func (e RateCardMeteredEntitlementType) Valid() bool { + switch e { + case RateCardMeteredEntitlementTypeMetered: + return true + default: + return false + } +} + +// Defines values for RateCardStaticEntitlementType. +const ( + RateCardStaticEntitlementTypeStatic RateCardStaticEntitlementType = "static" +) + +// Valid indicates whether the value is a known member of the RateCardStaticEntitlementType enum. +func (e RateCardStaticEntitlementType) Valid() bool { + switch e { + case RateCardStaticEntitlementTypeStatic: + return true + default: + return false + } +} + +// Defines values for RateCardType. +const ( + RateCardTypeFlatFee RateCardType = "flat_fee" + RateCardTypeUsageBased RateCardType = "usage_based" +) + +// Valid indicates whether the value is a known member of the RateCardType enum. +func (e RateCardType) Valid() bool { + switch e { + case RateCardTypeFlatFee: + return true + case RateCardTypeUsageBased: + return true + default: + return false + } +} + +// Defines values for RateCardUsageBasedType. +const ( + RateCardUsageBasedTypeUsageBased RateCardUsageBasedType = "usage_based" +) + +// Valid indicates whether the value is a known member of the RateCardUsageBasedType enum. +func (e RateCardUsageBasedType) Valid() bool { + switch e { + case RateCardUsageBasedTypeUsageBased: + return true + default: + return false + } +} + +// Defines values for RecurringPeriodIntervalEnum. +const ( + RecurringPeriodIntervalEnumDAY RecurringPeriodIntervalEnum = "DAY" + RecurringPeriodIntervalEnumMONTH RecurringPeriodIntervalEnum = "MONTH" + RecurringPeriodIntervalEnumWEEK RecurringPeriodIntervalEnum = "WEEK" + RecurringPeriodIntervalEnumYEAR RecurringPeriodIntervalEnum = "YEAR" +) + +// Valid indicates whether the value is a known member of the RecurringPeriodIntervalEnum enum. +func (e RecurringPeriodIntervalEnum) Valid() bool { + switch e { + case RecurringPeriodIntervalEnumDAY: + return true + case RecurringPeriodIntervalEnumMONTH: + return true + case RecurringPeriodIntervalEnumWEEK: + return true + case RecurringPeriodIntervalEnumYEAR: + return true + default: + return false + } +} + +// Defines values for RemovePhaseShifting. +const ( + RemovePhaseShiftingNext RemovePhaseShifting = "next" + RemovePhaseShiftingPrev RemovePhaseShifting = "prev" +) + +// Valid indicates whether the value is a known member of the RemovePhaseShifting enum. +func (e RemovePhaseShifting) Valid() bool { + switch e { + case RemovePhaseShiftingNext: + return true + case RemovePhaseShiftingPrev: + return true + default: + return false + } +} + +// Defines values for SandboxAppType. +const ( + SandboxAppTypeSandbox SandboxAppType = "sandbox" +) + +// Valid indicates whether the value is a known member of the SandboxAppType enum. +func (e SandboxAppType) Valid() bool { + switch e { + case SandboxAppTypeSandbox: + return true + default: + return false + } +} + +// Defines values for SandboxAppReplaceUpdateType. +const ( + SandboxAppReplaceUpdateTypeSandbox SandboxAppReplaceUpdateType = "sandbox" +) + +// Valid indicates whether the value is a known member of the SandboxAppReplaceUpdateType enum. +func (e SandboxAppReplaceUpdateType) Valid() bool { + switch e { + case SandboxAppReplaceUpdateTypeSandbox: + return true + default: + return false + } +} + +// Defines values for SandboxCustomerAppDataType. +const ( + SandboxCustomerAppDataTypeSandbox SandboxCustomerAppDataType = "sandbox" +) + +// Valid indicates whether the value is a known member of the SandboxCustomerAppDataType enum. +func (e SandboxCustomerAppDataType) Valid() bool { + switch e { + case SandboxCustomerAppDataTypeSandbox: + return true + default: + return false + } +} + +// Defines values for SortOrder. +const ( + SortOrderASC SortOrder = "ASC" + SortOrderDESC SortOrder = "DESC" +) + +// Valid indicates whether the value is a known member of the SortOrder enum. +func (e SortOrder) Valid() bool { + switch e { + case SortOrderASC: + return true + case SortOrderDESC: + return true + default: + return false + } +} + +// Defines values for StripeAppType. +const ( + StripeAppTypeStripe StripeAppType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeAppType enum. +func (e StripeAppType) Valid() bool { + switch e { + case StripeAppTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType. +const ( + StripeAppReadOrCreateOrUpdateOrDeleteOrQueryTypeStripe StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType enum. +func (e StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType) Valid() bool { + switch e { + case StripeAppReadOrCreateOrUpdateOrDeleteOrQueryTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeAppReplaceUpdateType. +const ( + StripeAppReplaceUpdateTypeStripe StripeAppReplaceUpdateType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeAppReplaceUpdateType enum. +func (e StripeAppReplaceUpdateType) Valid() bool { + switch e { + case StripeAppReplaceUpdateTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeCheckoutSessionMode. +const ( + StripeCheckoutSessionModeSetup StripeCheckoutSessionMode = "setup" +) + +// Valid indicates whether the value is a known member of the StripeCheckoutSessionMode enum. +func (e StripeCheckoutSessionMode) Valid() bool { + switch e { + case StripeCheckoutSessionModeSetup: + return true + default: + return false + } +} + +// Defines values for StripeCustomerAppDataType. +const ( + StripeCustomerAppDataTypeStripe StripeCustomerAppDataType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeCustomerAppDataType enum. +func (e StripeCustomerAppDataType) Valid() bool { + switch e { + case StripeCustomerAppDataTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeCustomerAppDataCreateOrUpdateItemType. +const ( + StripeCustomerAppDataCreateOrUpdateItemTypeStripe StripeCustomerAppDataCreateOrUpdateItemType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeCustomerAppDataCreateOrUpdateItemType enum. +func (e StripeCustomerAppDataCreateOrUpdateItemType) Valid() bool { + switch e { + case StripeCustomerAppDataCreateOrUpdateItemTypeStripe: + return true + default: + return false + } +} + +// Defines values for SubscriptionStatus. +const ( + SubscriptionStatusActive SubscriptionStatus = "active" + SubscriptionStatusCanceled SubscriptionStatus = "canceled" + SubscriptionStatusInactive SubscriptionStatus = "inactive" + SubscriptionStatusScheduled SubscriptionStatus = "scheduled" +) + +// Valid indicates whether the value is a known member of the SubscriptionStatus enum. +func (e SubscriptionStatus) Valid() bool { + switch e { + case SubscriptionStatusActive: + return true + case SubscriptionStatusCanceled: + return true + case SubscriptionStatusInactive: + return true + case SubscriptionStatusScheduled: + return true + default: + return false + } +} + +// Defines values for SubscriptionTimingEnum. +const ( + SubscriptionTimingEnumImmediate SubscriptionTimingEnum = "immediate" + SubscriptionTimingEnumNextBillingCycle SubscriptionTimingEnum = "next_billing_cycle" +) + +// Valid indicates whether the value is a known member of the SubscriptionTimingEnum enum. +func (e SubscriptionTimingEnum) Valid() bool { + switch e { + case SubscriptionTimingEnumImmediate: + return true + case SubscriptionTimingEnumNextBillingCycle: + return true + default: + return false + } +} + +// Defines values for TaxBehavior. +const ( + TaxBehaviorExclusive TaxBehavior = "exclusive" + TaxBehaviorInclusive TaxBehavior = "inclusive" +) + +// Valid indicates whether the value is a known member of the TaxBehavior enum. +func (e TaxBehavior) Valid() bool { + switch e { + case TaxBehaviorExclusive: + return true + case TaxBehaviorInclusive: + return true + default: + return false + } +} + +// Defines values for TieredPriceType. +const ( + TieredPriceTypeTiered TieredPriceType = "tiered" +) + +// Valid indicates whether the value is a known member of the TieredPriceType enum. +func (e TieredPriceType) Valid() bool { + switch e { + case TieredPriceTypeTiered: + return true + default: + return false + } +} + +// Defines values for TieredPriceMode. +const ( + TieredPriceModeGraduated TieredPriceMode = "graduated" + TieredPriceModeVolume TieredPriceMode = "volume" +) + +// Valid indicates whether the value is a known member of the TieredPriceMode enum. +func (e TieredPriceMode) Valid() bool { + switch e { + case TieredPriceModeGraduated: + return true + case TieredPriceModeVolume: + return true + default: + return false + } +} + +// Defines values for TieredPriceWithCommitmentsType. +const ( + TieredPriceWithCommitmentsTypeTiered TieredPriceWithCommitmentsType = "tiered" +) + +// Valid indicates whether the value is a known member of the TieredPriceWithCommitmentsType enum. +func (e TieredPriceWithCommitmentsType) Valid() bool { + switch e { + case TieredPriceWithCommitmentsTypeTiered: + return true + default: + return false + } +} + +// Defines values for UnitPriceType. +const ( + UnitPriceTypeUnit UnitPriceType = "unit" +) + +// Valid indicates whether the value is a known member of the UnitPriceType enum. +func (e UnitPriceType) Valid() bool { + switch e { + case UnitPriceTypeUnit: + return true + default: + return false + } +} + +// Defines values for UnitPriceWithCommitmentsType. +const ( + UnitPriceWithCommitmentsTypeUnit UnitPriceWithCommitmentsType = "unit" +) + +// Valid indicates whether the value is a known member of the UnitPriceWithCommitmentsType enum. +func (e UnitPriceWithCommitmentsType) Valid() bool { + switch e { + case UnitPriceWithCommitmentsTypeUnit: + return true + default: + return false + } +} + +// Defines values for ValidationIssueSeverity. +const ( + ValidationIssueSeverityCritical ValidationIssueSeverity = "critical" + ValidationIssueSeverityWarning ValidationIssueSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the ValidationIssueSeverity enum. +func (e ValidationIssueSeverity) Valid() bool { + switch e { + case ValidationIssueSeverityCritical: + return true + case ValidationIssueSeverityWarning: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLineActionType. +const ( + VoidInvoiceLineActionTypeDiscard VoidInvoiceLineActionType = "discard" + VoidInvoiceLineActionTypePending VoidInvoiceLineActionType = "pending" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLineActionType enum. +func (e VoidInvoiceLineActionType) Valid() bool { + switch e { + case VoidInvoiceLineActionTypeDiscard: + return true + case VoidInvoiceLineActionTypePending: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLineDiscardActionType. +const ( + VoidInvoiceLineDiscardActionTypeDiscard VoidInvoiceLineDiscardActionType = "discard" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLineDiscardActionType enum. +func (e VoidInvoiceLineDiscardActionType) Valid() bool { + switch e { + case VoidInvoiceLineDiscardActionTypeDiscard: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLinePendingActionCreateType. +const ( + VoidInvoiceLinePendingActionCreateTypePending VoidInvoiceLinePendingActionCreateType = "pending" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLinePendingActionCreateType enum. +func (e VoidInvoiceLinePendingActionCreateType) Valid() bool { + switch e { + case VoidInvoiceLinePendingActionCreateTypePending: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLinePendingActionCreateItemType. +const ( + VoidInvoiceLinePendingActionCreateItemTypePending VoidInvoiceLinePendingActionCreateItemType = "pending" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLinePendingActionCreateItemType enum. +func (e VoidInvoiceLinePendingActionCreateItemType) Valid() bool { + switch e { + case VoidInvoiceLinePendingActionCreateItemTypePending: + return true + default: + return false + } +} + +// Defines values for WindowSize. +const ( + WindowSizeDay WindowSize = "DAY" + WindowSizeHour WindowSize = "HOUR" + WindowSizeMinute WindowSize = "MINUTE" + WindowSizeMonth WindowSize = "MONTH" +) + +// Valid indicates whether the value is a known member of the WindowSize enum. +func (e WindowSize) Valid() bool { + switch e { + case WindowSizeDay: + return true + case WindowSizeHour: + return true + case WindowSizeMinute: + return true + case WindowSizeMonth: + return true + default: + return false + } +} + +// Addon Add-on allows extending subscriptions with compatible plans with additional ratecards. +type Addon struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the add-on. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EffectiveFrom The date and time when the add-on becomes effective. When not specified, the add-on is a draft. + EffectiveFrom *time.Time `json:"effectiveFrom,omitempty"` + + // EffectiveTo The date and time when the add-on is no longer effective. When not specified, the add-on is effective indefinitely. + EffectiveTo *time.Time `json:"effectiveTo,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // InstanceType The instanceType of the add-ons. Can be "single" or "multiple". + InstanceType AddonInstanceType `json:"instanceType"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the add-on. + RateCards []RateCard `json:"rateCards"` + + // Status The status of the add-on. + // Computed based on the effective start and end dates: + // - draft = no effectiveFrom + // - active = effectiveFrom <= now < effectiveTo + // - archived = effectiveTo <= now + Status AddonStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationErrors List of validation errors. + ValidationErrors *[]ValidationError `json:"validationErrors"` + + // Version Version of the add-on. Incremented when the add-on is updated. + Version int `json:"version"` +} + +// AddonCreate Resource create operation model. +type AddonCreate struct { + // Currency The currency code of the add-on. + Currency CurrencyCode `json:"currency"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // InstanceType The instanceType of the add-ons. Can be "single" or "multiple". + InstanceType AddonInstanceType `json:"instanceType"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the add-on. + RateCards []RateCard `json:"rateCards"` +} + +// AddonInstanceType The instanceType of the add-on. +// Single instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once. +type AddonInstanceType string + +// AddonOrderBy Order by options for add-ons. +type AddonOrderBy string + +// AddonPaginatedResponse Paginated response +type AddonPaginatedResponse struct { + // Items The items in the current page. + Items []Addon `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// AddonReplaceUpdate Resource update operation model. +type AddonReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // InstanceType The instanceType of the add-ons. Can be "single" or "multiple". + InstanceType AddonInstanceType `json:"instanceType"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the add-on. + RateCards []RateCard `json:"rateCards"` +} + +// AddonStatus The status of the add-on defined by the effectiveFrom and effectiveTo properties. +type AddonStatus string + +// Address Address +type Address struct { + // City City. + City *string `json:"city,omitempty"` + + // Country Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format. + Country *CountryCode `json:"country,omitempty"` + + // Line1 First line of the address. + Line1 *string `json:"line1,omitempty"` + + // Line2 Second line of the address. + Line2 *string `json:"line2,omitempty"` + + // PhoneNumber Phone number. + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // PostalCode Postal code. + PostalCode *string `json:"postalCode,omitempty"` + + // State State or province. + State *string `json:"state,omitempty"` +} + +// Alignment Alignment configuration for a plan or subscription. +type Alignment struct { + // BillablesMustAlign Whether all Billable items and RateCards must align. + // Alignment means the Price's BillingCadence must align for both duration and anchor time. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + BillablesMustAlign *bool `json:"billablesMustAlign,omitempty"` +} + +// Annotations Set of key-value pairs managed by the system. Cannot be modified by user. +type Annotations map[string]interface{} + +// App App. +// One of: stripe +type App struct { + union json.RawMessage +} + +// AppBase Abstract base model for installed apps. +// +// Represent an app installed to the organization. +// This is an actual instance, with its own configuration and credentials. +type AppBase struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// AppCapability App capability. +// +// Capabilities only exist in config so they don't extend the Resource model. +type AppCapability struct { + // Description The capability description. + Description string `json:"description"` + + // Key Key + Key string `json:"key"` + + // Name The capability name. + Name string `json:"name"` + + // Type The capability type. + Type AppCapabilityType `json:"type"` +} + +// AppCapabilityType App capability type. +type AppCapabilityType string + +// AppPaginatedResponse Paginated response +type AppPaginatedResponse struct { + // Items The items in the current page. + Items []App `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// AppReadOrCreateOrUpdateOrDeleteOrQuery App. +// One of: stripe +type AppReadOrCreateOrUpdateOrDeleteOrQuery struct { + union json.RawMessage +} + +// AppReference App reference +// +// Can be used as a short reference to an app if the full app object is not needed. +type AppReference struct { + // Id The ID of the app. + Id string `json:"id"` +} + +// AppReplaceUpdate App ReplaceUpdate Model +type AppReplaceUpdate struct { + union json.RawMessage +} + +// AppStatus App installed status. +type AppStatus string + +// AppType Type of the app. +type AppType string + +// BadRequestProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type BadRequestProblemResponse = UnexpectedProblemResponse + +// BalanceHistoryWindow The balance history window. +type BalanceHistoryWindow struct { + // BalanceAtStart The entitlement balance at the start of the period. + BalanceAtStart float64 `json:"balanceAtStart"` + + // Period A period with a start and end time. + Period Period `json:"period"` + + // Usage The total usage of the feature in the period. + Usage float64 `json:"usage"` +} + +// BillingCollectionAlignment BillingCollectionAlignment specifies when the pending line items should be collected into +// an invoice. +type BillingCollectionAlignment string + +// BillingCustomerProfile Customer specific merged profile. +// +// This profile is calculated from the customer override and the billing profile it references or the default. +// +// Thus this does not have any kind of resource fields, only the calculated values. +type BillingCustomerProfile struct { + // Apps The applications used by this billing profile. + // + // Expand settings govern if this includes the whole app object or just the ID references. + Apps BillingProfileAppsOrReference `json:"apps"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // Workflow The billing workflow settings for this profile + Workflow BillingWorkflow `json:"workflow"` +} + +// BillingDiscountMetadata Billing specific fields for product catalog discounts. +type BillingDiscountMetadata struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` +} + +// BillingDiscountPercentage A percentage discount. +type BillingDiscountPercentage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Percentage The percentage of the discount. + Percentage Percentage `json:"percentage"` +} + +// BillingDiscountReason The reason for the discount. +type BillingDiscountReason struct { + union json.RawMessage +} + +// BillingDiscountUsage A usage discount. +type BillingDiscountUsage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Quantity The quantity of the usage discount. + // + // Must be positive. + Quantity Numeric `json:"quantity"` +} + +// BillingDiscounts A discount by type. +type BillingDiscounts struct { + // Percentage The percentage discount. + Percentage *BillingDiscountPercentage `json:"percentage,omitempty"` + + // Usage The usage discount. + Usage *BillingDiscountUsage `json:"usage,omitempty"` +} + +// BillingInvoiceCustomerExtendedDetails BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the billing party details for invoices. +// +// These fields contain the OpenMeter specific details for the customer, that are not strictly required for the invoice itself. +type BillingInvoiceCustomerExtendedDetails struct { + // Addresses Regular post addresses for where information should be sent if needed. + Addresses *[]Address `json:"addresses,omitempty"` + + // Id Unique identifier for the party (if available) + Id *string `json:"id,omitempty"` + + // Key An optional unique key of the party (if available) + Key *string `json:"key,omitempty"` + + // Name Legal name or representation of the organization. + Name *string `json:"name,omitempty"` + + // TaxId The entity's legal ID code used for tax purposes. They may have + // other numbers, but we're only interested in those valid for tax purposes. + TaxId *BillingPartyTaxIdentity `json:"taxId,omitempty"` + + // UsageAttribution Mapping to attribute metered usage to the customer + UsageAttribution CustomerUsageAttribution `json:"usageAttribution"` +} + +// BillingParty Party represents a person or business entity. +type BillingParty struct { + // Addresses Regular post addresses for where information should be sent if needed. + Addresses *[]Address `json:"addresses,omitempty"` + + // Id Unique identifier for the party (if available) + Id *string `json:"id,omitempty"` + + // Key An optional unique key of the party (if available) + Key *string `json:"key,omitempty"` + + // Name Legal name or representation of the organization. + Name *string `json:"name,omitempty"` + + // TaxId The entity's legal ID code used for tax purposes. They may have + // other numbers, but we're only interested in those valid for tax purposes. + TaxId *BillingPartyTaxIdentity `json:"taxId,omitempty"` +} + +// BillingPartyReplaceUpdate Resource update operation model. +type BillingPartyReplaceUpdate struct { + // Addresses Regular post addresses for where information should be sent if needed. + Addresses *[]Address `json:"addresses,omitempty"` + + // Key An optional unique key of the party (if available) + Key *string `json:"key,omitempty"` + + // Name Legal name or representation of the organization. + Name *string `json:"name,omitempty"` + + // TaxId The entity's legal ID code used for tax purposes. They may have + // other numbers, but we're only interested in those valid for tax purposes. + TaxId *BillingPartyTaxIdentity `json:"taxId,omitempty"` +} + +// BillingPartyTaxIdentity Identity stores the details required to identify an entity for tax purposes in a specific country. +type BillingPartyTaxIdentity struct { + // Code Normalized tax code shown on the original identity document. + Code *BillingTaxIdentificationCode `json:"code,omitempty"` +} + +// BillingProfile BillingProfile represents a billing profile +type BillingProfile struct { + // Apps The applications used by this billing profile. + // + // Expand settings govern if this includes the whole app object or just the ID references. + Apps BillingProfileAppsOrReference `json:"apps"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Default Is this the default profile? + Default bool `json:"default"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // Workflow The billing workflow settings for this profile + Workflow BillingWorkflow `json:"workflow"` +} + +// BillingProfileAppReferences BillingProfileAppReferences represents the references (id, type) to the apps used by a billing profile +type BillingProfileAppReferences struct { + // Invoicing The invoicing app used for this workflow + Invoicing AppReference `json:"invoicing"` + + // Payment The payment app used for this workflow + Payment AppReference `json:"payment"` + + // Tax The tax app used for this workflow + Tax AppReference `json:"tax"` +} + +// BillingProfileApps BillingProfileApps represents the applications used by a billing profile +type BillingProfileApps struct { + // Invoicing The invoicing app used for this workflow + Invoicing App `json:"invoicing"` + + // Payment The payment app used for this workflow + Payment App `json:"payment"` + + // Tax The tax app used for this workflow + Tax App `json:"tax"` +} + +// BillingProfileAppsCreate BillingProfileAppsCreate represents the input for creating a billing profile's apps +type BillingProfileAppsCreate struct { + // Invoicing The invoicing app used for this workflow + Invoicing string `json:"invoicing"` + + // Payment The payment app used for this workflow + Payment string `json:"payment"` + + // Tax The tax app used for this workflow + Tax string `json:"tax"` +} + +// BillingProfileAppsOrReference ProfileAppsOrReference represents the union of ProfileApps and ProfileAppReferences +// for a billing profile. +type BillingProfileAppsOrReference struct { + union json.RawMessage +} + +// BillingProfileCreate BillingProfileCreate represents the input for creating a billing profile +type BillingProfileCreate struct { + // Apps The apps used by this billing profile. + Apps BillingProfileAppsCreate `json:"apps"` + + // Default Is this the default profile? + Default bool `json:"default"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // Workflow The billing workflow settings for this profile. + Workflow BillingWorkflowCreate `json:"workflow"` +} + +// BillingProfileCustomerOverride Customer override values. +type BillingProfileCustomerOverride struct { + // BillingProfileId The billing profile this override is associated with. + // + // If empty the default profile is looked up dynamically. + BillingProfileId *string `json:"billingProfileId,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CustomerId The customer id this override is associated with. + CustomerId string `json:"customerId"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// BillingProfileCustomerOverrideCreate Payload for creating a new or updating an existing customer override. +type BillingProfileCustomerOverrideCreate struct { + // BillingProfileId The billing profile this override is associated with. + // + // If not provided, the default billing profile is chosen if available. + BillingProfileId *string `json:"billingProfileId,omitempty"` +} + +// BillingProfileCustomerOverrideExpand CustomerOverrideExpand specifies the parts of the profile to expand. +type BillingProfileCustomerOverrideExpand string + +// BillingProfileCustomerOverrideOrderBy Order by options for customers. +type BillingProfileCustomerOverrideOrderBy string + +// BillingProfileCustomerOverrideWithDetails Customer specific workflow overrides. +type BillingProfileCustomerOverrideWithDetails struct { + // BaseBillingProfileId The billing profile the customerProfile is associated with at the time of query. + // + // customerOverride contains the explicit mapping set in the customer override object. If that is + // empty, then the baseBillingProfileId is the default profile. + BaseBillingProfileId string `json:"baseBillingProfileId"` + + // Customer The customer this override belongs to. + Customer *Customer `json:"customer,omitempty"` + + // CustomerOverride The customer override values. + // + // If empty the merged values are calculated based on the default profile. + CustomerOverride *BillingProfileCustomerOverride `json:"customerOverride,omitempty"` + + // CustomerProfile Merged billing profile with the customer specific overrides. + CustomerProfile *BillingCustomerProfile `json:"customerProfile,omitempty"` +} + +// BillingProfileCustomerOverrideWithDetailsPaginatedResponse Paginated response +type BillingProfileCustomerOverrideWithDetailsPaginatedResponse struct { + // Items The items in the current page. + Items []BillingProfileCustomerOverrideWithDetails `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// BillingProfileCustomerWorkflowOverride Customer specific workflow overrides. +type BillingProfileCustomerWorkflowOverride struct { + // Collection The collection settings for this workflow + Collection *BillingWorkflowCollectionSettings `json:"collection,omitempty"` + + // Invoicing The invoicing settings for this workflow + Invoicing *BillingWorkflowInvoicingSettings `json:"invoicing,omitempty"` + + // InvoicingApp The invoicing app used for this workflow + InvoicingApp AppReadOrCreateOrUpdateOrDeleteOrQuery `json:"invoicingApp"` + + // Payment The payment settings for this workflow + Payment *BillingWorkflowPaymentSettings `json:"payment,omitempty"` + + // PaymentApp The payment app used for this workflow + PaymentApp AppReadOrCreateOrUpdateOrDeleteOrQuery `json:"paymentApp"` + + // Tax The tax settings for this workflow + Tax *BillingWorkflowTaxSettings `json:"tax,omitempty"` + + // TaxApp The tax app used for this workflow + TaxApp AppReadOrCreateOrUpdateOrDeleteOrQuery `json:"taxApp"` +} + +// BillingProfileExpand BillingProfileExpand details what profile fields to expand +type BillingProfileExpand string + +// BillingProfileOrderBy BillingProfileOrderBy specifies the ordering options for profiles +type BillingProfileOrderBy string + +// BillingProfilePaginatedResponse Paginated response +type BillingProfilePaginatedResponse struct { + // Items The items in the current page. + Items []BillingProfile `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// BillingProfileReplaceUpdateWithWorkflow BillingProfileReplaceUpdate represents the input for updating a billing profile +// +// The apps field cannot be updated directly, if an app change is desired a new +// profile should be created. +type BillingProfileReplaceUpdateWithWorkflow struct { + // Default Is this the default profile? + Default bool `json:"default"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // Workflow The billing workflow settings for this profile. + Workflow BillingWorkflow `json:"workflow"` +} + +// BillingSettlementMode The settlement mode of a plan. +// It determines how the billing system generates invoices and credits for the subscriptions using this plan. +// - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode. +// - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. +type BillingSettlementMode string + +// BillingTaxIdentificationCode TaxIdentificationCode is a normalized tax code shown on the original identity document. +type BillingTaxIdentificationCode = string + +// BillingWorkflow BillingWorkflow represents the settings for a billing workflow. +type BillingWorkflow struct { + // Collection The collection settings for this workflow + Collection *BillingWorkflowCollectionSettings `json:"collection,omitempty"` + + // Invoicing The invoicing settings for this workflow + Invoicing *BillingWorkflowInvoicingSettings `json:"invoicing,omitempty"` + + // Payment The payment settings for this workflow + Payment *BillingWorkflowPaymentSettings `json:"payment,omitempty"` + + // Tax The tax settings for this workflow + Tax *BillingWorkflowTaxSettings `json:"tax,omitempty"` +} + +// BillingWorkflowAppReferenceType App reference type specifies the type of reference inside an app reference +type BillingWorkflowAppReferenceType string + +// BillingWorkflowCollectionAlignment The alignment for collecting the pending line items into an invoice. +// +// Defaults to subscription, which means that we are to create a new invoice every time the +// a subscription period starts (for in advance items) or ends (for in arrears items). +type BillingWorkflowCollectionAlignment struct { + union json.RawMessage +} + +// BillingWorkflowCollectionAlignmentAnchored BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items +// into an invoice. +type BillingWorkflowCollectionAlignmentAnchored struct { + // RecurringPeriod The recurring period for the alignment. + RecurringPeriod RecurringPeriodV2 `json:"recurringPeriod"` + + // Type The type of alignment. + Type BillingWorkflowCollectionAlignmentAnchoredType `json:"type"` +} + +// BillingWorkflowCollectionAlignmentAnchoredType The type of alignment. +type BillingWorkflowCollectionAlignmentAnchoredType string + +// BillingWorkflowCollectionAlignmentSubscription BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items +// into an invoice. +type BillingWorkflowCollectionAlignmentSubscription struct { + // Type The type of alignment. + Type BillingWorkflowCollectionAlignmentSubscriptionType `json:"type"` +} + +// BillingWorkflowCollectionAlignmentSubscriptionType The type of alignment. +type BillingWorkflowCollectionAlignmentSubscriptionType string + +// BillingWorkflowCollectionSettings Workflow collection specifies how to collect the pending line items for an invoice +type BillingWorkflowCollectionSettings struct { + // Alignment The alignment for collecting the pending line items into an invoice. + Alignment *BillingWorkflowCollectionAlignment `json:"alignment,omitempty"` + + // Interval This grace period can be used to delay the collection of the pending line items specified in + // alignment. + // + // This is useful, in case of multiple subscriptions having slightly different billing periods. + Interval *string `json:"interval,omitempty"` +} + +// BillingWorkflowCreate Resource create operation model. +type BillingWorkflowCreate struct { + // Collection The collection settings for this workflow + Collection *BillingWorkflowCollectionSettings `json:"collection,omitempty"` + + // Invoicing The invoicing settings for this workflow + Invoicing *BillingWorkflowInvoicingSettings `json:"invoicing,omitempty"` + + // Payment The payment settings for this workflow + Payment *BillingWorkflowPaymentSettings `json:"payment,omitempty"` + + // Tax The tax settings for this workflow + Tax *BillingWorkflowTaxSettings `json:"tax,omitempty"` +} + +// BillingWorkflowInvoicingSettings BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow +type BillingWorkflowInvoicingSettings struct { + // AutoAdvance Whether to automatically issue the invoice after the draftPeriod has passed. + AutoAdvance *bool `json:"autoAdvance,omitempty"` + + // DefaultTaxConfig Default tax configuration to apply to the invoices. + // + // Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + // deprecated and can no longer be added or changed: the organization default tax code is + // used instead. Existing tax-code values may still be removed, and `behavior` remains + // fully supported. + DefaultTaxConfig *TaxConfig `json:"defaultTaxConfig,omitempty"` + + // DraftPeriod The period for the invoice to be kept in draft status for manual reviews. + DraftPeriod *string `json:"draftPeriod,omitempty"` + + // DueAfter The period after which the invoice is due. + // With some payment solutions it's only applicable for manual collection method. + DueAfter *string `json:"dueAfter,omitempty"` + + // ProgressiveBilling Should progressive billing be allowed for this workflow? + ProgressiveBilling *bool `json:"progressiveBilling,omitempty"` + + // SubscriptionEndProrationMode Controls how subscription-ending shortened service periods are billed. + SubscriptionEndProrationMode *BillingWorkflowInvoicingSubscriptionEndProrationMode `json:"subscriptionEndProrationMode,omitempty"` +} + +// BillingWorkflowInvoicingSubscriptionEndProrationMode Billing workflow subscription end proration mode. +type BillingWorkflowInvoicingSubscriptionEndProrationMode string + +// BillingWorkflowLineResolution BillingWorkflowLineResolution specifies how the line items should be resolved in the invoice +type BillingWorkflowLineResolution string + +// BillingWorkflowPaymentSettings BillingWorkflowPaymentSettings represents the payment settings for a billing workflow +type BillingWorkflowPaymentSettings struct { + // CollectionMethod The payment method for the invoice. + CollectionMethod *CollectionMethod `json:"collectionMethod,omitempty"` +} + +// BillingWorkflowTaxSettings BillingWorkflowTaxSettings represents the tax settings for a billing workflow +type BillingWorkflowTaxSettings struct { + // Enabled Enable automatic tax calculation when tax is supported by the app. + // For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + Enabled *bool `json:"enabled,omitempty"` + + // Enforced Enforce tax calculation when tax is supported by the app. + // When enabled, OpenMeter will not allow to create an invoice without tax calculation. + // Enforcement is different per apps, for example, Stripe app requires customer + // to have a tax location when starting a paid subscription. + Enforced *bool `json:"enforced,omitempty"` +} + +// CheckoutSessionCustomTextAfterSubmitParams Stripe CheckoutSession.custom_text +type CheckoutSessionCustomTextAfterSubmitParams struct { + // AfterSubmit Custom text that should be displayed after the payment confirmation button. + AfterSubmit *struct { + Message *string `json:"message,omitempty"` + } `json:"afterSubmit,omitempty"` + + // ShippingAddress Custom text that should be displayed alongside shipping address collection. + ShippingAddress *struct { + Message *string `json:"message,omitempty"` + } `json:"shippingAddress,omitempty"` + + // Submit Custom text that should be displayed alongside the payment confirmation button. + Submit *struct { + Message *string `json:"message,omitempty"` + } `json:"submit,omitempty"` + + // TermsOfServiceAcceptance Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *struct { + Message *string `json:"message,omitempty"` + } `json:"termsOfServiceAcceptance,omitempty"` +} + +// CheckoutSessionUIMode Stripe CheckoutSession.ui_mode +type CheckoutSessionUIMode string + +// ClientAppStartResponse Response from the client app (OpenMeter backend) to start the OAuth2 flow. +type ClientAppStartResponse struct { + // Url The URL to start the OAuth2 authorization code grant flow. + Url string `json:"url"` +} + +// CollectionMethod CollectionMethod specifies how the invoice should be collected (automatic vs manual) +type CollectionMethod string + +// ConflictProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type ConflictProblemResponse = UnexpectedProblemResponse + +// CountryCode [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. +// Custom two-letter country codes are also supported for convenience. +type CountryCode = string + +// CreateCheckoutSessionTaxIdCollection Create Stripe checkout session tax ID collection. +type CreateCheckoutSessionTaxIdCollection struct { + // Enabled Enable tax ID collection during checkout. Defaults to false. + Enabled bool `json:"enabled"` + + // Required Describes whether a tax ID is required during checkout. Defaults to never. + Required *CreateCheckoutSessionTaxIdCollectionRequired `json:"required,omitempty"` +} + +// CreateCheckoutSessionTaxIdCollectionRequired Create Stripe checkout session tax ID collection required. +type CreateCheckoutSessionTaxIdCollectionRequired string + +// CreateStripeCheckoutSessionBillingAddressCollection Specify whether Checkout should collect the customer’s billing address. +type CreateStripeCheckoutSessionBillingAddressCollection string + +// CreateStripeCheckoutSessionConsentCollection Configure fields for the Checkout Session to gather active consent from customers. +type CreateStripeCheckoutSessionConsentCollection struct { + // PaymentMethodReuseAgreement Determines the position and visibility of the payment method reuse agreement in the UI. + // When set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI. + PaymentMethodReuseAgreement *CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement `json:"paymentMethodReuseAgreement,omitempty"` + + // Promotions If set to auto, enables the collection of customer consent for promotional communications. + // The Checkout Session will determine whether to display an option to opt into promotional + // communication from the merchant depending on the customer’s locale. Only available to US merchants. + Promotions *CreateStripeCheckoutSessionConsentCollectionPromotions `json:"promotions,omitempty"` + + // TermsOfService If set to required, it requires customers to check a terms of service checkbox before being able to pay. + // There must be a valid terms of service URL set in your Stripe Dashboard settings. + // https://dashboard.stripe.com/settings/public + TermsOfService *CreateStripeCheckoutSessionConsentCollectionTermsOfService `json:"termsOfService,omitempty"` +} + +// CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement Create Stripe checkout session payment method reuse agreement. +type CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement struct { + // Position Create Stripe checkout session consent collection agreement position. + Position *CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition `json:"position,omitempty"` +} + +// CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition Create Stripe checkout session consent collection agreement position. +type CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition string + +// CreateStripeCheckoutSessionConsentCollectionPromotions Create Stripe checkout session consent collection promotions. +type CreateStripeCheckoutSessionConsentCollectionPromotions string + +// CreateStripeCheckoutSessionConsentCollectionTermsOfService Create Stripe checkout session consent collection terms of service. +type CreateStripeCheckoutSessionConsentCollectionTermsOfService string + +// CreateStripeCheckoutSessionCustomerUpdate Controls what fields on Customer can be updated by the Checkout Session. +type CreateStripeCheckoutSessionCustomerUpdate struct { + // Address Describes whether Checkout saves the billing address onto customer.address. + // To always collect a full billing address, use billing_address_collection. + // Defaults to never. + Address *CreateStripeCheckoutSessionCustomerUpdateBehavior `json:"address,omitempty"` + + // Name Describes whether Checkout saves the name onto customer.name. + // Defaults to never. + Name *CreateStripeCheckoutSessionCustomerUpdateBehavior `json:"name,omitempty"` + + // Shipping Describes whether Checkout saves shipping information onto customer.shipping. + // To collect shipping information, use shipping_address_collection. + // Defaults to never. + Shipping *CreateStripeCheckoutSessionCustomerUpdateBehavior `json:"shipping,omitempty"` +} + +// CreateStripeCheckoutSessionCustomerUpdateBehavior Create Stripe checkout session customer update behavior. +type CreateStripeCheckoutSessionCustomerUpdateBehavior string + +// CreateStripeCheckoutSessionRedirectOnCompletion Create Stripe checkout session redirect on completion. +type CreateStripeCheckoutSessionRedirectOnCompletion string + +// CreateStripeCheckoutSessionRequest Create Stripe checkout session request. +type CreateStripeCheckoutSessionRequest struct { + // AppId If not provided, the default Stripe app is used if any. + AppId *string `json:"appId,omitempty"` + + // Customer Provide a customer ID or key to use an existing OpenMeter customer. + // or provide a customer object to create a new customer. + Customer CreateStripeCheckoutSessionRequest_Customer `json:"customer"` + + // Options Options passed to Stripe when creating the checkout session. + Options CreateStripeCheckoutSessionRequestOptions `json:"options"` + + // StripeCustomerId Stripe customer ID. + // If not provided OpenMeter creates a new Stripe customer or + // uses the OpenMeter customer's default Stripe customer ID. + StripeCustomerId *string `json:"stripeCustomerId,omitempty"` +} + +// CreateStripeCheckoutSessionRequest_Customer Provide a customer ID or key to use an existing OpenMeter customer. +// or provide a customer object to create a new customer. +type CreateStripeCheckoutSessionRequest_Customer struct { + union json.RawMessage +} + +// CreateStripeCheckoutSessionRequestOptions Create Stripe checkout session options +// See https://docs.stripe.com/api/checkout/sessions/create +type CreateStripeCheckoutSessionRequestOptions struct { + // BillingAddressCollection Specify whether Checkout should collect the customer’s billing address. Defaults to auto. + BillingAddressCollection *CreateStripeCheckoutSessionBillingAddressCollection `json:"billingAddressCollection,omitempty"` + + // CancelURL If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + // This parameter is not allowed if ui_mode is embedded. + CancelURL *string `json:"cancelURL,omitempty"` + + // ClientReferenceID A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + ClientReferenceID *string `json:"clientReferenceID,omitempty"` + + // ConsentCollection Configure fields for the Checkout Session to gather active consent from customers. + ConsentCollection *CreateStripeCheckoutSessionConsentCollection `json:"consentCollection,omitempty"` + + // Currency Three-letter ISO currency code, in lowercase. + Currency *CurrencyCode `json:"currency,omitempty"` + + // CustomText Display additional text for your customers using custom text. + CustomText *CheckoutSessionCustomTextAfterSubmitParams `json:"customText,omitempty"` + + // CustomerUpdate Controls what fields on Customer can be updated by the Checkout Session. + CustomerUpdate *CreateStripeCheckoutSessionCustomerUpdate `json:"customerUpdate,omitempty"` + + // ExpiresAt The Epoch time in seconds at which the Checkout Session will expire. + // It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + ExpiresAt *int64 `json:"expiresAt,omitempty"` + Locale *string `json:"locale,omitempty"` + + // Metadata Set of key-value pairs that you can attach to an object. + // This can be useful for storing additional information about the object in a structured format. + // Individual keys can be unset by posting an empty value to them. + // All keys can be unset by posting an empty value to metadata. + Metadata *map[string]string `json:"metadata,omitempty"` + + // PaymentMethodTypes A list of the types of payment methods (e.g., card) this Checkout Session can accept. + PaymentMethodTypes *[]string `json:"paymentMethodTypes,omitempty"` + + // RedirectOnCompletion This parameter applies to ui_mode: embedded. Defaults to always. + // Learn more about the redirect behavior of embedded sessions at + // https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + RedirectOnCompletion *CreateStripeCheckoutSessionRedirectOnCompletion `json:"redirectOnCompletion,omitempty"` + + // ReturnURL The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site. + // This parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session. + ReturnURL *string `json:"returnURL,omitempty"` + + // SuccessURL The URL to which Stripe should send customers when payment or setup is complete. + // This parameter is not allowed if ui_mode is embedded. + // If you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page: + // https://docs.stripe.com/payments/checkout/custom-success-page + SuccessURL *string `json:"successURL,omitempty"` + + // TaxIdCollection Controls tax ID collection during checkout. + TaxIdCollection *CreateCheckoutSessionTaxIdCollection `json:"taxIdCollection,omitempty"` + + // UiMode The UI mode of the Session. Defaults to hosted. + UiMode *CheckoutSessionUIMode `json:"uiMode,omitempty"` +} + +// CreateStripeCheckoutSessionResult Create Stripe Checkout Session response. +type CreateStripeCheckoutSessionResult struct { + // CancelURL Cancel URL. + CancelURL *string `json:"cancelURL,omitempty"` + + // ClientReferenceId A unique string to reference the Checkout Session. + // This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + ClientReferenceId *string `json:"clientReferenceId,omitempty"` + + // ClientSecret The client secret of the checkout session. + // This can be used to initialize Stripe.js for your client-side implementation. + ClientSecret *string `json:"clientSecret,omitempty"` + + // CreatedAt Timestamp at which the checkout session was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency Three-letter ISO currency code, in lowercase. + Currency *CurrencyCode `json:"currency,omitempty"` + + // CustomerEmail Customer's email address provided to Stripe. + CustomerEmail *string `json:"customerEmail,omitempty"` + + // CustomerId The OpenMeter customer ID. + CustomerId string `json:"customerId"` + + // ExpiresAt Timestamp at which the checkout session will expire. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Metadata Set of key-value pairs attached to the checkout session. + Metadata *map[string]string `json:"metadata,omitempty"` + + // Mode Mode + // Always `setup` for now. + Mode StripeCheckoutSessionMode `json:"mode"` + + // ReturnURL Return URL. + ReturnURL *string `json:"returnURL,omitempty"` + + // SessionId The checkout session ID. + SessionId string `json:"sessionId"` + + // SetupIntentId The checkout session setup intent ID. + SetupIntentId string `json:"setupIntentId"` + + // Status The status of the checkout session. + Status *string `json:"status,omitempty"` + + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // SuccessURL Success URL. + SuccessURL *string `json:"successURL,omitempty"` + + // Url URL to show the checkout session. + Url *string `json:"url,omitempty"` +} + +// CreateStripeCustomerPortalSessionParams Stripe customer portal request params. +type CreateStripeCustomerPortalSessionParams struct { + // ConfigurationId The ID of an existing configuration to use for this session, + // describing its functionality and features. + // If not specified, the session uses the default configuration. + // + // See https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration + ConfigurationId *string `json:"configurationId,omitempty"` + + // Locale The IETF language tag of the locale customer portal is displayed in. + // If blank or auto, the customer’s preferred_locales or browser’s locale is used. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale + Locale *string `json:"locale,omitempty"` + + // ReturnUrl The URL to redirect the customer to after they have completed + // their requested actions. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url + ReturnUrl *string `json:"returnUrl,omitempty"` +} + +// CreditNoteOriginalInvoiceRef Omitted fields: +// period: Tax period in which the referred document had an effect required by some tax regimes and formats. +// stamps: Seals of approval from other organisations that may need to be listed. +// ext: Extensions for additional codes that may be required. +type CreditNoteOriginalInvoiceRef = InvoiceGenericDocumentRef + +// Currency Currency describes a currency supported by OpenMeter. +type Currency struct { + // Code The currency ISO code. + Code CurrencyCode `json:"code"` + + // Name The currency name. + Name string `json:"name"` + + // Subunits Subunit of the currency. + Subunits uint32 `json:"subunits"` + + // Symbol The currency symbol. + Symbol string `json:"symbol"` +} + +// CurrencyCode Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. +// Custom three-letter currency codes are also supported for convenience. +type CurrencyCode = string + +// CustomInvoicingApp Custom Invoicing app can be used for interface with any invoicing or payment system. +// +// This app provides ways to manipulate invoices and payments, however the integration +// must rely on Notifications API to get notified about invoice changes. +type CustomInvoicingApp struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EnableDraftSyncHook Enable draft.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableDraftSyncHook bool `json:"enableDraftSyncHook"` + + // EnableIssuingSyncHook Enable issuing.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableIssuingSyncHook bool `json:"enableIssuingSyncHook"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // Type The app's type is CustomInvoicing. + Type CustomInvoicingAppType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// CustomInvoicingAppType The app's type is CustomInvoicing. +type CustomInvoicingAppType string + +// CustomInvoicingAppReplaceUpdate Resource update operation model. +type CustomInvoicingAppReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EnableDraftSyncHook Enable draft.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableDraftSyncHook bool `json:"enableDraftSyncHook"` + + // EnableIssuingSyncHook Enable issuing.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableIssuingSyncHook bool `json:"enableIssuingSyncHook"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Type The app's type is CustomInvoicing. + Type CustomInvoicingAppReplaceUpdateType `json:"type"` +} + +// CustomInvoicingAppReplaceUpdateType The app's type is CustomInvoicing. +type CustomInvoicingAppReplaceUpdateType string + +// CustomInvoicingCustomerAppData Custom Invoicing Customer App Data. +type CustomInvoicingCustomerAppData struct { + // App The installed custom invoicing app this data belongs to. + App *CustomInvoicingApp `json:"app,omitempty"` + + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // Metadata Metadata to be used by the custom invoicing provider. + Metadata *Metadata `json:"metadata,omitempty"` + + // Type The app name. + Type CustomInvoicingCustomerAppDataType `json:"type"` +} + +// CustomInvoicingCustomerAppDataType The app name. +type CustomInvoicingCustomerAppDataType string + +// CustomInvoicingDraftSynchronizedRequest Information to finalize the draft details of an invoice. +type CustomInvoicingDraftSynchronizedRequest struct { + // Invoicing The result of the synchronization. + Invoicing *CustomInvoicingSyncResult `json:"invoicing,omitempty"` +} + +// CustomInvoicingFinalizedInvoicingRequest Information to finalize the invoicing details of an invoice. +type CustomInvoicingFinalizedInvoicingRequest struct { + // InvoiceNumber If set the invoice's number will be set to this value. + InvoiceNumber *InvoiceNumber `json:"invoiceNumber,omitempty"` + + // SentToCustomerAt If set the invoice's sent to customer at will be set to this value. + SentToCustomerAt *time.Time `json:"sentToCustomerAt,omitempty"` +} + +// CustomInvoicingFinalizedPaymentRequest Information to finalize the payment details of an invoice. +type CustomInvoicingFinalizedPaymentRequest struct { + // ExternalId If set the invoice's payment external ID will be set to this value. + ExternalId *string `json:"externalId,omitempty"` +} + +// CustomInvoicingFinalizedRequest Information to finalize the invoice. +// +// If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix). +type CustomInvoicingFinalizedRequest struct { + // Invoicing The result of the synchronization. + Invoicing *CustomInvoicingFinalizedInvoicingRequest `json:"invoicing,omitempty"` + + // Payment The result of the payment synchronization. + Payment *CustomInvoicingFinalizedPaymentRequest `json:"payment,omitempty"` +} + +// CustomInvoicingLineDiscountExternalIdMapping Mapping between line discounts and external IDs. +type CustomInvoicingLineDiscountExternalIdMapping struct { + // ExternalId The external ID (e.g. custom invoicing system's ID). + ExternalId string `json:"externalId"` + + // LineDiscountId The line discount ID. + LineDiscountId string `json:"lineDiscountId"` +} + +// CustomInvoicingLineExternalIdMapping Mapping between lines and external IDs. +type CustomInvoicingLineExternalIdMapping struct { + // ExternalId The external ID (e.g. custom invoicing system's ID). + ExternalId string `json:"externalId"` + + // LineId The line ID. + LineId string `json:"lineId"` +} + +// CustomInvoicingPaymentTrigger Payment trigger to execute on a finalized invoice. +type CustomInvoicingPaymentTrigger string + +// CustomInvoicingSyncResult Information to synchronize the invoice. +// +// Can be used to store external app's IDs on the invoice or lines. +type CustomInvoicingSyncResult struct { + // ExternalId If set the invoice's invoicing external ID will be set to this value. + ExternalId *string `json:"externalId,omitempty"` + + // InvoiceNumber If set the invoice's number will be set to this value. + InvoiceNumber *InvoiceNumber `json:"invoiceNumber,omitempty"` + + // LineDiscountExternalIds If set the invoice's line discount external IDs will be set to this value. + // + // This can be used to reference the external system's entities in the + // invoice. + LineDiscountExternalIds *[]CustomInvoicingLineDiscountExternalIdMapping `json:"lineDiscountExternalIds,omitempty"` + + // LineExternalIds If set the invoice's line external IDs will be set to this value. + // + // This can be used to reference the external system's entities in the + // invoice. + LineExternalIds *[]CustomInvoicingLineExternalIdMapping `json:"lineExternalIds,omitempty"` +} + +// CustomInvoicingTaxConfig Custom invoicing tax config. +type CustomInvoicingTaxConfig struct { + // Code Tax code. + // + // The tax code should be interpreted by the custom invoicing provider. + Code string `json:"code"` +} + +// CustomInvoicingUpdatePaymentStatusRequest Update payment status request. +// +// Can be used to manipulate invoice's payment status (when custominvoicing app is being used). +type CustomInvoicingUpdatePaymentStatusRequest struct { + // Trigger The trigger to be executed on the invoice. + Trigger CustomInvoicingPaymentTrigger `json:"trigger"` +} + +// CustomPlanInput The template for omitting properties. +type CustomPlanInput struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // Currency The currency code of the plan. + Currency CurrencyCode `json:"currency"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` +} + +// CustomSubscriptionChange Change a custom subscription. +type CustomSubscriptionChange struct { + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // CustomPlan The custom plan description which defines the Subscription. + CustomPlan CustomPlanInput `json:"customPlan"` + + // Timing Timing configuration for the change, when the change should take effect. + // For changing a subscription, the accepted values depend on the subscription configuration. + Timing SubscriptionTiming `json:"timing"` +} + +// CustomSubscriptionCreate Create a custom subscription. +type CustomSubscriptionCreate struct { + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // CustomPlan The custom plan description which defines the Subscription. + CustomPlan CustomPlanInput `json:"customPlan"` + + // CustomerId The ID of the customer. Provide either the key or ID. Has presedence over the key. + CustomerId *string `json:"customerId,omitempty"` + + // CustomerKey The key of the customer. Provide either the key or ID. + CustomerKey *string `json:"customerKey,omitempty"` + + // Timing Timing configuration for the change, when the change should take effect. + // The default is immediate. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// Customer A customer object. +type Customer struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // BillingAddress The billing address of the customer. + // Used for tax and invoicing. + BillingAddress *Address `json:"billingAddress,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency Currency of the customer. + // Used for billing, tax and invoicing. + Currency *CurrencyCode `json:"currency,omitempty"` + + // CurrentSubscriptionId The ID of the Subscription if the customer has one. + CurrentSubscriptionId *string `json:"currentSubscriptionId,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Key An optional unique key of the customer. + // Either key or usageAttribution.subjectKeys must be provided. + // Useful to reference the customer in external systems. + // For example, your database ID. + Key *string `json:"key,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PrimaryEmail The primary email address of the customer. + PrimaryEmail *string `json:"primaryEmail,omitempty"` + + // Subscriptions The subscriptions of the customer. + // Only with the `subscriptions` expand option. + Subscriptions *[]Subscription `json:"subscriptions,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsageAttribution Mapping to attribute metered usage to the customer + // Either key or usageAttribution.subjectKeys must be provided. + UsageAttribution *CustomerUsageAttribution `json:"usageAttribution,omitempty"` +} + +// CustomerAccess CustomerAccess describes what features the customer has access to. +type CustomerAccess struct { + // Entitlements Map of entitlements the customer has access to. + // The key is the feature key, the value is the entitlement value + the entitlement ID. + Entitlements map[string]EntitlementValue `json:"entitlements"` +} + +// CustomerAppData CustomerAppData +// Stores the app specific data for the customer. +// One of: stripe, sandbox, custom_invoicing +type CustomerAppData struct { + union json.RawMessage +} + +// CustomerAppDataCreateOrUpdateItem CustomerAppData +// Stores the app specific data for the customer. +// One of: stripe, sandbox, custom_invoicing +type CustomerAppDataCreateOrUpdateItem struct { + union json.RawMessage +} + +// CustomerAppDataPaginatedResponse Paginated response +type CustomerAppDataPaginatedResponse struct { + // Items The items in the current page. + Items []CustomerAppData `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// CustomerCreate Resource create operation model. +type CustomerCreate struct { + // BillingAddress The billing address of the customer. + // Used for tax and invoicing. + BillingAddress *Address `json:"billingAddress,omitempty"` + + // Currency Currency of the customer. + // Used for billing, tax and invoicing. + Currency *CurrencyCode `json:"currency,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Key An optional unique key of the customer. + // Either key or usageAttribution.subjectKeys must be provided. + // Useful to reference the customer in external systems. + // For example, your database ID. + Key *string `json:"key,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PrimaryEmail The primary email address of the customer. + PrimaryEmail *string `json:"primaryEmail,omitempty"` + + // UsageAttribution Mapping to attribute metered usage to the customer + // Either key or usageAttribution.subjectKeys must be provided. + UsageAttribution *CustomerUsageAttribution `json:"usageAttribution,omitempty"` +} + +// CustomerExpand CustomerExpand specifies the parts of the customer to expand in the list output. +type CustomerExpand string + +// CustomerId Create Stripe checkout session with customer ID. +type CustomerId struct { + // Id ULID (Universally Unique Lexicographically Sortable Identifier). + Id string `json:"id"` +} + +// CustomerKey Create Stripe checkout session with customer key. +type CustomerKey struct { + Key string `json:"key"` +} + +// CustomerOrderBy Order by options for customers. +type CustomerOrderBy string + +// CustomerPaginatedResponse Paginated response +type CustomerPaginatedResponse struct { + // Items The items in the current page. + Items []Customer `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// CustomerReplaceUpdate Resource update operation model. +type CustomerReplaceUpdate struct { + // BillingAddress The billing address of the customer. + // Used for tax and invoicing. + BillingAddress *Address `json:"billingAddress,omitempty"` + + // Currency Currency of the customer. + // Used for billing, tax and invoicing. + Currency *CurrencyCode `json:"currency,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Key An optional unique key of the customer. + // Either key or usageAttribution.subjectKeys must be provided. + // Useful to reference the customer in external systems. + // For example, your database ID. + Key *string `json:"key,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PrimaryEmail The primary email address of the customer. + PrimaryEmail *string `json:"primaryEmail,omitempty"` + + // UsageAttribution Mapping to attribute metered usage to the customer + // Either key or usageAttribution.subjectKeys must be provided. + UsageAttribution *CustomerUsageAttribution `json:"usageAttribution,omitempty"` +} + +// CustomerSubscriptionOrderBy Order by options for customer subscriptions. +type CustomerSubscriptionOrderBy string + +// CustomerUsageAttribution Mapping to attribute metered usage to the customer. +// One customer can have zero or more subjects, +// but one subject can only belong to one customer. +type CustomerUsageAttribution struct { + // SubjectKeys The subjects that are attributed to the customer. + // Can be empty when no subjects are associated with the customer. + SubjectKeys []string `json:"subjectKeys"` +} + +// DiscountPercentage Percentage discount. +type DiscountPercentage struct { + // Percentage The percentage of the discount. + Percentage Percentage `json:"percentage"` +} + +// DiscountReasonMaximumSpend The reason for the discount is a maximum spend. +type DiscountReasonMaximumSpend struct { + Type DiscountReasonMaximumSpendType `json:"type"` +} + +// DiscountReasonMaximumSpendType defines model for DiscountReasonMaximumSpend.Type. +type DiscountReasonMaximumSpendType string + +// DiscountReasonRatecardPercentage The reason for the discount is a ratecard percentage. +type DiscountReasonRatecardPercentage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Percentage The percentage of the discount. + Percentage Percentage `json:"percentage"` + Type DiscountReasonRatecardPercentageType `json:"type"` +} + +// DiscountReasonRatecardPercentageType defines model for DiscountReasonRatecardPercentage.Type. +type DiscountReasonRatecardPercentageType string + +// DiscountReasonRatecardUsage The reason for the discount is a ratecard usage. +type DiscountReasonRatecardUsage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Quantity The quantity of the usage discount. + // + // Must be positive. + Quantity Numeric `json:"quantity"` + Type DiscountReasonRatecardUsageType `json:"type"` +} + +// DiscountReasonRatecardUsageType defines model for DiscountReasonRatecardUsage.Type. +type DiscountReasonRatecardUsageType string + +// DiscountReasonType The type of the discount reason. +type DiscountReasonType string + +// DiscountUsage Usage discount. +// +// Usage discount means that the first N items are free. From billing perspective +// this means that any usage on a specific feature is considered 0 until this discount +// is exhausted. +type DiscountUsage struct { + // Quantity The quantity of the usage discount. + // + // Must be positive. + Quantity Numeric `json:"quantity"` +} + +// Discounts Discount by type on a price +type Discounts struct { + // Percentage The percentage discount. + Percentage *DiscountPercentage `json:"percentage,omitempty"` + + // Usage The usage discount. + Usage *DiscountUsage `json:"usage,omitempty"` +} + +// DynamicPrice Dynamic price. +// +// The underlying meter's value is considered the base price in the +// customer's currency. +// +// The rate specifies the markup over the price. +type DynamicPrice struct { + // Multiplier The multiplier to apply to the base price to get the dynamic price. + // + // Examples: + // - 0.0: the price is zero + // - 0.5: the price is 50% of the base price + // - 1.0: the price is the same as the base price + // - 1.5: the price is 150% of the base price + Multiplier *Numeric `json:"multiplier,omitempty"` + + // Type The type of the price. + Type DynamicPriceType `json:"type"` +} + +// DynamicPriceType The type of the price. +type DynamicPriceType string + +// DynamicPriceWithCommitments Dynamic price with spend commitments. +type DynamicPriceWithCommitments struct { + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // Multiplier The multiplier to apply to the base price to get the dynamic price. + // + // Examples: + // - 0.0: the price is zero + // - 0.5: the price is 50% of the base price + // - 1.0: the price is the same as the base price + // - 1.5: the price is 150% of the base price + Multiplier *Numeric `json:"multiplier,omitempty"` + + // Type The type of the price. + Type DynamicPriceWithCommitmentsType `json:"type"` +} + +// DynamicPriceWithCommitmentsType The type of the price. +type DynamicPriceWithCommitmentsType string + +// EditOp Enum listing the different operation types. +type EditOp string + +// EditSubscriptionAddItem Add a new item to a phase. +type EditSubscriptionAddItem struct { + Op EditSubscriptionAddItemOp `json:"op"` + PhaseKey string `json:"phaseKey"` + + // RateCard A rate card defines the pricing and entitlement of a feature or service. + RateCard RateCard `json:"rateCard"` +} + +// EditSubscriptionAddItemOp defines model for EditSubscriptionAddItem.Op. +type EditSubscriptionAddItemOp string + +// EditSubscriptionAddPhase Add a new phase +type EditSubscriptionAddPhase struct { + Op EditSubscriptionAddPhaseOp `json:"op"` + + // Phase Subscription phase create input. + Phase SubscriptionPhaseCreate `json:"phase"` +} + +// EditSubscriptionAddPhaseOp defines model for EditSubscriptionAddPhase.Op. +type EditSubscriptionAddPhaseOp string + +// EditSubscriptionRemoveItem Remove an item from a phase. +type EditSubscriptionRemoveItem struct { + ItemKey string `json:"itemKey"` + Op EditSubscriptionRemoveItemOp `json:"op"` + PhaseKey string `json:"phaseKey"` +} + +// EditSubscriptionRemoveItemOp defines model for EditSubscriptionRemoveItem.Op. +type EditSubscriptionRemoveItemOp string + +// EditSubscriptionRemovePhase Remove a phase +type EditSubscriptionRemovePhase struct { + Op EditSubscriptionRemovePhaseOp `json:"op"` + PhaseKey string `json:"phaseKey"` + + // Shift The direction of the phase shift when a phase is removed. + Shift RemovePhaseShifting `json:"shift"` +} + +// EditSubscriptionRemovePhaseOp defines model for EditSubscriptionRemovePhase.Op. +type EditSubscriptionRemovePhaseOp string + +// EditSubscriptionStretchPhase Stretch a phase +type EditSubscriptionStretchPhase struct { + ExtendBy string `json:"extendBy"` + Op EditSubscriptionStretchPhaseOp `json:"op"` + PhaseKey string `json:"phaseKey"` +} + +// EditSubscriptionStretchPhaseOp defines model for EditSubscriptionStretchPhase.Op. +type EditSubscriptionStretchPhaseOp string + +// EditSubscriptionUnscheduleEdit Unschedules any edits from the current phase. +type EditSubscriptionUnscheduleEdit struct { + Op EditSubscriptionUnscheduleEditOp `json:"op"` +} + +// EditSubscriptionUnscheduleEditOp defines model for EditSubscriptionUnscheduleEdit.Op. +type EditSubscriptionUnscheduleEditOp string + +// Entitlement Entitlement templates are used to define the entitlements of a plan. +// Features are omitted from the entitlement template, as they are defined in the rate card. +type Entitlement struct { + union json.RawMessage +} + +// EntitlementBaseTemplate Shared fields of the entitlement templates. +type EntitlementBaseTemplate struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + + // Type The type of the entitlement. + Type EntitlementType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementBoolean Entitlement template of a boolean entitlement. +type EntitlementBoolean struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + Type EntitlementBooleanType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementBooleanType defines model for EntitlementBoolean.Type. +type EntitlementBooleanType string + +// EntitlementBooleanCreateInputs Create inputs for boolean entitlement +type EntitlementBooleanCreateInputs struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementBooleanCreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod *RecurringPeriodCreateInput `json:"usagePeriod,omitempty"` +} + +// EntitlementBooleanCreateInputsType defines model for EntitlementBooleanCreateInputs.Type. +type EntitlementBooleanCreateInputsType string + +// EntitlementBooleanV2 Entitlement template of a boolean entitlement. +type EntitlementBooleanV2 struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementBooleanV2Type `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementBooleanV2Type defines model for EntitlementBooleanV2.Type. +type EntitlementBooleanV2Type string + +// EntitlementCreateInputs Create inputs for entitlement +type EntitlementCreateInputs struct { + union json.RawMessage +} + +// EntitlementCreateSharedFields Shared fields for entitlement creation +type EntitlementCreateSharedFields struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod *RecurringPeriodCreateInput `json:"usagePeriod,omitempty"` +} + +// EntitlementCustomerFields Customer fields for entitlements +type EntitlementCustomerFields struct { + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` +} + +// EntitlementGrant The grant. +type EntitlementGrant struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // Annotations Grant annotations + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // EntitlementId The unique entitlement ULID that the grant is associated with. + EntitlementId string `json:"entitlementId"` + + // Expiration The grant expiration definition + Expiration ExpirationPeriod `json:"expiration"` + + // ExpiresAt The time the grant expires. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // NextRecurrence The next time the grant will recurr. + NextRecurrence *time.Time `json:"nextRecurrence,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The recurrence period of the grant. + Recurrence *RecurringPeriod `json:"recurrence,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // VoidedAt The time the grant was voided. + VoidedAt *time.Time `json:"voidedAt,omitempty"` +} + +// EntitlementGrantCreateInput The grant creation input. +type EntitlementGrantCreateInput struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // Expiration The grant expiration definition + Expiration ExpirationPeriod `json:"expiration"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The subject of the grant. + Recurrence *RecurringPeriodCreateInput `json:"recurrence,omitempty"` +} + +// EntitlementGrantCreateInputV2 The grant creation input. +type EntitlementGrantCreateInputV2 struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // Annotations Grant annotations + Annotations *Annotations `json:"annotations,omitempty"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // Expiration The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + Expiration *ExpirationPeriod `json:"expiration,omitempty"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The subject of the grant. + Recurrence *RecurringPeriodCreateInput `json:"recurrence,omitempty"` +} + +// EntitlementGrantV2 The grant. +type EntitlementGrantV2 struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // Annotations Grant annotations + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // EntitlementId The unique entitlement ULID that the grant is associated with. + EntitlementId string `json:"entitlementId"` + + // Expiration The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + Expiration *ExpirationPeriod `json:"expiration,omitempty"` + + // ExpiresAt The time the grant expires. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // NextRecurrence The next time the grant will recurr. + NextRecurrence *time.Time `json:"nextRecurrence,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The recurrence period of the grant. + Recurrence *RecurringPeriod `json:"recurrence,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // VoidedAt The time the grant was voided. + VoidedAt *time.Time `json:"voidedAt,omitempty"` +} + +// EntitlementMetered Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. +// Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). +type EntitlementMetered struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod Period `json:"currentUsagePeriod"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // IsUnlimited Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IsUnlimited *bool `json:"isUnlimited,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // LastReset The time the last reset happened. + LastReset time.Time `json:"lastReset"` + + // MeasureUsageFrom The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom time.Time `json:"measureUsageFrom"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + Type EntitlementMeteredType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod THe usage period of the entitlement. + UsagePeriod RecurringPeriod `json:"usagePeriod"` +} + +// EntitlementMeteredType defines model for EntitlementMetered.Type. +type EntitlementMeteredType string + +// EntitlementMeteredCalculatedFields Calculated fields for metered entitlements. +type EntitlementMeteredCalculatedFields struct { + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod Period `json:"currentUsagePeriod"` + + // LastReset The time the last reset happened. + LastReset time.Time `json:"lastReset"` + + // MeasureUsageFrom The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom time.Time `json:"measureUsageFrom"` + + // UsagePeriod THe usage period of the entitlement. + UsagePeriod RecurringPeriod `json:"usagePeriod"` +} + +// EntitlementMeteredCreateInputs Create inpurs for metered entitlement +type EntitlementMeteredCreateInputs struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // IsUnlimited Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IsUnlimited *bool `json:"isUnlimited,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // MeasureUsageFrom Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom *MeasureUsageFrom `json:"measureUsageFrom,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type EntitlementMeteredCreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod RecurringPeriodCreateInput `json:"usagePeriod"` +} + +// EntitlementMeteredCreateInputsType defines model for EntitlementMeteredCreateInputs.Type. +type EntitlementMeteredCreateInputsType string + +// EntitlementMeteredV2 Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. +// Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). +type EntitlementMeteredV2 struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod Period `json:"currentUsagePeriod"` + + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // Issue Issue after reset + Issue *IssueAfterReset `json:"issue,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // LastReset The time the last reset happened. + LastReset time.Time `json:"lastReset"` + + // MeasureUsageFrom The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom time.Time `json:"measureUsageFrom"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type EntitlementMeteredV2Type `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod THe usage period of the entitlement. + UsagePeriod RecurringPeriod `json:"usagePeriod"` +} + +// EntitlementMeteredV2Type defines model for EntitlementMeteredV2.Type. +type EntitlementMeteredV2Type string + +// EntitlementMeteredV2CreateInputs Create inputs for metered entitlement +type EntitlementMeteredV2CreateInputs struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Grants Grants + Grants *[]EntitlementGrantCreateInputV2 `json:"grants,omitempty"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // Issue Issue after reset + Issue *IssueAfterReset `json:"issue,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // MeasureUsageFrom Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom *MeasureUsageFrom `json:"measureUsageFrom,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type EntitlementMeteredV2CreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod RecurringPeriodCreateInput `json:"usagePeriod"` +} + +// EntitlementMeteredV2CreateInputsType defines model for EntitlementMeteredV2CreateInputs.Type. +type EntitlementMeteredV2CreateInputsType string + +// EntitlementOrderBy Order by options for entitlements. +type EntitlementOrderBy string + +// EntitlementPaginatedResponse Paginated response +type EntitlementPaginatedResponse struct { + // Items The items in the current page. + Items []Entitlement `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// EntitlementStatic A static entitlement. +type EntitlementStatic struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + Type EntitlementStaticType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementStaticType defines model for EntitlementStatic.Type. +type EntitlementStaticType string + +// EntitlementStaticCreateInputs Create inputs for static entitlement +type EntitlementStaticCreateInputs struct { + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementStaticCreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod *RecurringPeriodCreateInput `json:"usagePeriod,omitempty"` +} + +// EntitlementStaticCreateInputsType defines model for EntitlementStaticCreateInputs.Type. +type EntitlementStaticCreateInputsType string + +// EntitlementStaticV2 A static entitlement. +type EntitlementStaticV2 struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementStaticV2Type `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementStaticV2Type defines model for EntitlementStaticV2.Type. +type EntitlementStaticV2Type string + +// EntitlementType Type of the entitlement. +type EntitlementType = string + +// EntitlementV2 Entitlement templates are used to define the entitlements of a plan. +// Features are omitted from the entitlement template, as they are defined in the rate card. +type EntitlementV2 struct { + union json.RawMessage +} + +// EntitlementV2CreateInputs Create inputs for entitlement +type EntitlementV2CreateInputs struct { + union json.RawMessage +} + +// EntitlementV2PaginatedResponse Paginated response +type EntitlementV2PaginatedResponse struct { + // Items The items in the current page. + Items []EntitlementV2 `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// EntitlementValue Entitlements are the core of OpenMeter access management. They define access to features for subjects. Entitlements can be metered, boolean, or static. +type EntitlementValue struct { + // Balance Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + Balance *float64 `json:"balance,omitempty"` + + // Config Only available for static entitlements. The JSON parsable config of the entitlement. + Config *string `json:"config,omitempty"` + + // HasAccess Whether the subject has access to the feature. Shared accross all entitlement types. + HasAccess bool `json:"hasAccess"` + + // Overage Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + Overage *float64 `json:"overage,omitempty"` + + // TotalAvailableGrantAmount Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + TotalAvailableGrantAmount *float64 `json:"totalAvailableGrantAmount,omitempty"` + + // Usage Only available for metered entitlements. Returns the total feature usage in the current period. + Usage *float64 `json:"usage,omitempty"` +} + +// EntitlementValueV2 EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 APIs. +type EntitlementValueV2 struct { + // Balance Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + Balance *float64 `json:"balance,omitempty"` + + // Config Only available for static entitlements. The JSON parsable config of the entitlement. + Config *string `json:"config,omitempty"` + + // GrantBalances Only available for metered entitlements. The closing balance of each active grant at query time. + // The key is the grant ID and the value is the remaining balance. + GrantBalances *map[string]float64 `json:"grantBalances,omitempty"` + + // HasAccess Whether the subject has access to the feature. Shared accross all entitlement types. + HasAccess bool `json:"hasAccess"` + + // Overage Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + Overage *float64 `json:"overage,omitempty"` + + // TotalAvailableGrantAmount Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + TotalAvailableGrantAmount *float64 `json:"totalAvailableGrantAmount,omitempty"` + + // Usage Only available for metered entitlements. Returns the total feature usage in the current period. + Usage *float64 `json:"usage,omitempty"` +} + +// ErrorExtension Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode] +type ErrorExtension struct { + // Code The machine readable description of the error. + Code string `json:"code"` + + // Field The path to the field. + Field string `json:"field"` + + // Message The human readable description of the error. + Message string `json:"message"` + AdditionalProperties map[string]interface{} `json:"-"` +} + +// Event CloudEvents Specification JSON Schema +// +// Optional properties are nullable according to the CloudEvents specification: +// OPTIONAL not omitted attributes MAY be represented as a null JSON value. +type Event = event.Event + +// EventDeliveryAttemptResponse The response of the event delivery attempt. +type EventDeliveryAttemptResponse struct { + // Body The body of the response. + Body string `json:"body"` + + // DurationMs The duration of the response in milliseconds. + DurationMs int `json:"durationMs"` + + // StatusCode Status code of the response if available. + StatusCode *int `json:"statusCode,omitempty"` + + // Url URL where the event was sent in case of notification channel with webhook type. + Url *string `json:"url,omitempty"` +} + +// ExpirationDuration The expiration duration enum +type ExpirationDuration string + +// ExpirationPeriod The grant expiration definition +type ExpirationPeriod struct { + // Count The number of time units in the expiration period. + Count uint32 `json:"count"` + + // Duration The unit of time for the expiration period. + Duration ExpirationDuration `json:"duration"` +} + +// Feature Represents a feature that can be enabled or disabled for a plan. +// Used both for product catalog and entitlements. +type Feature struct { + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *map[string]FilterString `json:"advancedMeterGroupByFilters,omitempty"` + + // ArchivedAt Timestamp of when the resource was archived. + ArchivedAt *time.Time `json:"archivedAt,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Key A key is a unique string that is used to identify a resource. + Key string `json:"key"` + Metadata *Metadata `json:"metadata,omitempty"` + + // MeterGroupByFilters Optional meter group by filters. + // Useful if the meter scope is broader than what feature tracks. + // Example scenario would be a meter tracking all token use with groupBy fields for the model, + // then the feature could filter for model=gpt-4. + // + // ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + MeterGroupByFilters *map[string]string `json:"meterGroupByFilters,omitempty"` + + // MeterSlug A key is a unique string that is used to identify a resource. + MeterSlug *string `json:"meterSlug,omitempty"` + Name string `json:"name"` + + // UnitCost Optional per-unit cost configuration. + // Use "manual" for a fixed per-unit cost, or "llm" to look up cost + // from the LLM cost database based on meter group-by properties. + UnitCost *FeatureUnitCost `json:"unitCost,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// FeatureCreateInputs Represents a feature that can be enabled or disabled for a plan. +// Used both for product catalog and entitlements. +type FeatureCreateInputs struct { + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *map[string]FilterString `json:"advancedMeterGroupByFilters,omitempty"` + + // Key A key is a unique string that is used to identify a resource. + Key string `json:"key"` + Metadata *Metadata `json:"metadata,omitempty"` + + // MeterGroupByFilters Optional meter group by filters. + // Useful if the meter scope is broader than what feature tracks. + // Example scenario would be a meter tracking all token use with groupBy fields for the model, + // then the feature could filter for model=gpt-4. + // + // ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + MeterGroupByFilters *map[string]string `json:"meterGroupByFilters,omitempty"` + + // MeterSlug A key is a unique string that is used to identify a resource. + MeterSlug *string `json:"meterSlug,omitempty"` + Name string `json:"name"` + + // UnitCost Optional per-unit cost configuration. + // Use "manual" for a fixed per-unit cost, or "llm" to look up cost + // from the LLM cost database based on meter group-by properties. + UnitCost *FeatureUnitCost `json:"unitCost,omitempty"` +} + +// FeatureLLMUnitCost LLM cost lookup configuration. +// Maps meter group-by dimensions to LLM cost database fields. +type FeatureLLMUnitCost struct { + // Model Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). + // Use this when the feature tracks a single model. + // Mutually exclusive with `modelProperty`. + Model *string `json:"model,omitempty"` + + // ModelProperty Meter group-by property that holds the model ID. + // Use this when the meter has a group-by dimension for model. + // Mutually exclusive with `model`. + ModelProperty *string `json:"modelProperty,omitempty"` + + // Pricing Resolved per-token pricing from the LLM cost database. + // Only populated in responses when the feature's meter group-by filters + // specify exact provider and model values. + Pricing *FeatureLLMUnitCostPricing `json:"pricing,omitempty"` + + // Provider Static LLM provider value (e.g., "openai", "anthropic"). + // Use this when the feature tracks a single provider. + // Mutually exclusive with `providerProperty`. + Provider *string `json:"provider,omitempty"` + + // ProviderProperty Meter group-by property that holds the LLM provider. + // Use this when the meter has a group-by dimension for provider. + // Mutually exclusive with `provider`. + ProviderProperty *string `json:"providerProperty,omitempty"` + + // TokenType Static token type value. + // Use this when the feature tracks a single token type (e.g., only input tokens). + // Expected values: input, output, cache_read, reasoning, cache_write, request, response. + // `request` is an alias for `input`, `response` is an alias for `output`. + // Mutually exclusive with `tokenTypeProperty`. + TokenType *string `json:"tokenType,omitempty"` + + // TokenTypeProperty Meter group-by property that holds the token type. + // Use this when the meter has a group-by dimension for token type. + // Mutually exclusive with `tokenType`. + TokenTypeProperty *string `json:"tokenTypeProperty,omitempty"` + Type FeatureLLMUnitCostType `json:"type"` +} + +// FeatureLLMUnitCostType defines model for FeatureLLMUnitCost.Type. +type FeatureLLMUnitCostType string + +// FeatureLLMUnitCostPricing Resolved per-token pricing from the LLM cost database. +type FeatureLLMUnitCostPricing struct { + // CacheReadPerToken Cost per cache read token in USD. + CacheReadPerToken *Numeric `json:"cacheReadPerToken,omitempty"` + + // CacheWritePerToken Cost per cache write token in USD. + CacheWritePerToken *Numeric `json:"cacheWritePerToken,omitempty"` + + // InputPerToken Cost per input token in USD. + InputPerToken Numeric `json:"inputPerToken"` + + // OutputPerToken Cost per output token in USD. + OutputPerToken Numeric `json:"outputPerToken"` + + // ReasoningPerToken Cost per reasoning token in USD. + ReasoningPerToken *Numeric `json:"reasoningPerToken,omitempty"` +} + +// FeatureManualUnitCost A fixed per-unit cost amount. +type FeatureManualUnitCost struct { + // Amount Fixed per-unit cost amount in USD. + Amount Numeric `json:"amount"` + Type FeatureManualUnitCostType `json:"type"` +} + +// FeatureManualUnitCostType defines model for FeatureManualUnitCost.Type. +type FeatureManualUnitCostType string + +// FeatureMeta Limited representation of a feature resource which includes only its unique identifiers (id, key). +type FeatureMeta struct { + // Id Unique identifier of a feature. + Id string `json:"id"` + + // Key The key is an immutable unique identifier of the feature used throughout the API, + // for example when interacting with a subject's entitlements. + Key string `json:"key"` +} + +// FeatureOrderBy Order by options for features. +type FeatureOrderBy string + +// FeaturePaginatedResponse Paginated response +type FeaturePaginatedResponse struct { + // Items The items in the current page. + Items []Feature `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// FeatureUnitCost Per-unit cost configuration for a feature. +// Either a fixed manual amount or a dynamic LLM cost lookup. +type FeatureUnitCost struct { + union json.RawMessage +} + +// FeatureUnitCostType The type of unit cost. +type FeatureUnitCostType string + +// FilterBoolean A filter for a boolean field. +type FilterBoolean struct { + // Eq The field must be equal to the provided value. + Eq *bool `json:"$eq,omitempty"` +} + +// FilterFloat A filter for a float field. +type FilterFloat struct { + // And Provide a list of filters to be combined with a logical AND. + And *[]FilterFloat `json:"$and,omitempty"` + + // Eq The field must be equal to the provided value. + Eq *float64 `json:"$eq,omitempty"` + + // Gt The field must be greater than the provided value. + Gt *float64 `json:"$gt,omitempty"` + + // Gte The field must be greater than or equal to the provided value. + Gte *float64 `json:"$gte,omitempty"` + + // Lt The field must be less than the provided value. + Lt *float64 `json:"$lt,omitempty"` + + // Lte The field must be less than or equal to the provided value. + Lte *float64 `json:"$lte,omitempty"` + + // Ne The field must not be equal to the provided value. + Ne *float64 `json:"$ne,omitempty"` + + // Or Provide a list of filters to be combined with a logical OR. + Or *[]FilterFloat `json:"$or,omitempty"` +} + +// FilterIDExact A filter for a ID (ULID) field allowing only equality or inclusion. +type FilterIDExact struct { + // In The field must be in the provided list of values. + In *[]string `json:"$in,omitempty"` +} + +// FilterInteger A filter for an integer field. +type FilterInteger struct { + // And Provide a list of filters to be combined with a logical AND. + And *[]FilterInteger `json:"$and,omitempty"` + + // Eq The field must be equal to the provided value. + Eq *int `json:"$eq,omitempty"` + + // Gt The field must be greater than the provided value. + Gt *int `json:"$gt,omitempty"` + + // Gte The field must be greater than or equal to the provided value. + Gte *int `json:"$gte,omitempty"` + + // Lt The field must be less than the provided value. + Lt *int `json:"$lt,omitempty"` + + // Lte The field must be less than or equal to the provided value. + Lte *int `json:"$lte,omitempty"` + + // Ne The field must not be equal to the provided value. + Ne *int `json:"$ne,omitempty"` + + // Or Provide a list of filters to be combined with a logical OR. + Or *[]FilterInteger `json:"$or,omitempty"` +} + +// FilterString A filter for a string field. +type FilterString struct { + // And Provide a list of filters to be combined with a logical AND. + And *[]FilterString `json:"$and,omitempty"` + + // Eq The field must be equal to the provided value. + Eq *string `json:"$eq,omitempty"` + + // Gt The field must be greater than the provided value. + Gt *string `json:"$gt,omitempty"` + + // Gte The field must be greater than or equal to the provided value. + Gte *string `json:"$gte,omitempty"` + + // Ilike The field must match the provided value, ignoring case. + Ilike *string `json:"$ilike,omitempty"` + + // In The field must be in the provided list of values. + In *[]string `json:"$in,omitempty"` + + // Like The field must match the provided value. + Like *string `json:"$like,omitempty"` + + // Lt The field must be less than the provided value. + Lt *string `json:"$lt,omitempty"` + + // Lte The field must be less than or equal to the provided value. + Lte *string `json:"$lte,omitempty"` + + // Ne The field must not be equal to the provided value. + Ne *string `json:"$ne,omitempty"` + + // Nilike The field must not match the provided value, ignoring case. + Nilike *string `json:"$nilike,omitempty"` + + // Nin The field must not be in the provided list of values. + Nin *[]string `json:"$nin,omitempty"` + + // Nlike The field must not match the provided value. + Nlike *string `json:"$nlike,omitempty"` + + // Or Provide a list of filters to be combined with a logical OR. + Or *[]FilterString `json:"$or,omitempty"` +} + +// FilterTime A filter for a time field. +type FilterTime struct { + // And Provide a list of filters to be combined with a logical AND. + And *[]FilterTime `json:"$and,omitempty"` + + // Gt The field must be greater than the provided value. + Gt *time.Time `json:"$gt,omitempty"` + + // Gte The field must be greater than or equal to the provided value. + Gte *time.Time `json:"$gte,omitempty"` + + // Lt The field must be less than the provided value. + Lt *time.Time `json:"$lt,omitempty"` + + // Lte The field must be less than or equal to the provided value. + Lte *time.Time `json:"$lte,omitempty"` + + // Or Provide a list of filters to be combined with a logical OR. + Or *[]FilterTime `json:"$or,omitempty"` +} + +// FlatPrice Flat price. +type FlatPrice struct { + // Amount The amount of the flat price. + Amount Numeric `json:"amount"` + + // Type The type of the price. + Type FlatPriceType `json:"type"` +} + +// FlatPriceType The type of the price. +type FlatPriceType string + +// FlatPriceWithPaymentTerm Flat price with payment term. +type FlatPriceWithPaymentTerm struct { + // Amount The amount of the flat price. + Amount Numeric `json:"amount"` + + // PaymentTerm The payment term of the flat price. + // Defaults to in advance. + PaymentTerm *PricePaymentTerm `json:"paymentTerm,omitempty"` + + // Type The type of the price. + Type FlatPriceWithPaymentTermType `json:"type"` +} + +// FlatPriceWithPaymentTermType The type of the price. +type FlatPriceWithPaymentTermType string + +// ForbiddenProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type ForbiddenProblemResponse = UnexpectedProblemResponse + +// GatewayTimeoutProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type GatewayTimeoutProblemResponse = UnexpectedProblemResponse + +// GrantBurnDownHistorySegment A segment of the grant burn down history. +// +// A given segment represents the usage of a grant between events that changed either the grant burn down priority order or the usag period. +type GrantBurnDownHistorySegment struct { + // BalanceAtEnd The entitlement balance at the end of the period. + BalanceAtEnd float64 `json:"balanceAtEnd"` + + // BalanceAtStart entitlement balance at the start of the period. + BalanceAtStart float64 `json:"balanceAtStart"` + + // GrantBalancesAtEnd The balance breakdown of each active grant at the end of the period: GrantID: Balance + GrantBalancesAtEnd map[string]float64 `json:"grantBalancesAtEnd"` + + // GrantBalancesAtStart The balance breakdown of each active grant at the start of the period: GrantID: Balance + GrantBalancesAtStart map[string]float64 `json:"grantBalancesAtStart"` + + // GrantUsages Which grants were actually burnt down in the period and by what amount. + GrantUsages []GrantUsageRecord `json:"grantUsages"` + + // Overage Overuse that wasn't covered by grants. + Overage float64 `json:"overage"` + + // Period The period of the segment. + Period Period `json:"period"` + + // Usage The total usage of the grant in the period. + Usage float64 `json:"usage"` +} + +// GrantOrderBy Order by options for grants. +type GrantOrderBy string + +// GrantPaginatedResponse Paginated response +type GrantPaginatedResponse struct { + // Items The items in the current page. + Items []EntitlementGrant `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// GrantUsageRecord Usage Record +type GrantUsageRecord struct { + // GrantId The id of the grant + GrantId string `json:"grantId"` + + // Usage The usage in the period + Usage float64 `json:"usage"` +} + +// GrantV2PaginatedResponse Paginated response +type GrantV2PaginatedResponse struct { + // Items The items in the current page. + Items []EntitlementGrantV2 `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// IDResource IDResource is a resouce with an ID. +type IDResource struct { + // Id A unique identifier for the resource. + Id string `json:"id"` +} + +// IngestEventsBody The body of the events request. +// Either a single event or a batch of events. +type IngestEventsBody struct { + union json.RawMessage +} + +// IngestEventsBody1 defines model for . +type IngestEventsBody1 = []Event + +// IngestedEvent An ingested event with optional validation error. +type IngestedEvent struct { + // CustomerId The customer ID if the event is associated with a customer. + CustomerId *string `json:"customerId,omitempty"` + + // Event The original event ingested. + Event Event `json:"event"` + + // IngestedAt The date and time the event was ingested. + IngestedAt time.Time `json:"ingestedAt"` + + // StoredAt The date and time the event was stored. + StoredAt time.Time `json:"storedAt"` + + // ValidationError The validation error if the event failed validation. + ValidationError *string `json:"validationError,omitempty"` +} + +// IngestedEventCursorPaginatedResponse A response for cursor pagination. +type IngestedEventCursorPaginatedResponse struct { + // Items The items in the response. + Items []IngestedEvent `json:"items"` + + // NextCursor The cursor of the last item in the list. + NextCursor *string `json:"nextCursor,omitempty"` +} + +// InstallMethod Install method of the application. +type InstallMethod string + +// InternalServerErrorProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type InternalServerErrorProblemResponse = UnexpectedProblemResponse + +// Invoice Invoice represents an invoice in the system. +type Invoice struct { + // CollectionAt The time when the invoice will be/has been collected. + CollectionAt *time.Time `json:"collectionAt,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency Currency for all invoice line items. + // + // Multi currency invoices are not supported yet. + Currency CurrencyCode `json:"currency"` + + // Customer Legal entity receiving the goods or services. + Customer BillingInvoiceCustomerExtendedDetails `json:"customer"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // DraftUntil The time until the invoice is in draft status. + // + // On draft invoice creation it is calculated from the workflow settings. + // + // If manual approval is required, the draftUntil time is set. + DraftUntil *time.Time `json:"draftUntil,omitempty"` + + // DueAt Due time of the fulfillment of the invoice (if available). + DueAt *time.Time `json:"dueAt,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceAppExternalIds `json:"externalIds,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // IssuedAt The time the invoice was issued. + // + // Depending on the status of the invoice this can mean multiple things: + // - draft, gathering: The time the invoice will be issued based on the workflow settings. + // - issued: The time the invoice was issued. + IssuedAt *time.Time `json:"issuedAt,omitempty"` + + // Lines List of invoice lines representing each of the items sold to the customer. + Lines *[]InvoiceLine `json:"lines,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Number Number specifies the human readable key used to reference this Invoice. + // + // The invoice number can change in the draft phases, as we are allocating temporary draft + // invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + // + // Please note that the number is (depending on the upstream settings) either unique for the + // whole organization or unique for the customer, or in multi (stripe) account setups unique for the + // account. + Number InvoiceNumber `json:"number"` + + // Payment Information on when, how, and to whom the invoice should be paid. + Payment *InvoicePaymentTerms `json:"payment,omitempty"` + + // Period The period the invoice covers. If the invoice has no line items, it's not set. + Period *Period `json:"period,omitempty"` + + // Preceding Key information regarding previous invoices and potentially details as to why they were corrected. + Preceding *[]InvoiceDocumentRef `json:"preceding,omitempty"` + + // QuantitySnapshotedAt The time when the quantity snapshots on the invoice lines were taken. + QuantitySnapshotedAt *time.Time `json:"quantitySnapshotedAt,omitempty"` + + // SentToCustomerAt The time the invoice was sent to customer. + SentToCustomerAt *time.Time `json:"sentToCustomerAt,omitempty"` + + // Status The status of the invoice. + // + // This field only conatins a simplified status, for more detailed information use the statusDetails field. + Status InvoiceStatus `json:"status"` + + // StatusDetails The details of the current invoice status. + StatusDetails InvoiceStatusDetails `json:"statusDetails"` + + // Supplier The taxable entity supplying the goods or services. + Supplier BillingParty `json:"supplier"` + + // Totals Summary of all the invoice totals, including taxes (calculated). + Totals InvoiceTotals `json:"totals"` + + // Type Type of the invoice. + // + // The type of invoice determines the purpose of the invoice and how it should be handled. + // + // Supported types: + // - standard: A regular commercial invoice document between a supplier and customer. + // - credit_note: Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + Type InvoiceType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationIssues Validation issues reported by the invoice workflow. + ValidationIssues *[]ValidationIssue `json:"validationIssues,omitempty"` + + // VoidedAt The time the invoice was voided. + // + // If the invoice was voided, this field will be set to the time the invoice was voided. + VoidedAt *time.Time `json:"voidedAt,omitempty"` + + // Workflow The workflow associated with the invoice. + // + // It is always a snapshot of the workflow settings at the time of invoice creation. The + // field is optional as it should be explicitly requested with expand options. + Workflow InvoiceWorkflowSettings `json:"workflow"` +} + +// InvoiceAppExternalIds InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. +type InvoiceAppExternalIds struct { + // Invoicing The external ID of the invoice in the invoicing app if available. + Invoicing *string `json:"invoicing,omitempty"` + + // Payment The external ID of the invoice in the payment app if available. + Payment *string `json:"payment,omitempty"` + + // Tax The external ID of the invoice in the tax app if available. + Tax *string `json:"tax,omitempty"` +} + +// InvoiceAvailableActionDetails InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for +// non-gathering invoices. +type InvoiceAvailableActionDetails struct { + // ResultingState The state the invoice will reach if the action is activated and + // all intermediate steps are successful. + // + // For example advancing a draft_created invoice will result in a draft_manual_approval_needed invoice. + ResultingState string `json:"resultingState"` +} + +// InvoiceAvailableActionInvoiceDetails InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for +// gathering invoices. +type InvoiceAvailableActionInvoiceDetails = map[string]interface{} + +// InvoiceAvailableActions InvoiceAvailableActions represents the actions that can be performed on the invoice. +type InvoiceAvailableActions struct { + // Advance Advance the invoice to the next status. + Advance *InvoiceAvailableActionDetails `json:"advance,omitempty"` + + // Approve Approve an invoice that requires manual approval. + Approve *InvoiceAvailableActionDetails `json:"approve,omitempty"` + + // Delete Delete the invoice (only non-issued invoices can be deleted). + Delete *InvoiceAvailableActionDetails `json:"delete,omitempty"` + + // Invoice Invoice a gathering invoice + Invoice *InvoiceAvailableActionInvoiceDetails `json:"invoice,omitempty"` + + // Retry Retry an invoice issuing step that failed. + Retry *InvoiceAvailableActionDetails `json:"retry,omitempty"` + + // SnapshotQuantities Snapshot quantities for usage based line items. + SnapshotQuantities *InvoiceAvailableActionDetails `json:"snapshotQuantities,omitempty"` + + // Void Void an already issued invoice. + Void *InvoiceAvailableActionDetails `json:"void,omitempty"` +} + +// InvoiceDetailedLine InvoiceDetailedLine represents a line item that is sold to the customer as a manually added fee. +type InvoiceDetailedLine struct { + // Category Category of the flat fee. + Category *InvoiceDetailedLineCostCategory `json:"category,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CreditAllocations Credit allocations applied to this line. + // + // Credits are deducted from the line total before taxes are applied. + CreditAllocations *[]InvoiceLineCreditAllocation `json:"creditAllocations,omitempty"` + + // Currency The currency of this line. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts Discounts detailes applied to this line. + // + // New discounts can be added via the invoice's discounts API, to facilitate + // discounts that are affecting multiple lines. + Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the line. + Id string `json:"id"` + + // Invoice The invoice this item belongs to. + Invoice *InvoiceReference `json:"invoice,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + InvoiceAt time.Time `json:"invoiceAt"` + + // ManagedBy managedBy specifies if the line is manually added via the api or managed by OpenMeter. + ManagedBy InvoiceLineManagedBy `json:"managedBy"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PaymentTerm Payment term of the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + PaymentTerm *PricePaymentTerm `json:"paymentTerm,omitempty"` + + // PerUnitAmount Price of the item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + PerUnitAmount *Numeric `json:"perUnitAmount,omitempty"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Quantity Quantity of the item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Quantity *Numeric `json:"quantity,omitempty"` + + // RateCard The rate card that is used for this line. + RateCard *InvoiceDetailedLineRateCard `json:"rateCard,omitempty"` + + // Status Status of the line. + // + // External calls always create valid lines, other line types are managed by the + // billing engine of OpenMeter. + Status InvoiceLineStatus `json:"status"` + + // Subscription Subscription are the references to the subscritpions that this line is related to. + Subscription *InvoiceLineSubscriptionReference `json:"subscription,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Taxes Taxes applied to the invoice totals. + Taxes *[]InvoiceLineTaxItem `json:"taxes,omitempty"` + + // Totals Totals for this line. + Totals InvoiceTotals `json:"totals"` + + // Type Type of the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Type InvoiceDetailedLineType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceDetailedLineType Type of the line. +type InvoiceDetailedLineType string + +// InvoiceDetailedLineCostCategory InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a +// commitment. +type InvoiceDetailedLineCostCategory string + +// InvoiceDetailedLineRateCard InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. +type InvoiceDetailedLineRateCard struct { + // Discounts The discounts that are applied to the line. + Discounts *BillingDiscounts `json:"discounts,omitempty"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *FlatPriceWithPaymentTerm `json:"price"` + + // Quantity Quantity of the item being sold. + // + // Default: 1 + Quantity *Numeric `json:"quantity,omitempty"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceDiscountBase InvoiceDiscountBase represents a charge or discount that can be applied to a line or the entire invoice. +type InvoiceDiscountBase struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Text description as to why the discount was applied. + Description *string `json:"description,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // Reason Reason code. + Reason BillingDiscountReason `json:"reason"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceDocumentRef CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is based on. +type InvoiceDocumentRef = CreditNoteOriginalInvoiceRef + +// InvoiceDocumentRefType InvoiceDocumentRefType defines the type of document that is being referenced. +type InvoiceDocumentRefType string + +// InvoiceExpand InvoiceExpand specifies the parts of the invoice to expand in the list output. +type InvoiceExpand string + +// InvoiceGenericDocumentRef Omitted fields: +// period: Tax period in which the referred document had an effect required by some tax regimes and formats. +// stamps: Seals of approval from other organisations that may need to be listed. +// ext: Extensions for additional codes that may be required. +type InvoiceGenericDocumentRef struct { + // Description Additional details about the document. + Description *string `json:"description,omitempty"` + + // Reason Human readable description on why this reference is here or needs to be used. + Reason *string `json:"reason,omitempty"` + + // Type Type of the document referenced. + Type InvoiceDocumentRefType `json:"type"` +} + +// InvoiceLine InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. +type InvoiceLine struct { + // Children The lines detailing the item or service sold. + Children *[]InvoiceDetailedLine `json:"children,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CreditAllocations Credit allocations applied to this line. + // + // Credits are deducted from the line total before taxes are applied. + CreditAllocations *[]InvoiceLineCreditAllocation `json:"creditAllocations,omitempty"` + + // Currency The currency of this line. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts Discounts detailes applied to this line. + // + // New discounts can be added via the invoice's discounts API, to facilitate + // discounts that are affecting multiple lines. + Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // Id ID of the line. + Id string `json:"id"` + + // Invoice The invoice this item belongs to. + Invoice *InvoiceReference `json:"invoice,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // ManagedBy managedBy specifies if the line is manually added via the api or managed by OpenMeter. + ManagedBy InvoiceLineManagedBy `json:"managedBy"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // MeteredPreLinePeriodQuantity The metered quantity of the item used in before this line's period without any discounts applied. + // + // It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + MeteredPreLinePeriodQuantity *Numeric `json:"meteredPreLinePeriodQuantity,omitempty"` + + // MeteredQuantity The quantity of the item that has been metered for the period before any discounts were applied. + MeteredQuantity *Numeric `json:"meteredQuantity,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // PreLinePeriodQuantity The quantity of the item used before this line's period. + // + // It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + // + // Any usage discounts applied previously are deducted from this quantity. + PreLinePeriodQuantity *Numeric `json:"preLinePeriodQuantity,omitempty"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // Quantity The quantity of the item being sold. + // + // Any usage discounts applied previously are deducted from this quantity. + Quantity *Numeric `json:"quantity,omitempty"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // Status Status of the line. + // + // External calls always create valid lines, other line types are managed by the + // billing engine of OpenMeter. + Status InvoiceLineStatus `json:"status"` + + // Subscription Subscription are the references to the subscritpions that this line is related to. + Subscription *InvoiceLineSubscriptionReference `json:"subscription,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Taxes Taxes applied to the invoice totals. + Taxes *[]InvoiceLineTaxItem `json:"taxes,omitempty"` + + // Totals Totals for this line. + Totals InvoiceTotals `json:"totals"` + + // Type Type of the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Type InvoiceLineType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceLineType Type of the line. +type InvoiceLineType string + +// InvoiceLineAmountDiscount InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied before taxes. +type InvoiceLineAmountDiscount struct { + // Amount Fixed discount amount to apply (calculated if percent present). + Amount Numeric `json:"amount"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Text description as to why the discount was applied. + Description *string `json:"description,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // Reason Reason code. + Reason BillingDiscountReason `json:"reason"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceLineAppExternalIds InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. +type InvoiceLineAppExternalIds struct { + // Invoicing The external ID of the invoice in the invoicing app if available. + Invoicing *string `json:"invoicing,omitempty"` + + // Tax The external ID of the invoice in the tax app if available. + Tax *string `json:"tax,omitempty"` +} + +// InvoiceLineBase InvoiceLine represents a single item or service sold to the customer. +// +// This is a base class for all line types, and should not be used directly. +type InvoiceLineBase struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CreditAllocations Credit allocations applied to this line. + // + // Credits are deducted from the line total before taxes are applied. + CreditAllocations *[]InvoiceLineCreditAllocation `json:"creditAllocations,omitempty"` + + // Currency The currency of this line. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts Discounts detailes applied to this line. + // + // New discounts can be added via the invoice's discounts API, to facilitate + // discounts that are affecting multiple lines. + Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the line. + Id string `json:"id"` + + // Invoice The invoice this item belongs to. + Invoice *InvoiceReference `json:"invoice,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // ManagedBy managedBy specifies if the line is manually added via the api or managed by OpenMeter. + ManagedBy InvoiceLineManagedBy `json:"managedBy"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Status Status of the line. + // + // External calls always create valid lines, other line types are managed by the + // billing engine of OpenMeter. + Status InvoiceLineStatus `json:"status"` + + // Subscription Subscription are the references to the subscritpions that this line is related to. + Subscription *InvoiceLineSubscriptionReference `json:"subscription,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Taxes Taxes applied to the invoice totals. + Taxes *[]InvoiceLineTaxItem `json:"taxes,omitempty"` + + // Totals Totals for this line. + Totals InvoiceTotals `json:"totals"` + + // Type Type of the line. + // + // A line's type cannot be changed after creation. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Type InvoiceLineTypes `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceLineCreditAllocation InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are applied. +type InvoiceLineCreditAllocation struct { + // Amount Amount allocated from credits. + Amount Numeric `json:"amount"` + + // Description Text description as to why the credit was allocated. + Description *string `json:"description,omitempty"` +} + +// InvoiceLineDiscounts InvoiceLineDiscounts represents the discounts applied to the invoice line by type. +type InvoiceLineDiscounts struct { + // Amount Amount based discounts applied to the line. + // + // Amount based discounts are deduced from the total price of the line. + Amount *[]InvoiceLineAmountDiscount `json:"amount,omitempty"` + + // Usage Usage based discounts applied to the line. + // + // Usage based discounts are deduced from the usage of the line before price calculations are applied. + Usage *[]InvoiceLineUsageDiscount `json:"usage,omitempty"` +} + +// InvoiceLineManagedBy InvoiceLineManagedBy specifies who manages the line. +type InvoiceLineManagedBy string + +// InvoiceLineReplaceUpdate InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. +// +// This type makes ID optional to allow for creating new lines as part of the update. +type InvoiceLineReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // Id The ID of the line. + Id *string `json:"id,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceLineStatus Line status specifies the status of the line. +type InvoiceLineStatus string + +// InvoiceLineSubscriptionReference InvoiceLineSubscriptionReference contains the references to the subscription that this line is related to. +type InvoiceLineSubscriptionReference struct { + // BillingPeriod The billing period of the subscription. In case the subscription item's billing period is different + // from the subscription's billing period, this field will contain the billing period of the subscription itself. + // + // For example, in case of: + // - A monthly billed subscription anchored to 2025-01-01 + // - A subscription item billed daily + // + // An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed daily, but the subscription's billing period + // will be 2025-01-01 to 2025-01-31. + BillingPeriod Period `json:"billingPeriod"` + + // Item The item this line is related to. + Item IDResource `json:"item"` + + // Phase The phase of the subscription. + Phase IDResource `json:"phase"` + + // Subscription The subscription. + Subscription IDResource `json:"subscription"` +} + +// InvoiceLineTaxBehavior InvoiceLineTaxBehavior details how the tax item is applied to the base amount. +// +// Inclusive means the tax is included in the base amount. +// Exclusive means the tax is added to the base amount. +type InvoiceLineTaxBehavior string + +// InvoiceLineTaxItem TaxConfig stores the configuration for a tax line relative to an invoice line. +type InvoiceLineTaxItem struct { + // Behavior Is the tax item inclusive or exclusive of the base amount. + Behavior *InvoiceLineTaxBehavior `json:"behavior,omitempty"` + + // Config Tax provider configuration. + Config *TaxConfig `json:"config,omitempty"` + + // Percent Percent defines the percentage set manually or determined from + // the rate key (calculated if rate present). A nil percent implies that + // this tax combo is **exempt** from tax.") + Percent *Percentage `json:"percent,omitempty"` + + // Surcharge Some countries require an additional surcharge (calculated if rate present). + Surcharge *Numeric `json:"surcharge,omitempty"` +} + +// InvoiceLineTypes LineTypes represents the different types of lines that can be used in an invoice. +type InvoiceLineTypes string + +// InvoiceLineUsageDiscount InvoiceLineUsageDiscount represents an usage-based discount applied to the line. +// +// The deduction is done before the pricing algorithm is applied. +type InvoiceLineUsageDiscount struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Text description as to why the discount was applied. + Description *string `json:"description,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // PreLinePeriodQuantity The usage discount already applied to the previous split lines. + // + // Only set if progressive billing is enabled and the line is a split line. + PreLinePeriodQuantity *Numeric `json:"preLinePeriodQuantity,omitempty"` + + // Quantity The usage to apply. + Quantity Numeric `json:"quantity"` + + // Reason Reason code. + Reason BillingDiscountReason `json:"reason"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceNumber InvoiceNumber is a unique identifier for the invoice, generated by the +// invoicing app. +// +// The uniqueness depends on a lot of factors: +// - app setting (unique per app or unique per customer) +// - multiple app scenarios (multiple apps generating invoices with the same prefix) +type InvoiceNumber = string + +// InvoiceOrderBy InvoiceOrderBy specifies the ordering options for invoice listing. +type InvoiceOrderBy string + +// InvoicePaginatedResponse Paginated response +type InvoicePaginatedResponse struct { + // Items The items in the current page. + Items []Invoice `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// InvoicePaymentTerms Payment contains details as to how the invoice should be paid. +type InvoicePaymentTerms struct { + // Terms The terms of payment for the invoice. + Terms *PaymentTerms `json:"terms,omitempty"` +} + +// InvoicePendingLineCreate InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage. +type InvoicePendingLineCreate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoicePendingLineCreateInput InvoicePendingLineCreate represents the create model for a pending invoice line. +type InvoicePendingLineCreateInput struct { + // Currency The currency of the lines to be created. + Currency CurrencyCode `json:"currency"` + + // Lines The lines to be created. + Lines []InvoicePendingLineCreate `json:"lines"` +} + +// InvoicePendingLineCreateResponse InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. +type InvoicePendingLineCreateResponse struct { + // Invoice The invoice containing the created lines. + Invoice Invoice `json:"invoice"` + + // IsInvoiceNew Whether the invoice was newly created. + IsInvoiceNew bool `json:"isInvoiceNew"` + + // Lines The lines that were created. + Lines []InvoiceLine `json:"lines"` +} + +// InvoicePendingLinesActionFiltersInput InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. +type InvoicePendingLinesActionFiltersInput struct { + // LineIds The pending line items to include in the invoice, if not provided: + // - all line items that have invoice_at < asOf will be included + // - [progressive billing only] all usage based line items will be included up to asOf, new + // usage-based line items will be staged for the rest of the billing cycle + // + // All lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail. + LineIds *[]string `json:"lineIds,omitempty"` +} + +// InvoicePendingLinesActionInput BillingInvoiceActionInput is the input for creating an invoice. +// +// Invoice creation is always based on already pending line items created by the billingCreateLineByCustomer +// operation. Empty invoices are not allowed. +type InvoicePendingLinesActionInput struct { + // AsOf The time as of which the invoice is created. + // + // If not provided, the current time is used. + AsOf *time.Time `json:"asOf,omitempty"` + + // CustomerId The customer ID for which to create the invoice. + CustomerId string `json:"customerId"` + + // Filters Filters to apply when creating the invoice. + Filters *InvoicePendingLinesActionFiltersInput `json:"filters,omitempty"` + + // ProgressiveBillingOverride Override the progressive billing setting of the customer. + // + // Can be used to disable/enable progressive billing in case the business logic + // requires it, if not provided the billing profile's progressive billing setting will be used. + ProgressiveBillingOverride *bool `json:"progressiveBillingOverride,omitempty"` +} + +// InvoiceReference Reference to an invoice. +type InvoiceReference struct { + // Id The ID of the invoice. + Id string `json:"id"` + + // Number The number of the invoice. + Number *InvoiceNumber `json:"number,omitempty"` +} + +// InvoiceReplaceUpdate InvoiceReplaceUpdate represents the update model for an invoice. +type InvoiceReplaceUpdate struct { + // Customer The customer the invoice is sent to. + Customer BillingPartyReplaceUpdate `json:"customer"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Lines The lines included in the invoice. + Lines []InvoiceLineReplaceUpdate `json:"lines"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Supplier The supplier of the lines included in the invoice. + Supplier BillingPartyReplaceUpdate `json:"supplier"` + + // Workflow The workflow settings for the invoice. + Workflow InvoiceWorkflowReplaceUpdate `json:"workflow"` +} + +// InvoiceSimulationInput InvoiceSimulationInput is the input for simulating an invoice. +type InvoiceSimulationInput struct { + // Currency Currency for all invoice line items. + // + // Multi currency invoices are not supported yet. + Currency CurrencyCode `json:"currency"` + + // Lines Lines to be included in the generated invoice. + Lines []InvoiceSimulationLine `json:"lines"` + + // Number The number of the invoice. + Number *InvoiceNumber `json:"number,omitempty"` +} + +// InvoiceSimulationLine InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint. +type InvoiceSimulationLine struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // Id ID of the line. If not specified it will be auto-generated. + // + // When discounts are specified, this must be provided, so that the discount can reference it. + Id *string `json:"id,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // PreLinePeriodQuantity The quantity of the item used before this line's period, if the line is billed progressively. + PreLinePeriodQuantity *Numeric `json:"preLinePeriodQuantity,omitempty"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // Quantity The quantity of the item being sold. + Quantity Numeric `json:"quantity"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceStatus InvoiceStatus describes the status of an invoice. +type InvoiceStatus string + +// InvoiceStatusDetails InvoiceStatusDetails represents the details of the invoice status. +// +// API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine +// the next steps of the invoice instead of the extendedStatus field. +type InvoiceStatusDetails struct { + // AvailableActions The actions that can be performed on the invoice. + AvailableActions InvoiceAvailableActions `json:"availableActions"` + + // ExtendedStatus Extended status information for the invoice. + ExtendedStatus string `json:"extendedStatus"` + + // Failed Is the invoice in a failed state? + Failed bool `json:"failed"` + + // Immutable Is the invoice editable? + Immutable bool `json:"immutable"` +} + +// InvoiceTotals Totals contains the summaries of all calculations for the invoice. +type InvoiceTotals struct { + // Amount The total value of the line before taxes, discounts and commitments. + Amount Numeric `json:"amount"` + + // ChargesTotal The amount of value of the line that are due to additional charges. + ChargesTotal Numeric `json:"chargesTotal"` + + // CreditsTotal The amount of value of the line that are due to credits. + CreditsTotal Numeric `json:"creditsTotal"` + + // DiscountsTotal The amount of value of the line that are due to discounts. + DiscountsTotal Numeric `json:"discountsTotal"` + + // TaxesExclusiveTotal The total amount of taxes that are added on top of amount from the line. + TaxesExclusiveTotal Numeric `json:"taxesExclusiveTotal"` + + // TaxesInclusiveTotal The total amount of taxes that are included in the line. + TaxesInclusiveTotal Numeric `json:"taxesInclusiveTotal"` + + // TaxesTotal The total amount of taxes for this line. + TaxesTotal Numeric `json:"taxesTotal"` + + // Total The total amount value of the line after taxes, discounts and commitments. + Total Numeric `json:"total"` +} + +// InvoiceType InvoiceType represents the type of invoice. +// +// The type of invoice determines the purpose of the invoice and how it should be handled. +type InvoiceType string + +// InvoiceUsageBasedRateCard InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. +type InvoiceUsageBasedRateCard struct { + // Discounts The discounts that are applied to the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Discounts *BillingDiscounts `json:"discounts,omitempty"` + + // FeatureKey The feature the customer is entitled to use. + FeatureKey *string `json:"featureKey,omitempty"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *RateCardUsageBasedPrice `json:"price"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceWorkflowInvoicingSettingsReplaceUpdate InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow. +type InvoiceWorkflowInvoicingSettingsReplaceUpdate struct { + // AutoAdvance Whether to automatically issue the invoice after the draftPeriod has passed. + AutoAdvance *bool `json:"autoAdvance,omitempty"` + + // DefaultTaxConfig Default tax configuration to apply to the invoices. + // + // Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + // deprecated and can no longer be added or changed: the organization default tax code is + // used instead. Existing tax-code values may still be removed, and `behavior` remains + // fully supported. + DefaultTaxConfig *TaxConfig `json:"defaultTaxConfig,omitempty"` + + // DraftPeriod The period for the invoice to be kept in draft status for manual reviews. + DraftPeriod *string `json:"draftPeriod,omitempty"` + + // DueAfter The period after which the invoice is due. + // With some payment solutions it's only applicable for manual collection method. + DueAfter *string `json:"dueAfter,omitempty"` + + // SubscriptionEndProrationMode Controls how subscription-ending shortened service periods are billed. + SubscriptionEndProrationMode *BillingWorkflowInvoicingSubscriptionEndProrationMode `json:"subscriptionEndProrationMode,omitempty"` +} + +// InvoiceWorkflowReplaceUpdate InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. +// +// Fields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings. +type InvoiceWorkflowReplaceUpdate struct { + // Workflow The workflow used for this invoice. + Workflow InvoiceWorkflowSettingsReplaceUpdate `json:"workflow"` +} + +// InvoiceWorkflowSettings InvoiceWorkflowSettings represents the workflow settings used by the invoice. +// +// This is a clone of the billing profile's workflow settings at the time of invoice creation +// with customer overrides considered. +type InvoiceWorkflowSettings struct { + // Apps The apps that will be used to orchestrate the invoice's workflow. + Apps *BillingProfileAppsOrReference `json:"apps,omitempty"` + + // SourceBillingProfileId sourceBillingProfileID is the billing profile on which the workflow was based on. + // + // The profile is snapshotted on invoice creation, after which it can be altered independently + // of the profile itself. + SourceBillingProfileId string `json:"sourceBillingProfileId"` + + // Workflow The workflow details used by this invoice. + Workflow BillingWorkflow `json:"workflow"` +} + +// InvoiceWorkflowSettingsReplaceUpdate Mutable workflow settings for an invoice. +// +// Other fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow +// at creation time. +type InvoiceWorkflowSettingsReplaceUpdate struct { + // Invoicing The invoicing settings for this workflow + Invoicing InvoiceWorkflowInvoicingSettingsReplaceUpdate `json:"invoicing"` + + // Payment The payment settings for this workflow + Payment BillingWorkflowPaymentSettings `json:"payment"` +} + +// IssueAfterReset Issue after reset +type IssueAfterReset struct { + // Amount The initial grant amount + Amount float64 `json:"amount"` + + // Priority The priority of the issue after reset + Priority *uint8 `json:"priority,omitempty"` +} + +// ListAppsRequest Query params for listing installed apps +type ListAppsRequest struct { + // Page Page index. + // + // Default is 1. + Page *int `json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *int `json:"pageSize,omitempty"` +} + +// ListEntitlementsResult List entitlements result +type ListEntitlementsResult struct { + union json.RawMessage +} + +// ListEntitlementsResult0 defines model for . +type ListEntitlementsResult0 = []Entitlement + +// ListFeaturesResult List features result +type ListFeaturesResult struct { + union json.RawMessage +} + +// ListFeaturesResult0 defines model for . +type ListFeaturesResult0 = []Feature + +// MarketplaceInstallRequestPayload Marketplace install request payload. +type MarketplaceInstallRequestPayload struct { + // CreateBillingProfile If true, a billing profile will be created for the app. + // The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + CreateBillingProfile *bool `json:"createBillingProfile,omitempty"` + + // Name Name of the application to install. + // + // If name is not provided defaults to the marketplace listing's name. + Name *string `json:"name,omitempty"` +} + +// MarketplaceInstallResponse Marketplace install response. +type MarketplaceInstallResponse struct { + // App App. + // One of: stripe + App App `json:"app"` + + // DefaultForCapabilityTypes Default for capabilities + DefaultForCapabilityTypes []AppCapabilityType `json:"defaultForCapabilityTypes"` +} + +// MarketplaceListing A marketplace listing. +// Represent an available app in the app marketplace that can be installed to the organization. +// +// Marketplace apps only exist in config so they don't extend the Resource model. +type MarketplaceListing struct { + // Capabilities The app's capabilities. + Capabilities []AppCapability `json:"capabilities"` + + // Description The app's description. + Description string `json:"description"` + + // InstallMethods Install methods. + // + // List of methods to install the app. + InstallMethods []InstallMethod `json:"installMethods"` + + // Name The app's name. + Name string `json:"name"` + + // Type The app's type + Type AppType `json:"type"` +} + +// MarketplaceListingPaginatedResponse Paginated response +type MarketplaceListingPaginatedResponse struct { + // Items The items in the current page. + Items []MarketplaceListing `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// MeasureUsageFrom Measure usage from +type MeasureUsageFrom struct { + union json.RawMessage +} + +// MeasureUsageFromPreset Start of measurement options +type MeasureUsageFromPreset string + +// MeasureUsageFromTime [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. +type MeasureUsageFromTime = time.Time + +// Metadata Set of key-value pairs. +// Metadata can be used to store additional information about a resource. +type Metadata = map[string]string + +// Meter A meter is a configuration that defines how to match and aggregate events. +type Meter struct { + // Aggregation The aggregation type to use for the meter. + Aggregation MeterAggregation `json:"aggregation"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EventFrom The date since the meter should include events. + // Useful to skip old events. + // If not specified, all historical events are included. + EventFrom *time.Time `json:"eventFrom,omitempty"` + + // EventType The event type to aggregate. + EventType string `json:"eventType"` + + // GroupBy Named JSONPath expressions to extract the group by values from the event data. + // + // Keys must be unique and consist only alphanumeric and underscore characters. + GroupBy *map[string]string `json:"groupBy,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + // Defaults to the slug if not specified. + Name *string `json:"name,omitempty"` + + // Slug A unique, human-readable identifier for the meter. + // Must consist only alphanumeric and underscore characters. + Slug string `json:"slug"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValueProperty JSONPath expression to extract the value from the ingested event's data property. + // + // The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + // + // For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + ValueProperty *string `json:"valueProperty,omitempty"` +} + +// MeterAggregation The aggregation type to use for the meter. +type MeterAggregation string + +// MeterCreate A meter create model. +type MeterCreate struct { + // Aggregation The aggregation type to use for the meter. + Aggregation MeterAggregation `json:"aggregation"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EventFrom The date since the meter should include events. + // Useful to skip old events. + // If not specified, all historical events are included. + EventFrom *time.Time `json:"eventFrom,omitempty"` + + // EventType The event type to aggregate. + EventType string `json:"eventType"` + + // GroupBy Named JSONPath expressions to extract the group by values from the event data. + // + // Keys must be unique and consist only alphanumeric and underscore characters. + GroupBy *map[string]string `json:"groupBy,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + // Defaults to the slug if not specified. + Name *string `json:"name,omitempty"` + + // Slug A unique, human-readable identifier for the meter. + // Must consist only alphanumeric and underscore characters. + Slug string `json:"slug"` + + // ValueProperty JSONPath expression to extract the value from the ingested event's data property. + // + // The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + // + // For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + ValueProperty *string `json:"valueProperty,omitempty"` +} + +// MeterOrderBy Order by options for meters. +type MeterOrderBy string + +// MeterQueryRequest A meter query request. +type MeterQueryRequest struct { + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *map[string]FilterString `json:"advancedMeterGroupByFilters,omitempty"` + + // ClientId Client ID + // Useful to track progress of a query. + ClientId *string `json:"clientId,omitempty"` + + // FilterCustomerId Filtering by multiple customers. + FilterCustomerId *[]string `json:"filterCustomerId,omitempty"` + + // FilterGroupBy Simple filter for group bys with exact match. + FilterGroupBy *map[string][]string `json:"filterGroupBy,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + From *time.Time `json:"from,omitempty"` + + // GroupBy If not specified a single aggregate will be returned for each subject and time window. + // `subject` is a reserved group by value. + GroupBy *[]string `json:"groupBy,omitempty"` + + // Subject Filtering by multiple subjects. + Subject *[]string `json:"subject,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + To *time.Time `json:"to,omitempty"` + + // WindowSize If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + WindowSize *WindowSize `json:"windowSize,omitempty"` + + // WindowTimeZone The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + // If not specified, the UTC timezone will be used. + WindowTimeZone *string `json:"windowTimeZone,omitempty"` +} + +// MeterQueryResult The result of a meter query. +type MeterQueryResult struct { + // Data The usage data. + // If no data is available, an empty array is returned. + Data []MeterQueryRow `json:"data"` + + // From The start of the period the usage is queried from. + // If not specified, the usage is queried from the beginning of time. + From *time.Time `json:"from,omitempty"` + + // To The end of the period the usage is queried to. + // If not specified, the usage is queried up to the current time. + To *time.Time `json:"to,omitempty"` + + // WindowSize The window size that the usage is aggregated. + // If not specified, the usage is aggregated over the entire period. + WindowSize *WindowSize `json:"windowSize,omitempty"` +} + +// MeterQueryRow A row in the result of a meter query. +type MeterQueryRow struct { + // CustomerId The customer ID the value is aggregated over. + CustomerId *string `json:"customerId,omitempty"` + + // GroupBy The group by values the value is aggregated over. + GroupBy map[string]*string `json:"groupBy"` + + // Subject The subject the value is aggregated over. + // If not specified, the value is aggregated over all subjects. + Subject *string `json:"subject"` + + // Value The aggregated value. + Value float64 `json:"value"` + + // WindowEnd The end of the window the value is aggregated over. + WindowEnd time.Time `json:"windowEnd"` + + // WindowStart The start of the window the value is aggregated over. + WindowStart time.Time `json:"windowStart"` +} + +// MeterUpdate A meter update model. +// +// Only the properties that can be updated are included. +// For example, the slug and aggregation cannot be updated. +type MeterUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // GroupBy Named JSONPath expressions to extract the group by values from the event data. + // + // Keys must be unique and consist only alphanumeric and underscore characters. + GroupBy *map[string]string `json:"groupBy,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + // Defaults to the slug if not specified. + Name *string `json:"name,omitempty"` +} + +// NotFoundProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type NotFoundProblemResponse = UnexpectedProblemResponse + +// NotImplementedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type NotImplementedProblemResponse = UnexpectedProblemResponse + +// NotificationChannel Notification channel with webhook type. +type NotificationChannel = NotificationChannelWebhook + +// NotificationChannelCreateRequest Request with input parameters for creating new notification channel with webhook type. +type NotificationChannelCreateRequest = NotificationChannelWebhookCreateRequest + +// NotificationChannelMeta Metadata only fields of a notification channel. +type NotificationChannelMeta struct { + // Id Identifies the notification channel. + Id string `json:"id"` + + // Type Notification channel type. + Type NotificationChannelType `json:"type"` +} + +// NotificationChannelOrderBy Order by options for notification channels. +type NotificationChannelOrderBy string + +// NotificationChannelPaginatedResponse Paginated response +type NotificationChannelPaginatedResponse struct { + // Items The items in the current page. + Items []NotificationChannel `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// NotificationChannelType Type of the notification channel. +type NotificationChannelType string + +// NotificationChannelWebhook Notification channel with webhook type. +type NotificationChannelWebhook struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CustomHeaders Custom HTTP headers sent as part of the webhook request. + CustomHeaders *map[string]string `json:"customHeaders,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the channel is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Id Identifies the notification channel. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name User friendly name of the channel. + Name string `json:"name"` + + // SigningSecret Signing secret used for webhook request validation on the receiving end. + // + // Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + SigningSecret *string `json:"signingSecret,omitempty"` + + // Type Notification channel type. + Type NotificationChannelWebhookType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // Url Webhook URL where the notification is sent. + Url string `json:"url"` +} + +// NotificationChannelWebhookType Notification channel type. +type NotificationChannelWebhookType string + +// NotificationChannelWebhookCreateRequest Request with input parameters for creating new notification channel with webhook type. +type NotificationChannelWebhookCreateRequest struct { + // CustomHeaders Custom HTTP headers sent as part of the webhook request. + CustomHeaders *map[string]string `json:"customHeaders,omitempty"` + + // Disabled Whether the channel is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name User friendly name of the channel. + Name string `json:"name"` + + // SigningSecret Signing secret used for webhook request validation on the receiving end. + // + // Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + SigningSecret *string `json:"signingSecret,omitempty"` + + // Type Notification channel type. + Type NotificationChannelWebhookCreateRequestType `json:"type"` + + // Url Webhook URL where the notification is sent. + Url string `json:"url"` +} + +// NotificationChannelWebhookCreateRequestType Notification channel type. +type NotificationChannelWebhookCreateRequestType string + +// NotificationEvent Type of the notification event. +type NotificationEvent struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp when the notification event was created in RFC 3339 format. + CreatedAt time.Time `json:"createdAt"` + + // DeliveryStatus The delivery status of the notification event. + DeliveryStatus []NotificationEventDeliveryStatus `json:"deliveryStatus"` + + // Id A unique identifier of the notification event. + Id string `json:"id"` + + // Payload Timestamp when the notification event was created in RFC 3339 format. + Payload NotificationEventPayload `json:"payload"` + + // Rule The nnotification rule which generated this event. + Rule NotificationRule `json:"rule"` + + // Type Type of the notification event. + Type NotificationEventType `json:"type"` +} + +// NotificationEventBalanceThresholdPayload Payload for notification event with `entitlements.balance.threshold` type. +type NotificationEventBalanceThresholdPayload struct { + // Data The data of the payload. + Data NotificationEventBalanceThresholdPayloadData `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventBalanceThresholdPayloadType `json:"type"` +} + +// NotificationEventBalanceThresholdPayloadType Type of the notification event. +type NotificationEventBalanceThresholdPayloadType string + +// NotificationEventBalanceThresholdPayloadData Data of the payload for notification event with `entitlements.balance.threshold` type. +type NotificationEventBalanceThresholdPayloadData struct { + Customer *Customer `json:"customer,omitempty"` + Entitlement EntitlementMetered `json:"entitlement"` + Feature Feature `json:"feature"` + Subject Subject `json:"subject"` + Threshold NotificationRuleBalanceThresholdValue `json:"threshold"` + Value EntitlementValue `json:"value"` +} + +// NotificationEventDeliveryAttempt The delivery attempt of the notification event. +type NotificationEventDeliveryAttempt struct { + // Response Response returned by the notification event recipient. + Response EventDeliveryAttemptResponse `json:"response"` + + // State State of teh delivery attempt. + State NotificationEventDeliveryStatusState `json:"state"` + + // Timestamp Timestamp of the delivery attempt. + Timestamp time.Time `json:"timestamp"` +} + +// NotificationEventDeliveryStatus The delivery status of the notification event. +type NotificationEventDeliveryStatus struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Attempts List of delivery attempts. + Attempts []NotificationEventDeliveryAttempt `json:"attempts"` + + // Channel Notification channel the delivery status associated with. + Channel NotificationChannelMeta `json:"channel"` + + // NextAttempt Timestamp of the next delivery attempt. If null it means there will be no more delivery attempts. + NextAttempt *time.Time `json:"nextAttempt,omitempty"` + + // Reason The reason of the last deliverry state update. + Reason string `json:"reason"` + + // State Delivery state of the notification event to the channel. + State NotificationEventDeliveryStatusState `json:"state"` + + // UpdatedAt Timestamp of when the status was last updated in RFC 3339 format. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationEventDeliveryStatusState The delivery state of the notification event to the channel. +type NotificationEventDeliveryStatusState string + +// NotificationEventEntitlementValuePayloadBase Base data for any payload with entitlement entitlement value. +type NotificationEventEntitlementValuePayloadBase struct { + Customer *Customer `json:"customer,omitempty"` + Entitlement EntitlementMetered `json:"entitlement"` + Feature Feature `json:"feature"` + Subject Subject `json:"subject"` + Value EntitlementValue `json:"value"` +} + +// NotificationEventInvoiceCreatedPayload Payload for notification event with `invoice.created` type. +type NotificationEventInvoiceCreatedPayload struct { + // Data The data of the payload. + Data Invoice `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventInvoiceCreatedPayloadType `json:"type"` +} + +// NotificationEventInvoiceCreatedPayloadType Type of the notification event. +type NotificationEventInvoiceCreatedPayloadType string + +// NotificationEventInvoiceUpdatedPayload Payload for notification event with `invoice.updated` type. +type NotificationEventInvoiceUpdatedPayload struct { + // Data The data of the payload. + Data Invoice `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventInvoiceUpdatedPayloadType `json:"type"` +} + +// NotificationEventInvoiceUpdatedPayloadType Type of the notification event. +type NotificationEventInvoiceUpdatedPayloadType string + +// NotificationEventOrderBy Order by options for notification channels. +type NotificationEventOrderBy string + +// NotificationEventPaginatedResponse Paginated response +type NotificationEventPaginatedResponse struct { + // Items The items in the current page. + Items []NotificationEvent `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// NotificationEventPayload The delivery status of the notification event. +type NotificationEventPayload struct { + union json.RawMessage +} + +// NotificationEventResendRequest A notification event that will be re-sent. +type NotificationEventResendRequest struct { + // Channels Notification channels to which the event should be re-sent. + Channels *[]string `json:"channels,omitempty"` +} + +// NotificationEventResetPayload Payload for notification event with `entitlements.reset` type. +type NotificationEventResetPayload struct { + // Data The data of the payload. + Data NotificationEventEntitlementValuePayloadBase `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventResetPayloadType `json:"type"` +} + +// NotificationEventResetPayloadType Type of the notification event. +type NotificationEventResetPayloadType string + +// NotificationEventType Type of the notification event. +type NotificationEventType string + +// NotificationRule Notification Rule. +type NotificationRule struct { + union json.RawMessage +} + +// NotificationRuleBalanceThreshold Notification rule with entitlements.balance.threshold type. +type NotificationRuleBalanceThreshold struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field containing list of features the rule applies to. + Features *[]FeatureMeta `json:"features,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Thresholds List of thresholds the rule suppose to be triggered. + Thresholds []NotificationRuleBalanceThresholdValue `json:"thresholds"` + + // Type Notification rule type. + Type NotificationRuleBalanceThresholdType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleBalanceThresholdType Notification rule type. +type NotificationRuleBalanceThresholdType string + +// NotificationRuleBalanceThresholdCreateRequest Request with input parameters for creating new notification rule with entitlements.balance.threshold type. +type NotificationRuleBalanceThresholdCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field for defining the scope of notification by feature. It may contain features by id or key. + Features *[]string `json:"features,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Thresholds List of thresholds the rule suppose to be triggered. + Thresholds []NotificationRuleBalanceThresholdValue `json:"thresholds"` + + // Type Notification rule type. + Type NotificationRuleBalanceThresholdCreateRequestType `json:"type"` +} + +// NotificationRuleBalanceThresholdCreateRequestType Notification rule type. +type NotificationRuleBalanceThresholdCreateRequestType string + +// NotificationRuleBalanceThresholdValue Threshold value with multiple supported types. +type NotificationRuleBalanceThresholdValue struct { + // Type Type of the threshold. + Type NotificationRuleBalanceThresholdValueType `json:"type"` + + // Value Value of the threshold. + Value float64 `json:"value"` +} + +// NotificationRuleBalanceThresholdValueType Type of the rule in the balance threshold specification: +// * `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period +// * `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period +// * `usage_value`: threshold defined by the usage value in the current usage period +// * `NUMBER` (**deprecated**): see `usage_value` +// * `PERCENT` (**deprecated**): see `usage_percentage` +type NotificationRuleBalanceThresholdValueType string + +// NotificationRuleCreateRequest Union type for requests creating new notification rule with certain type. +type NotificationRuleCreateRequest struct { + union json.RawMessage +} + +// NotificationRuleEntitlementReset Notification rule with entitlements.reset type. +type NotificationRuleEntitlementReset struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field containing list of features the rule applies to. + Features *[]FeatureMeta `json:"features,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleEntitlementResetType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleEntitlementResetType Notification rule type. +type NotificationRuleEntitlementResetType string + +// NotificationRuleEntitlementResetCreateRequest Request with input parameters for creating new notification rule with entitlements.reset type. +type NotificationRuleEntitlementResetCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field for defining the scope of notification by feature. It may contain features by id or key. + Features *[]string `json:"features,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleEntitlementResetCreateRequestType `json:"type"` +} + +// NotificationRuleEntitlementResetCreateRequestType Notification rule type. +type NotificationRuleEntitlementResetCreateRequestType string + +// NotificationRuleInvoiceCreated Notification rule with invoice.created type. +type NotificationRuleInvoiceCreated struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceCreatedType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleInvoiceCreatedType Notification rule type. +type NotificationRuleInvoiceCreatedType string + +// NotificationRuleInvoiceCreatedCreateRequest Request with input parameters for creating new notification rule with invoice.created type. +type NotificationRuleInvoiceCreatedCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceCreatedCreateRequestType `json:"type"` +} + +// NotificationRuleInvoiceCreatedCreateRequestType Notification rule type. +type NotificationRuleInvoiceCreatedCreateRequestType string + +// NotificationRuleInvoiceUpdated Notification rule with invoice.updated type. +type NotificationRuleInvoiceUpdated struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceUpdatedType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleInvoiceUpdatedType Notification rule type. +type NotificationRuleInvoiceUpdatedType string + +// NotificationRuleInvoiceUpdatedCreateRequest Request with input parameters for creating new notification rule with invoice.updated type. +type NotificationRuleInvoiceUpdatedCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceUpdatedCreateRequestType `json:"type"` +} + +// NotificationRuleInvoiceUpdatedCreateRequestType Notification rule type. +type NotificationRuleInvoiceUpdatedCreateRequestType string + +// NotificationRuleMeta Metadata only fields of a notification channel. +type NotificationRuleMeta struct { + // Id Identifies the notification rule. + Id string `json:"id"` + + // Type Notification rule type. + Type NotificationEventType `json:"type"` +} + +// NotificationRuleOrderBy Order by options for notification channels. +type NotificationRuleOrderBy string + +// NotificationRulePaginatedResponse Paginated response +type NotificationRulePaginatedResponse struct { + // Items The items in the current page. + Items []NotificationRule `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// Numeric Numeric represents an arbitrary precision number. +type Numeric = string + +// OAuth2AuthorizationCodeGrantErrorType OAuth2 authorization code grant error types. +type OAuth2AuthorizationCodeGrantErrorType string + +// PackagePrice Package price. +// +// The item is sold in packages. Each package contains quantityPerPackage items, the price of the +// package is set in amount. +// +// The total price of the usage will be enough packages that can accomodate all the usage. +// +// Examples (given a package size of 20, and an amount of $10): +// - if the quantity is 98, the price will be 5*$10=$50. +// - if the quantity is zero, the price will be 0*$10=$0, as even the first package is not purchased. +// - if the quantity is 20, the price will be 1*$10=$10, as the usage fits into the first package. +// - if the quantity is 20.1, the price will be 2*$10=$20, as the additional 0.1 usage (compared to the +// previous example) requires a new package. +type PackagePrice struct { + // Amount The price of one package. + Amount Numeric `json:"amount"` + + // QuantityPerPackage The quantity per package. + QuantityPerPackage Numeric `json:"quantityPerPackage"` + + // Type The type of the price. + Type PackagePriceType `json:"type"` +} + +// PackagePriceType The type of the price. +type PackagePriceType string + +// PackagePriceWithCommitments Package price with spend commitments. +type PackagePriceWithCommitments struct { + // Amount The price of one package. + Amount Numeric `json:"amount"` + + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // QuantityPerPackage The quantity per package. + QuantityPerPackage Numeric `json:"quantityPerPackage"` + + // Type The type of the price. + Type PackagePriceWithCommitmentsType `json:"type"` +} + +// PackagePriceWithCommitmentsType The type of the price. +type PackagePriceWithCommitmentsType string + +// PaymentDueDate PaymentDueDate contains an amount that should be paid by the given date. +type PaymentDueDate struct { + // Amount How much needs to be paid by the date. + Amount Numeric `json:"amount"` + + // Currency If different from the parent document's base currency. + Currency *CurrencyCode `json:"currency,omitempty"` + + // DueAt When the payment is due. + DueAt time.Time `json:"dueAt"` + + // Notes Other details to take into account for the due date. + Notes *string `json:"notes,omitempty"` + + // Percent Percentage of the total that should be paid by the date. + Percent *Percentage `json:"percent,omitempty"` +} + +// PaymentTermDueDate PaymentTermDueDate defines the terms for payment on a specific date. +type PaymentTermDueDate struct { + // Detail Text detail of the chosen payment terms. + Detail *string `json:"detail,omitempty"` + + // DueAt When the payment is due. + DueAt []PaymentDueDate `json:"dueAt"` + + // Notes Description of the conditions for payment. + Notes *string `json:"notes,omitempty"` + + // Type Type of terms to be applied. + Type PaymentTermDueDateType `json:"type"` +} + +// PaymentTermDueDateType Type of terms to be applied. +type PaymentTermDueDateType string + +// PaymentTermInstant PaymentTermInstant defines the terms for payment on receipt of invoice. +type PaymentTermInstant struct { + // Detail Text detail of the chosen payment terms. + Detail *string `json:"detail,omitempty"` + + // Notes Description of the conditions for payment. + Notes *string `json:"notes,omitempty"` + + // Type Type of terms to be applied. + Type PaymentTermInstantType `json:"type"` +} + +// PaymentTermInstantType Type of terms to be applied. +type PaymentTermInstantType string + +// PaymentTermType PaymentTermType defines the type of terms to be applied. +type PaymentTermType string + +// PaymentTerms PaymentTerms defines the terms for payment. +type PaymentTerms struct { + union json.RawMessage +} + +// Percentage Numeric representation of a percentage +// +// 50% is represented as 50 +type Percentage = models.Percentage + +// Period A period with a start and end time. +type Period struct { + // From Period start time. + From time.Time `json:"from"` + + // To Period end time. + To time.Time `json:"to"` +} + +// Plan Plans provide a template for subscriptions. +type Plan struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the plan. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EffectiveFrom The date and time when the plan becomes effective. When not specified, the plan is a draft. + EffectiveFrom *time.Time `json:"effectiveFrom,omitempty"` + + // EffectiveTo The date and time when the plan is no longer effective. When not specified, the plan is effective indefinitely. + EffectiveTo *time.Time `json:"effectiveTo,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` + + // Status The status of the plan. + // Computed based on the effective start and end dates: + // - draft = no effectiveFrom + // - active = effectiveFrom <= now < effectiveTo + // - archived / inactive = effectiveTo <= now + // - scheduled = now < effectiveFrom < effectiveTo + Status PlanStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationErrors List of validation errors. + ValidationErrors *[]ValidationError `json:"validationErrors"` + + // Version Version of the plan. Incremented when the plan is updated. + Version int `json:"version"` +} + +// PlanAddon The PlanAddon describes the association between a plan and add-on. +type PlanAddon struct { + // Addon Add-on object. + Addon Addon `json:"addon"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FromPlanPhase The key of the plan phase from the add-on becomes available for purchase. + FromPlanPhase string `json:"fromPlanPhase"` + + // MaxQuantity The maximum number of times the add-on can be purchased for the plan. + // It is not applicable for add-ons with single instance type. + MaxQuantity *int `json:"maxQuantity,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationErrors List of validation errors. + ValidationErrors *[]ValidationError `json:"validationErrors"` +} + +// PlanAddonCreate A plan add-on assignment create request. +type PlanAddonCreate struct { + // AddonId The add-on unique identifier in ULID format. + AddonId string `json:"addonId"` + + // FromPlanPhase The key of the plan phase from the add-on becomes available for purchase. + FromPlanPhase string `json:"fromPlanPhase"` + + // MaxQuantity The maximum number of times the add-on can be purchased for the plan. + // It is not applicable for add-ons with single instance type. + MaxQuantity *int `json:"maxQuantity,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` +} + +// PlanAddonOrderBy Order by options for plan add-on assignments. +type PlanAddonOrderBy string + +// PlanAddonPaginatedResponse Paginated response +type PlanAddonPaginatedResponse struct { + // Items The items in the current page. + Items []PlanAddon `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// PlanAddonReplaceUpdate Resource update operation model. +type PlanAddonReplaceUpdate struct { + // FromPlanPhase The key of the plan phase from the add-on becomes available for purchase. + FromPlanPhase string `json:"fromPlanPhase"` + + // MaxQuantity The maximum number of times the add-on can be purchased for the plan. + // It is not applicable for add-ons with single instance type. + MaxQuantity *int `json:"maxQuantity,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` +} + +// PlanCreate Resource create operation model. +type PlanCreate struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // Currency The currency code of the plan. + Currency CurrencyCode `json:"currency"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` +} + +// PlanOrderBy Order by options for plans. +type PlanOrderBy string + +// PlanPaginatedResponse Paginated response +type PlanPaginatedResponse struct { + // Items The items in the current page. + Items []Plan `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// PlanPhase The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. +type PlanPhase struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Duration The duration of the phase. + Duration *string `json:"duration"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the plan. + RateCards []RateCard `json:"rateCards"` +} + +// PlanReference References an exact plan. +type PlanReference struct { + // Id The plan ID. + Id string `json:"id"` + + // Key The plan key. + Key string `json:"key"` + + // Version The plan version. + Version int `json:"version"` +} + +// PlanReferenceInput References an exact plan defaulting to the current active version. +type PlanReferenceInput struct { + // Key The plan key. + Key string `json:"key"` + + // Version The plan version. + Version *int `json:"version,omitempty"` +} + +// PlanReplaceUpdate Resource update operation model. +type PlanReplaceUpdate struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` +} + +// PlanStatus The status of a plan. +type PlanStatus string + +// PlanSubscriptionChange Change subscription based on plan. +type PlanSubscriptionChange struct { + // Alignment What alignment settings the subscription should have. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // Description Description for the Subscription. + Description *string `json:"description,omitempty"` + + // Metadata Arbitrary metadata associated with the subscription. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The name of the Subscription. If not provided the plan name is used. + Name *string `json:"name,omitempty"` + + // Plan The plan reference to change to. + Plan PlanReferenceInput `json:"plan"` + + // SettlementMode The settlement mode of the subscription. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` + + // StartingPhase The key of the phase to start the subscription in. + // If not provided, the subscription will start in the first phase of the plan. + StartingPhase *string `json:"startingPhase,omitempty"` + + // Timing Timing configuration for the change, when the change should take effect. + // For changing a subscription, the accepted values depend on the subscription configuration. + Timing SubscriptionTiming `json:"timing"` +} + +// PlanSubscriptionCreate Create subscription based on plan. +type PlanSubscriptionCreate struct { + // Alignment What alignment settings the subscription should have. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // CustomerId The ID of the customer. Provide either the key or ID. Has presedence over the key. + CustomerId *string `json:"customerId,omitempty"` + + // CustomerKey The key of the customer. Provide either the key or ID. + CustomerKey *string `json:"customerKey,omitempty"` + + // Description Description for the Subscription. + Description *string `json:"description,omitempty"` + + // Metadata Arbitrary metadata associated with the subscription. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The name of the Subscription. If not provided the plan name is used. + Name *string `json:"name,omitempty"` + + // Plan The plan reference to change to. + Plan PlanReferenceInput `json:"plan"` + + // SettlementMode The settlement mode of the subscription. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` + + // StartingPhase The key of the phase to start the subscription in. + // If not provided, the subscription will start in the first phase of the plan. + StartingPhase *string `json:"startingPhase,omitempty"` + + // Timing Timing configuration for the change, when the change should take effect. + // The default is immediate. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// PortalToken A consumer portal token. +// +// Validator doesn't obey required for readOnly properties +// See: https://github.com/stoplightio/spectral/issues/1274 +type PortalToken struct { + // AllowedMeterSlugs Optional, if defined only the specified meters will be allowed. + AllowedMeterSlugs *[]string `json:"allowedMeterSlugs,omitempty"` + + // CreatedAt [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + CreatedAt *time.Time `json:"createdAt,omitempty"` + Expired *bool `json:"expired,omitempty"` + + // ExpiresAt [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Id ULID (Universally Unique Lexicographically Sortable Identifier). + Id *string `json:"id,omitempty"` + Subject string `json:"subject"` + + // Token The token is only returned at creation. + Token *string `json:"token,omitempty"` +} + +// PreconditionFailedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type PreconditionFailedProblemResponse = UnexpectedProblemResponse + +// Price Price. +// One of: flat, unit, or tiered. +type Price struct { + union json.RawMessage +} + +// PricePaymentTerm The payment term of a flat price. +// One of: in_advance or in_arrears. +type PricePaymentTerm string + +// PriceTier A price tier. +// At least one price component is required in each tier. +type PriceTier struct { + // FlatPrice The flat price component of the tier. + FlatPrice *FlatPrice `json:"flatPrice"` + + // UnitPrice The unit price component of the tier. + UnitPrice *UnitPrice `json:"unitPrice"` + + // UpToAmount Up to and including to this quantity will be contained in the tier. + // If null, the tier is open-ended. + UpToAmount *Numeric `json:"upToAmount,omitempty"` +} + +// PriceType The type of the price. +type PriceType string + +// ProRatingConfig Configuration for pro-rating behavior. +type ProRatingConfig struct { + // Enabled Whether pro-rating is enabled for this plan. + Enabled bool `json:"enabled"` + + // Mode How to handle pro-rating for billing period changes. + Mode ProRatingMode `json:"mode"` +} + +// ProRatingMode Pro-rating mode options for handling billing period changes. +type ProRatingMode string + +// Progress Progress describes a progress of a task. +type Progress struct { + // Failed Failed is the number of items that failed + Failed uint64 `json:"failed"` + + // Success Success is the number of items that succeeded + Success uint64 `json:"success"` + + // Total The total number of items to process + Total uint64 `json:"total"` + + // UpdatedAt The time the progress was last updated + UpdatedAt time.Time `json:"updatedAt"` +} + +// RateCard A rate card defines the pricing and entitlement of a feature or service. +type RateCard struct { + union json.RawMessage +} + +// RateCardBooleanEntitlement Entitlement template of a boolean entitlement. +type RateCardBooleanEntitlement struct { + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type RateCardBooleanEntitlementType `json:"type"` +} + +// RateCardBooleanEntitlementType defines model for RateCardBooleanEntitlement.Type. +type RateCardBooleanEntitlementType string + +// RateCardEntitlement Entitlement templates are used to define the entitlements of a plan. +// Features are omitted from the entitlement template, as they are defined in the rate card. +type RateCardEntitlement struct { + union json.RawMessage +} + +// RateCardFlatFee A flat fee rate card defines a one-time purchase or a recurring fee. +type RateCardFlatFee struct { + // BillingCadence The billing cadence of the rate card. + // When null it means it is a one time fee. + BillingCadence *string `json:"billingCadence"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discount of the rate card. For flat fee rate cards only percentage discounts are supported. + // Only available when price is set. + Discounts *Discounts `json:"discounts,omitempty"` + + // EntitlementTemplate The entitlement of the rate card. + // Only available when featureKey is set. + EntitlementTemplate *RateCardEntitlement `json:"entitlementTemplate,omitempty"` + + // FeatureKey The feature the customer is entitled to use. + FeatureKey *string `json:"featureKey,omitempty"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *FlatPriceWithPaymentTerm `json:"price"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Type The type of the RateCard. + Type RateCardFlatFeeType `json:"type"` +} + +// RateCardFlatFeeType The type of the RateCard. +type RateCardFlatFeeType string + +// RateCardMeteredEntitlement The entitlement template with a metered entitlement. +type RateCardMeteredEntitlement struct { + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type RateCardMeteredEntitlementType `json:"type"` + + // UsagePeriod The interval of the metered entitlement. + // Defaults to the billing cadence of the rate card. + UsagePeriod *string `json:"usagePeriod,omitempty"` +} + +// RateCardMeteredEntitlementType defines model for RateCardMeteredEntitlement.Type. +type RateCardMeteredEntitlementType string + +// RateCardStaticEntitlement Entitlement template of a static entitlement. +type RateCardStaticEntitlement struct { + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type RateCardStaticEntitlementType `json:"type"` +} + +// RateCardStaticEntitlementType defines model for RateCardStaticEntitlement.Type. +type RateCardStaticEntitlementType string + +// RateCardType The type of the rate card. +type RateCardType string + +// RateCardUsageBased A usage-based rate card defines a price based on usage. +type RateCardUsageBased struct { + // BillingCadence The billing cadence of the rate card. + BillingCadence string `json:"billingCadence"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts of the rate card. + // + // Flat fee rate cards only support percentage discounts. + Discounts *Discounts `json:"discounts,omitempty"` + + // EntitlementTemplate The entitlement of the rate card. + // Only available when featureKey is set. + EntitlementTemplate *RateCardEntitlement `json:"entitlementTemplate,omitempty"` + + // FeatureKey The feature the customer is entitled to use. + FeatureKey *string `json:"featureKey,omitempty"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *RateCardUsageBasedPrice `json:"price"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Type The type of the RateCard. + Type RateCardUsageBasedType `json:"type"` +} + +// RateCardUsageBasedType The type of the RateCard. +type RateCardUsageBasedType string + +// RateCardUsageBasedPrice The price of the usage based rate card. +type RateCardUsageBasedPrice struct { + union json.RawMessage +} + +// RecurringPeriod Recurring period with an interval and an anchor. +type RecurringPeriod struct { + // Anchor A date-time anchor to base the recurring period on. + Anchor time.Time `json:"anchor"` + + // Interval The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + Interval RecurringPeriodInterval `json:"interval"` + + // IntervalISO The unit of time for the interval in ISO8601 format. + IntervalISO string `json:"intervalISO"` +} + +// RecurringPeriodCreateInput Recurring period with an interval and an anchor. +type RecurringPeriodCreateInput struct { + // Anchor A date-time anchor to base the recurring period on. + Anchor *time.Time `json:"anchor,omitempty"` + + // Interval The unit of time for the interval. + Interval RecurringPeriodInterval `json:"interval"` +} + +// RecurringPeriodInterval Period duration for the recurrence +type RecurringPeriodInterval struct { + union json.RawMessage +} + +// RecurringPeriodInterval0 defines model for . +type RecurringPeriodInterval0 = string + +// RecurringPeriodIntervalEnum The unit of time for the interval. +// One of: `day`, `week`, `month`, or `year`. +type RecurringPeriodIntervalEnum string + +// RecurringPeriodV2 Recurring period with an interval and an anchor. +type RecurringPeriodV2 struct { + // Anchor A date-time anchor to base the recurring period on. + Anchor time.Time `json:"anchor"` + + // Interval The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + Interval RecurringPeriodInterval `json:"interval"` +} + +// RemovePhaseShifting The direction of the phase shift when a phase is removed. +type RemovePhaseShifting string + +// ResetEntitlementUsageInput Reset parameters +type ResetEntitlementUsageInput struct { + // EffectiveAt The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored. + EffectiveAt *time.Time `json:"effectiveAt,omitempty"` + + // PreserveOverage Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior. + // - If true, the overage is preserved. + // - If false, the overage is forgiven. + PreserveOverage *bool `json:"preserveOverage,omitempty"` + + // RetainAnchor Determines whether the usage period anchor is retained or reset to the effectiveAt time. + // - If true, the usage period anchor is retained. + // - If false, the usage period anchor is reset to the effectiveAt time. + RetainAnchor *bool `json:"retainAnchor,omitempty"` +} + +// SandboxApp Sandbox app can be used for testing OpenMeter features. +// +// The app is not creating anything in external systems, thus it is safe to use for +// verifying OpenMeter features. +type SandboxApp struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // Type The app's type is Sandbox. + Type SandboxAppType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SandboxAppType The app's type is Sandbox. +type SandboxAppType string + +// SandboxAppReplaceUpdate Resource update operation model. +type SandboxAppReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Type The app's type is Sandbox. + Type SandboxAppReplaceUpdateType `json:"type"` +} + +// SandboxAppReplaceUpdateType The app's type is Sandbox. +type SandboxAppReplaceUpdateType string + +// SandboxCustomerAppData Sandbox Customer App Data. +type SandboxCustomerAppData struct { + // App The installed sandbox app this data belongs to. + App *SandboxApp `json:"app,omitempty"` + + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // Type The app name. + Type SandboxCustomerAppDataType `json:"type"` +} + +// SandboxCustomerAppDataType The app name. +type SandboxCustomerAppDataType string + +// ServiceUnavailableProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type ServiceUnavailableProblemResponse = UnexpectedProblemResponse + +// SortOrder The order direction. +type SortOrder string + +// SpendCommitments Spending commitments. +// The customer is committed to spend at least the minimum amount and at most the maximum amount. +type SpendCommitments struct { + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` +} + +// StripeAPIKeyInput The Stripe API key input. +// Used to authenticate with the Stripe API. +type StripeAPIKeyInput struct { + SecretAPIKey string `json:"secretAPIKey"` +} + +// StripeApp A installed Stripe app object. +type StripeApp struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Livemode Livemode, true if the app is in production mode. + Livemode bool `json:"livemode"` + + // MaskedAPIKey The masked API key. + // Only shows the first 8 and last 3 characters. + MaskedAPIKey string `json:"maskedAPIKey"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // StripeAccountId The Stripe account ID. + StripeAccountId string `json:"stripeAccountId"` + + // Type The app's type is Stripe. + Type StripeAppType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// StripeAppType The app's type is Stripe. +type StripeAppType string + +// StripeAppReadOrCreateOrUpdateOrDeleteOrQuery A installed Stripe app object. +type StripeAppReadOrCreateOrUpdateOrDeleteOrQuery struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Livemode Livemode, true if the app is in production mode. + Livemode bool `json:"livemode"` + + // MaskedAPIKey The masked API key. + // Only shows the first 8 and last 3 characters. + MaskedAPIKey string `json:"maskedAPIKey"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // SecretAPIKey The Stripe API key. + SecretAPIKey *string `json:"secretAPIKey,omitempty"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // StripeAccountId The Stripe account ID. + StripeAccountId string `json:"stripeAccountId"` + + // Type The app's type is Stripe. + Type StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType The app's type is Stripe. +type StripeAppReadOrCreateOrUpdateOrDeleteOrQueryType string + +// StripeAppReplaceUpdate Resource update operation model. +type StripeAppReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // SecretAPIKey The Stripe API key. + SecretAPIKey *string `json:"secretAPIKey,omitempty"` + + // Type The app's type is Stripe. + Type StripeAppReplaceUpdateType `json:"type"` +} + +// StripeAppReplaceUpdateType The app's type is Stripe. +type StripeAppReplaceUpdateType string + +// StripeCheckoutSessionMode Stripe CheckoutSession.mode +type StripeCheckoutSessionMode string + +// StripeCustomerAppData Stripe Customer App Data. +type StripeCustomerAppData struct { + // App The installed stripe app this data belongs to. + App *StripeApp `json:"app,omitempty"` + + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // StripeDefaultPaymentMethodId The Stripe default payment method ID. + StripeDefaultPaymentMethodId *string `json:"stripeDefaultPaymentMethodId,omitempty"` + + // Type The app name. + Type StripeCustomerAppDataType `json:"type"` +} + +// StripeCustomerAppDataType The app name. +type StripeCustomerAppDataType string + +// StripeCustomerAppDataBase Stripe Customer App Data Base. +type StripeCustomerAppDataBase struct { + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // StripeDefaultPaymentMethodId The Stripe default payment method ID. + StripeDefaultPaymentMethodId *string `json:"stripeDefaultPaymentMethodId,omitempty"` +} + +// StripeCustomerAppDataCreateOrUpdateItem Stripe Customer App Data. +type StripeCustomerAppDataCreateOrUpdateItem struct { + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // StripeDefaultPaymentMethodId The Stripe default payment method ID. + StripeDefaultPaymentMethodId *string `json:"stripeDefaultPaymentMethodId,omitempty"` + + // Type The app name. + Type StripeCustomerAppDataCreateOrUpdateItemType `json:"type"` +} + +// StripeCustomerAppDataCreateOrUpdateItemType The app name. +type StripeCustomerAppDataCreateOrUpdateItemType string + +// StripeCustomerPortalSession Stripe customer portal session. +// +// See: https://docs.stripe.com/api/customer_portal/sessions/object +type StripeCustomerPortalSession struct { + // ConfigurationId Configuration used to customize the customer portal. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + ConfigurationId string `json:"configurationId"` + + // CreatedAt Created at. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + CreatedAt time.Time `json:"createdAt"` + + // Id The ID of the customer portal session. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + Id string `json:"id"` + + // Livemode Livemode. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + Livemode bool `json:"livemode"` + + // Locale Status. + // /** + // The IETF language tag of the locale customer portal is displayed in. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + Locale string `json:"locale"` + + // ReturnUrl Return URL. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + ReturnUrl string `json:"returnUrl"` + + // StripeCustomerId The ID of the stripe customer. + StripeCustomerId string `json:"stripeCustomerId"` + + // Url /** + // The ID of the customer.The URL to redirect the customer to after they have completed + // their requested actions. + Url string `json:"url"` +} + +// StripeTaxConfig The tax config for Stripe. +type StripeTaxConfig struct { + // Code Product tax code. + // + // See: https://docs.stripe.com/tax/tax-codes + Code string `json:"code"` +} + +// StripeWebhookEvent Stripe webhook event. +type StripeWebhookEvent struct { + // Created The event created timestamp. + Created int32 `json:"created"` + + // Data The event data. + Data struct { + Object interface{} `json:"object"` + } `json:"data"` + + // Id The event ID. + Id string `json:"id"` + + // Livemode Live mode. + Livemode bool `json:"livemode"` + + // Type The event type. + Type string `json:"type"` +} + +// StripeWebhookResponse Stripe webhook response. +type StripeWebhookResponse struct { + // AppId ULID (Universally Unique Lexicographically Sortable Identifier). + AppId string `json:"appId"` + + // CustomerId ULID (Universally Unique Lexicographically Sortable Identifier). + CustomerId *string `json:"customerId,omitempty"` + Message *string `json:"message,omitempty"` + + // NamespaceId ULID (Universally Unique Lexicographically Sortable Identifier). + NamespaceId string `json:"namespaceId"` +} + +// Subject A subject is a unique identifier for a usage attribution by its key. +// Subjects only exist in the concept of metering. +// Subjects are optional to create and work as an enrichment for the subject key like displayName, metadata, etc. +// Subjects are useful when you are reporting usage events with your own database ID but want to enrich the subject with a human-readable name or metadata. +// For most use cases, a subject is equivalent to a customer. +// +// ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. +type Subject struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentPeriodEnd The end of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"` + + // CurrentPeriodStart The start of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodStart *time.Time `json:"currentPeriodStart,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // DisplayName A human-readable display name for the subject. + DisplayName *string `json:"displayName,omitempty"` + + // Id A unique identifier for the subject. + Id string `json:"id"` + + // Key A unique, human-readable identifier for the subject. + // This is typically a database ID or a customer key. + Key string `json:"key"` + + // Metadata Metadata for the subject. + Metadata *map[string]interface{} `json:"metadata,omitempty"` + + // StripeCustomerId The Stripe customer ID for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + StripeCustomerId *string `json:"stripeCustomerId,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubjectUpsert A subject is a unique identifier for a user or entity. +// +// ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. +type SubjectUpsert struct { + // CurrentPeriodEnd The end of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"` + + // CurrentPeriodStart The start of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodStart *time.Time `json:"currentPeriodStart,omitempty"` + + // DisplayName A human-readable display name for the subject. + DisplayName *string `json:"displayName,omitempty"` + + // Key A unique, human-readable identifier for the subject. + // This is typically a database ID or a customer key. + Key string `json:"key"` + + // Metadata Metadata for the subject. + Metadata *map[string]interface{} `json:"metadata,omitempty"` + + // StripeCustomerId The Stripe customer ID for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + StripeCustomerId *string `json:"stripeCustomerId,omitempty"` +} + +// Subscription Subscription is an exact subscription instance. +type Subscription struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // BillingAnchor The normalizedbilling anchor of the subscription. + BillingAnchor time.Time `json:"billingAnchor"` + + // BillingCadence The billing cadence for the subscriptions. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the subscription. + // Will be revised once we add multi currency support. + Currency CurrencyCode `json:"currency"` + + // CustomerId The customer ID of the subscription. + CustomerId string `json:"customerId"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Plan The plan of the subscription. + Plan *PlanReference `json:"plan,omitempty"` + + // ProRatingConfig The pro-rating configuration for the subscriptions. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the subscription. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode BillingSettlementMode `json:"settlementMode"` + + // Status The status of the subscription. + Status SubscriptionStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionAddon A subscription add-on, represents concrete instances of an add-on for a given subscription. +type SubscriptionAddon struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Addon Partially populated add-on properties. + Addon struct { + // Id The ID of the add-on. + Id string `json:"id"` + + // InstanceType The instance type of the add-on. + InstanceType AddonInstanceType `json:"instanceType"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Version The version of the Add-on which templates this instance. + Version int `json:"version"` + } `json:"addon"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Quantity The quantity of the add-on. Always 1 for single instance add-ons. + Quantity int `json:"quantity"` + + // QuantityAt For which point in time the quantity was resolved to. + QuantityAt time.Time `json:"quantityAt"` + + // RateCards The rate cards of the add-on. + RateCards []SubscriptionAddonRateCard `json:"rateCards"` + + // SubscriptionId The ID of the subscription. + SubscriptionId string `json:"subscriptionId"` + + // Timeline The timeline of the add-on. The returned periods are sorted and continuous. + Timeline []SubscriptionAddonTimelineSegment `json:"timeline"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionAddonCreate A subscription add-on create body. +type SubscriptionAddonCreate struct { + // Addon The add-on to create. + Addon struct { + // Id The ID of the add-on. + Id string `json:"id"` + } `json:"addon"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Quantity The quantity of the add-on. Always 1 for single instance add-ons. + Quantity int `json:"quantity"` + + // Timing The timing of the operation. After the create or update, a new entry will be created in the timeline. + Timing SubscriptionTiming `json:"timing"` +} + +// SubscriptionAddonRateCard A rate card for a subscription add-on. +type SubscriptionAddonRateCard struct { + // AffectedSubscriptionItemIds The IDs of the subscription items that this rate card belongs to. + AffectedSubscriptionItemIds []string `json:"affectedSubscriptionItemIds"` + + // RateCard The rate card. + RateCard RateCard `json:"rateCard"` +} + +// SubscriptionAddonTimelineSegment A subscription add-on event. +type SubscriptionAddonTimelineSegment struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Quantity The quantity of the add-on for the given period. + Quantity int `json:"quantity"` +} + +// SubscriptionAddonUpdate Resource create or update operation model. +type SubscriptionAddonUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name *string `json:"name,omitempty"` + + // Quantity The quantity of the add-on. Always 1 for single instance add-ons. + Quantity *int `json:"quantity,omitempty"` + + // Timing The timing of the operation. After the create or update, a new entry will be created in the timeline. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// SubscriptionAlignment Alignment details enriched with the current billing period. +type SubscriptionAlignment struct { + // BillablesMustAlign Whether all Billable items and RateCards must align. + // Alignment means the Price's BillingCadence must align for both duration and anchor time. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + BillablesMustAlign *bool `json:"billablesMustAlign,omitempty"` + + // CurrentAlignedBillingPeriod The current billing period. Only has value if the subscription is aligned and active. + CurrentAlignedBillingPeriod *Period `json:"currentAlignedBillingPeriod,omitempty"` +} + +// SubscriptionBadRequestErrorResponse The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. +type SubscriptionBadRequestErrorResponse struct { + // Detail A human-readable explanation specific to this occurrence of the problem. + Detail string `json:"detail"` + + // Extensions Additional properties specific to the problem type may be present. + Extensions *SubscriptionErrorExtensions `json:"extensions,omitempty"` + + // Instance A URI reference that identifies the specific occurrence of the problem. + Instance string `json:"instance"` + + // Status The HTTP status code generated by the origin server for this occurrence of the problem. + Status *int16 `json:"status,omitempty"` + + // Title A a short, human-readable summary of the problem type. + Title string `json:"title"` + + // Type Type contains a URI that identifies the problem type. + Type string `json:"type"` +} + +// SubscriptionChange Change a subscription. +type SubscriptionChange struct { + union json.RawMessage +} + +// SubscriptionChangeResponseBody Response body for subscription change. +type SubscriptionChangeResponseBody struct { + // Current The current subscription before the change. + Current Subscription `json:"current"` + + // Next The new state of the subscription after the change. + Next SubscriptionExpanded `json:"next"` +} + +// SubscriptionConflictErrorResponse The request could not be completed due to a conflict with the current state of the target resource. +// Variants with ErrorExtensions specific to subscriptions. +type SubscriptionConflictErrorResponse struct { + // Detail A human-readable explanation specific to this occurrence of the problem. + Detail string `json:"detail"` + + // Extensions Additional properties specific to the problem type may be present. + Extensions *SubscriptionErrorExtensions `json:"extensions,omitempty"` + + // Instance A URI reference that identifies the specific occurrence of the problem. + Instance string `json:"instance"` + + // Status The HTTP status code generated by the origin server for this occurrence of the problem. + Status *int16 `json:"status,omitempty"` + + // Title A a short, human-readable summary of the problem type. + Title string `json:"title"` + + // Type Type contains a URI that identifies the problem type. + Type string `json:"type"` +} + +// SubscriptionCreate Create a subscription. +type SubscriptionCreate struct { + union json.RawMessage +} + +// SubscriptionEdit Subscription edit input. +type SubscriptionEdit struct { + // Customizations Batch processing commands for manipulating running subscriptions. + // The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + Customizations []SubscriptionEditOperation `json:"customizations"` + + // Timing Whether the billing period should be restarted.Timing configuration to allow for the changes to take effect at different times. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// SubscriptionEditOperation The operation to be performed on the subscription. +type SubscriptionEditOperation struct { + union json.RawMessage +} + +// SubscriptionErrorExtensions Error extensions for the Subscription Errors. +type SubscriptionErrorExtensions struct { + ValidationErrors []ErrorExtension `json:"validationErrors"` +} + +// SubscriptionExpanded Expanded subscription +type SubscriptionExpanded struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Alignment Alignment details enriched with the current billing period. + Alignment *SubscriptionAlignment `json:"alignment,omitempty"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // BillingAnchor The normalizedbilling anchor of the subscription. + BillingAnchor time.Time `json:"billingAnchor"` + + // BillingCadence The billing cadence for the subscriptions. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the subscription. + // Will be revised once we add multi currency support. + Currency CurrencyCode `json:"currency"` + + // CustomerId The customer ID of the subscription. + CustomerId string `json:"customerId"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The phases of the subscription. + Phases []SubscriptionPhaseExpanded `json:"phases"` + + // Plan The plan of the subscription. + Plan *PlanReference `json:"plan,omitempty"` + + // ProRatingConfig The pro-rating configuration for the subscriptions. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the subscription. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode BillingSettlementMode `json:"settlementMode"` + + // Status The status of the subscription. + Status SubscriptionStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionItem The actual contents of the Subscription, what the user gets, what they pay, etc... +type SubscriptionItem struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // BillingCadence The billing cadence of the rate card. + // When null, the rate card is a one-time purchase. + BillingCadence *string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts applied to the rate card. + Discounts *Discounts `json:"discounts,omitempty"` + + // FeatureKey The feature's key (if present). + FeatureKey *string `json:"featureKey,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Included Describes what access is gained via the SubscriptionItem + Included *SubscriptionItemIncluded `json:"included,omitempty"` + + // Key The identifier of the RateCard. + // SubscriptionItem/RateCard can be identified, it has a reference: + // + // 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + // 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across versions) + // 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version of a Feature + // + // 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + // + // We say "referenced by the Price" regardless of how a price itself is referenced, it colloquially makes sense to say "paying the same price for the same thing". In practice this should be derived from what's printed on the invoice line-item. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *RateCardUsageBasedPrice `json:"price"` + + // TaxConfig The tax config of the Subscription Item. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionItemIncluded Included contents like Entitlement, or the Feature. +type SubscriptionItemIncluded struct { + // Entitlement The entitlement of the Subscription Item. + Entitlement *Entitlement `json:"entitlement,omitempty"` + + // Feature The feature the customer is entitled to use. + Feature Feature `json:"feature"` +} + +// SubscriptionPaginatedResponse Paginated response +type SubscriptionPaginatedResponse struct { + // Items The items in the current page. + Items []Subscription `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// SubscriptionPhase Subscription phase, analogous to plan phases. +type SubscriptionPhase struct { + // ActiveFrom The time from which the phase is active. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The until which the Phase is active. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts on the plan. + Discounts *Discounts `json:"discounts,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Key A locally unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionPhaseCreate Subscription phase create input. +type SubscriptionPhaseCreate struct { + // Description The description of the phase. + Description *string `json:"description,omitempty"` + + // Discounts The discounts on the plan. + Discounts *Discounts `json:"discounts,omitempty"` + + // Duration The intended duration of the new phase. + // Duration is required when the phase will not be the last phase. + Duration *string `json:"duration,omitempty"` + + // Key A locally unique identifier for the phase. + Key string `json:"key"` + + // Name The name of the phase. + Name string `json:"name"` + + // StartAfter Interval after the subscription starts to transition to the phase. + // When null, the phase starts immediately after the subscription starts. + StartAfter *string `json:"startAfter"` +} + +// SubscriptionPhaseExpanded Expanded subscription phase +type SubscriptionPhaseExpanded struct { + // ActiveFrom The time from which the phase is active. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The until which the Phase is active. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts on the plan. + Discounts *Discounts `json:"discounts,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // ItemTimelines Includes all versions of the items on each key, including all edits, scheduled changes, etc... + ItemTimelines map[string][]SubscriptionItem `json:"itemTimelines"` + + // Items The items of the phase. The structure is flattened to better conform to the Plan API. + // The timelines are flattened according to the following rules: + // - for the current phase, the `items` contains only the active item for each key + // - for past phases, the `items` contains only the last item for each key + // - for future phases, the `items` contains only the first version of the item for each key + Items []SubscriptionItem `json:"items"` + + // Key A locally unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionStatus Subscription status. +type SubscriptionStatus string + +// SubscriptionTiming Subscription edit timing defined when the changes should take effect. +// If the provided configuration is not supported by the subscription, an error will be returned. +type SubscriptionTiming struct { + union json.RawMessage +} + +// SubscriptionTiming1 [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. +type SubscriptionTiming1 = time.Time + +// SubscriptionTimingEnum Subscription edit timing. +// When immediate, the requested changes take effect immediately. +// When nextBillingCycle, the requested changes take effect at the next billing cycle. +type SubscriptionTimingEnum string + +// TaxBehavior Tax behavior. +// +// This enum is used to specify whether tax is included in the price or excluded from the price. +type TaxBehavior string + +// TaxConfig Set of provider specific tax configs. +type TaxConfig struct { + // Behavior Tax behavior. + // + // If not specified the billing profile is used to determine the tax behavior. + // If not specified in the billing profile, the provider's default behavior is used. + Behavior *TaxBehavior `json:"behavior,omitempty"` + + // CustomInvoicing Custom invoicing tax config. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CustomInvoicing *CustomInvoicingTaxConfig `json:"customInvoicing,omitempty"` + + // Stripe Stripe tax config. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Stripe *StripeTaxConfig `json:"stripe,omitempty"` + + // TaxCodeId Tax code reference. + // + // When both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence: + // the referenced tax code entity is used and `stripe.code` is ignored. + TaxCodeId *string `json:"taxCodeId,omitempty"` +} + +// TieredPrice Tiered price. +type TieredPrice struct { + // Mode Defines if the tiering mode is volume-based or graduated: + // - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + // - In `graduated` tiering, pricing can change as the quantity grows. + Mode TieredPriceMode `json:"mode"` + + // Tiers The tiers of the tiered price. + // At least one price component is required in each tier. + Tiers []PriceTier `json:"tiers"` + + // Type The type of the price. + // + // One of: flat, unit, or tiered. + Type TieredPriceType `json:"type"` +} + +// TieredPriceType The type of the price. +// +// One of: flat, unit, or tiered. +type TieredPriceType string + +// TieredPriceMode The mode of the tiered price. +type TieredPriceMode string + +// TieredPriceWithCommitments Tiered price with spend commitments. +type TieredPriceWithCommitments struct { + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // Mode Defines if the tiering mode is volume-based or graduated: + // - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + // - In `graduated` tiering, pricing can change as the quantity grows. + Mode TieredPriceMode `json:"mode"` + + // Tiers The tiers of the tiered price. + // At least one price component is required in each tier. + Tiers []PriceTier `json:"tiers"` + + // Type The type of the price. + // + // One of: flat, unit, or tiered. + Type TieredPriceWithCommitmentsType `json:"type"` +} + +// TieredPriceWithCommitmentsType The type of the price. +// +// One of: flat, unit, or tiered. +type TieredPriceWithCommitmentsType string + +// ULIDOrExternalKey ULID (Universally Unique Lexicographically Sortable Identifier) or external unique key. +type ULIDOrExternalKey = string + +// UnauthorizedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type UnauthorizedProblemResponse = UnexpectedProblemResponse + +// UnexpectedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type UnexpectedProblemResponse = models.StatusProblem + +// UnitPrice Unit price. +type UnitPrice struct { + // Amount The amount of the unit price. + Amount Numeric `json:"amount"` + + // Type The type of the price. + Type UnitPriceType `json:"type"` +} + +// UnitPriceType The type of the price. +type UnitPriceType string + +// UnitPriceWithCommitments Unit price with spend commitments. +type UnitPriceWithCommitments struct { + // Amount The amount of the unit price. + Amount Numeric `json:"amount"` + + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // Type The type of the price. + Type UnitPriceWithCommitmentsType `json:"type"` +} + +// UnitPriceWithCommitmentsType The type of the price. +type UnitPriceWithCommitmentsType string + +// ValidationError Validation errors providing detailed description of the issue. +type ValidationError struct { + // Attributes Additional attributes. + Attributes *Annotations `json:"attributes,omitempty"` + + // Code The machine readable description of the error. + Code string `json:"code"` + + // Field The path to the field. + Field string `json:"field"` + + // Message The human readable description of the error. + Message string `json:"message"` +} + +// ValidationErrorProblemResponse A BadRequestError with a validationErrors extension. +type ValidationErrorProblemResponse struct { + // Detail A human-readable explanation specific to this occurrence of the problem. + Detail string `json:"detail"` + + // Extensions Validation issues. + Extensions *struct { + ValidationErrors *[]ValidationError `json:"validationErrors,omitempty"` + } `json:"extensions,omitempty"` + + // Instance A URI reference that identifies the specific occurrence of the problem. + Instance string `json:"instance"` + + // Status The HTTP status code generated by the origin server for this occurrence of the problem. + Status *int16 `json:"status,omitempty"` + + // Title A a short, human-readable summary of the problem type. + Title string `json:"title"` + + // Type Type contains a URI that identifies the problem type. + Type string `json:"type"` +} + +// ValidationIssue ValidationIssue captures any validation issues related to the invoice. +// +// Issues with severity "critical" will prevent the invoice from being issued. +type ValidationIssue struct { + // Code Machine indentifiable code for the issue, if available. + Code *string `json:"code,omitempty"` + + // Component Component reporting the issue. + Component string `json:"component"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Field The field that the issue is related to, if available in JSON path format. + Field *string `json:"field,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // Message A human-readable description of the issue. + Message string `json:"message"` + + // Metadata Additional context for the issue. + Metadata *Metadata `json:"metadata,omitempty"` + + // Severity The severity of the issue. + Severity ValidationIssueSeverity `json:"severity"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// ValidationIssueSeverity ValidationIssueSeverity describes the severity of a validation issue. +// +// Issues with severity "critical" will prevent the invoice from being issued. +type ValidationIssueSeverity string + +// VoidInvoiceActionCreate InvoiceVoidAction describes how to handle the voided line items. +type VoidInvoiceActionCreate struct { + // Action The action to take on the line items. + Action VoidInvoiceLineActionCreate `json:"action"` + + // Percentage How much of the total line items to be voided? (e.g. 100% means all charges are voided) + Percentage Percentage `json:"percentage"` +} + +// VoidInvoiceActionCreateItem InvoiceVoidAction describes how to handle the voided line items. +type VoidInvoiceActionCreateItem struct { + // Action The action to take on the line items. + Action VoidInvoiceLineActionCreateItem `json:"action"` + + // Percentage How much of the total line items to be voided? (e.g. 100% means all charges are voided) + Percentage Percentage `json:"percentage"` +} + +// VoidInvoiceActionInput Request to void an invoice +type VoidInvoiceActionInput struct { + // Action The action to take on the voided line items. + Action VoidInvoiceActionCreate `json:"action"` + + // Overrides Per line item overrides for the action. + // + // If not specified, the `action` will be applied to all line items. + Overrides *[]VoidInvoiceActionLineOverride `json:"overrides,omitempty"` + + // Reason The reason for voiding the invoice. + Reason string `json:"reason"` +} + +// VoidInvoiceActionLineOverride VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding. +type VoidInvoiceActionLineOverride struct { + // Action The action to take on the line item. + Action VoidInvoiceActionCreateItem `json:"action"` + + // LineId The line item ID to override. + LineId string `json:"lineId"` +} + +// VoidInvoiceLineActionCreate VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. +type VoidInvoiceLineActionCreate struct { + union json.RawMessage +} + +// VoidInvoiceLineActionCreateItem VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. +type VoidInvoiceLineActionCreateItem struct { + union json.RawMessage +} + +// VoidInvoiceLineActionType VoidInvoiceLineActionType describes how to handle the voidied line item in the invoice. +type VoidInvoiceLineActionType string + +// VoidInvoiceLineDiscardAction VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. +type VoidInvoiceLineDiscardAction struct { + // Type The action to take on the line item. + Type VoidInvoiceLineDiscardActionType `json:"type"` +} + +// VoidInvoiceLineDiscardActionType The action to take on the line item. +type VoidInvoiceLineDiscardActionType string + +// VoidInvoiceLinePendingActionCreate VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. +type VoidInvoiceLinePendingActionCreate struct { + // NextInvoiceAt The time at which the line item should be invoiced again. + // + // If not provided, the line item will be re-invoiced now. + NextInvoiceAt *time.Time `json:"nextInvoiceAt,omitempty"` + + // Type The action to take on the line item. + Type VoidInvoiceLinePendingActionCreateType `json:"type"` +} + +// VoidInvoiceLinePendingActionCreateType The action to take on the line item. +type VoidInvoiceLinePendingActionCreateType string + +// VoidInvoiceLinePendingActionCreateItem VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. +type VoidInvoiceLinePendingActionCreateItem struct { + // NextInvoiceAt The time at which the line item should be invoiced again. + // + // If not provided, the line item will be re-invoiced now. + NextInvoiceAt *time.Time `json:"nextInvoiceAt,omitempty"` + + // Type The action to take on the line item. + Type VoidInvoiceLinePendingActionCreateItemType `json:"type"` +} + +// VoidInvoiceLinePendingActionCreateItemType The action to take on the line item. +type VoidInvoiceLinePendingActionCreateItemType string + +// WindowSize Aggregation window size. +type WindowSize string + +// WindowedBalanceHistory The windowed balance history. +type WindowedBalanceHistory struct { + // BurndownHistory Grant burndown history. + BurndownHistory []GrantBurnDownHistorySegment `json:"burndownHistory"` + + // WindowedHistory The windowed balance history. + // - It only returns rows for windows where there was usage. + // - The windows are inclusive at their start and exclusive at their end. + // - The last window may be smaller than the window size and is inclusive at both ends. + WindowedHistory []BalanceHistoryWindow `json:"windowedHistory"` +} + +// AddonOrderByOrderingOrder The order direction. +type AddonOrderByOrderingOrder = SortOrder + +// AddonOrderByOrderingOrderBy Order by options for add-ons. +type AddonOrderByOrderingOrderBy = AddonOrderBy + +// BillingProfileCustomerOverrideOrderByOrderingOrder The order direction. +type BillingProfileCustomerOverrideOrderByOrderingOrder = SortOrder + +// BillingProfileCustomerOverrideOrderByOrderingOrderBy Order by options for customers. +type BillingProfileCustomerOverrideOrderByOrderingOrderBy = BillingProfileCustomerOverrideOrderBy + +// BillingProfileListCustomerOverridesParamsBillingProfile defines model for BillingProfileListCustomerOverridesParams.billingProfile. +type BillingProfileListCustomerOverridesParamsBillingProfile = []string + +// BillingProfileListCustomerOverridesParamsCustomerId defines model for BillingProfileListCustomerOverridesParams.customerId. +type BillingProfileListCustomerOverridesParamsCustomerId = []string + +// BillingProfileListCustomerOverridesParamsCustomerKey defines model for BillingProfileListCustomerOverridesParams.customerKey. +type BillingProfileListCustomerOverridesParamsCustomerKey = string + +// BillingProfileListCustomerOverridesParamsCustomerName defines model for BillingProfileListCustomerOverridesParams.customerName. +type BillingProfileListCustomerOverridesParamsCustomerName = string + +// BillingProfileListCustomerOverridesParamsCustomerPrimaryEmail defines model for BillingProfileListCustomerOverridesParams.customerPrimaryEmail. +type BillingProfileListCustomerOverridesParamsCustomerPrimaryEmail = string + +// BillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile defines model for BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile. +type BillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile = bool + +// BillingProfileListCustomerOverridesParamsExpand defines model for BillingProfileListCustomerOverridesParams.expand. +type BillingProfileListCustomerOverridesParamsExpand = []BillingProfileCustomerOverrideExpand + +// BillingProfileListCustomerOverridesParamsIncludeAllCustomers defines model for BillingProfileListCustomerOverridesParams.includeAllCustomers. +type BillingProfileListCustomerOverridesParamsIncludeAllCustomers = bool + +// BillingProfileOrderByOrderingOrder The order direction. +type BillingProfileOrderByOrderingOrder = SortOrder + +// BillingProfileOrderByOrderingOrderBy BillingProfileOrderBy specifies the ordering options for profiles +type BillingProfileOrderByOrderingOrderBy = BillingProfileOrderBy + +// CursorPaginationCursor defines model for CursorPagination.cursor. +type CursorPaginationCursor = string + +// CursorPaginationLimit defines model for CursorPagination.limit. +type CursorPaginationLimit = int + +// CustomerOrderByOrderingOrder The order direction. +type CustomerOrderByOrderingOrder = SortOrder + +// CustomerOrderByOrderingOrderBy Order by options for customers. +type CustomerOrderByOrderingOrderBy = CustomerOrderBy + +// CustomerSubscriptionOrderByOrderingOrder The order direction. +type CustomerSubscriptionOrderByOrderingOrder = SortOrder + +// CustomerSubscriptionOrderByOrderingOrderBy Order by options for customer subscriptions. +type CustomerSubscriptionOrderByOrderingOrderBy = CustomerSubscriptionOrderBy + +// EntitlementOrderByOrderingOrder The order direction. +type EntitlementOrderByOrderingOrder = SortOrder + +// EntitlementOrderByOrderingOrderBy Order by options for entitlements. +type EntitlementOrderByOrderingOrderBy = EntitlementOrderBy + +// FeatureOrderByOrderingOrder The order direction. +type FeatureOrderByOrderingOrder = SortOrder + +// FeatureOrderByOrderingOrderBy Order by options for features. +type FeatureOrderByOrderingOrderBy = FeatureOrderBy + +// GrantOrderByOrderingOrder The order direction. +type GrantOrderByOrderingOrder = SortOrder + +// GrantOrderByOrderingOrderBy Order by options for grants. +type GrantOrderByOrderingOrderBy = GrantOrderBy + +// InvoiceListParamsCreatedAfter defines model for InvoiceListParams.createdAfter. +type InvoiceListParamsCreatedAfter = time.Time + +// InvoiceListParamsCreatedBefore defines model for InvoiceListParams.createdBefore. +type InvoiceListParamsCreatedBefore = time.Time + +// InvoiceListParamsCustomers defines model for InvoiceListParams.customers. +type InvoiceListParamsCustomers = []string + +// InvoiceListParamsExpand defines model for InvoiceListParams.expand. +type InvoiceListParamsExpand = []InvoiceExpand + +// InvoiceListParamsExtendedStatuses defines model for InvoiceListParams.extendedStatuses. +type InvoiceListParamsExtendedStatuses = []string + +// InvoiceListParamsIncludeDeleted defines model for InvoiceListParams.includeDeleted. +type InvoiceListParamsIncludeDeleted = bool + +// InvoiceListParamsIssuedAfter defines model for InvoiceListParams.issuedAfter. +type InvoiceListParamsIssuedAfter = time.Time + +// InvoiceListParamsIssuedBefore defines model for InvoiceListParams.issuedBefore. +type InvoiceListParamsIssuedBefore = time.Time + +// InvoiceListParamsPeriodStartAfter defines model for InvoiceListParams.periodStartAfter. +type InvoiceListParamsPeriodStartAfter = time.Time + +// InvoiceListParamsPeriodStartBefore defines model for InvoiceListParams.periodStartBefore. +type InvoiceListParamsPeriodStartBefore = time.Time + +// InvoiceListParamsStatuses defines model for InvoiceListParams.statuses. +type InvoiceListParamsStatuses = []InvoiceStatus + +// InvoiceOrderByOrderingOrder The order direction. +type InvoiceOrderByOrderingOrder = SortOrder + +// InvoiceOrderByOrderingOrderBy InvoiceOrderBy specifies the ordering options for invoice listing. +type InvoiceOrderByOrderingOrderBy = InvoiceOrderBy + +// LimitOffsetLimit defines model for LimitOffset.limit. +type LimitOffsetLimit = int + +// LimitOffsetOffset defines model for LimitOffset.offset. +type LimitOffsetOffset = int + +// MarketplaceApiKeyInstallRequestType Type of the app. +type MarketplaceApiKeyInstallRequestType = AppType + +// MarketplaceInstallRequestType Type of the app. +type MarketplaceInstallRequestType = AppType + +// MarketplaceOAuth2InstallAuthorizeRequestType Type of the app. +type MarketplaceOAuth2InstallAuthorizeRequestType = AppType + +// MeterOrderByOrderingOrder The order direction. +type MeterOrderByOrderingOrder = SortOrder + +// MeterOrderByOrderingOrderBy Order by options for meters. +type MeterOrderByOrderingOrderBy = MeterOrderBy + +// MeterQueryAdvancedMeterGroupByFilters defines model for MeterQuery.advancedMeterGroupByFilters. +type MeterQueryAdvancedMeterGroupByFilters map[string]FilterString + +// MeterQueryClientId defines model for MeterQuery.clientId. +type MeterQueryClientId = string + +// MeterQueryFilterCustomerId defines model for MeterQuery.filterCustomerId. +type MeterQueryFilterCustomerId = []string + +// MeterQueryFilterGroupBy defines model for MeterQuery.filterGroupBy. +type MeterQueryFilterGroupBy map[string]string + +// MeterQueryFrom defines model for MeterQuery.from. +type MeterQueryFrom = time.Time + +// MeterQueryGroupBy defines model for MeterQuery.groupBy. +type MeterQueryGroupBy = []string + +// MeterQuerySubject defines model for MeterQuery.subject. +type MeterQuerySubject = []string + +// MeterQueryTo defines model for MeterQuery.to. +type MeterQueryTo = time.Time + +// MeterQueryWindowSize Aggregation window size. +type MeterQueryWindowSize = WindowSize + +// MeterQueryWindowTimeZone defines model for MeterQuery.windowTimeZone. +type MeterQueryWindowTimeZone = string + +// NotificationChannelOrderByOrderingOrder The order direction. +type NotificationChannelOrderByOrderingOrder = SortOrder + +// NotificationChannelOrderByOrderingOrderBy Order by options for notification channels. +type NotificationChannelOrderByOrderingOrderBy = NotificationChannelOrderBy + +// NotificationEventOrderByOrderingOrder The order direction. +type NotificationEventOrderByOrderingOrder = SortOrder + +// NotificationEventOrderByOrderingOrderBy Order by options for notification channels. +type NotificationEventOrderByOrderingOrderBy = NotificationEventOrderBy + +// NotificationRuleOrderByOrderingOrder The order direction. +type NotificationRuleOrderByOrderingOrder = SortOrder + +// NotificationRuleOrderByOrderingOrderBy Order by options for notification channels. +type NotificationRuleOrderByOrderingOrderBy = NotificationRuleOrderBy + +// OAuth2AuthorizationCodeGrantErrorParamsError OAuth2 authorization code grant error types. +type OAuth2AuthorizationCodeGrantErrorParamsError = OAuth2AuthorizationCodeGrantErrorType + +// OAuth2AuthorizationCodeGrantErrorParamsErrorDescription defines model for OAuth2AuthorizationCodeGrantErrorParams.error_description. +type OAuth2AuthorizationCodeGrantErrorParamsErrorDescription = string + +// OAuth2AuthorizationCodeGrantErrorParamsErrorUri defines model for OAuth2AuthorizationCodeGrantErrorParams.error_uri. +type OAuth2AuthorizationCodeGrantErrorParamsErrorUri = string + +// OAuth2AuthorizationCodeGrantSuccessParamsCode defines model for OAuth2AuthorizationCodeGrantSuccessParams.code. +type OAuth2AuthorizationCodeGrantSuccessParamsCode = string + +// OAuth2AuthorizationCodeGrantSuccessParamsState defines model for OAuth2AuthorizationCodeGrantSuccessParams.state. +type OAuth2AuthorizationCodeGrantSuccessParamsState = string + +// PaginationPage defines model for Pagination.page. +type PaginationPage = int + +// PaginationPageSize defines model for Pagination.pageSize. +type PaginationPageSize = int + +// PlanAddonOrderByOrderingOrder The order direction. +type PlanAddonOrderByOrderingOrder = SortOrder + +// PlanAddonOrderByOrderingOrderBy Order by options for plan add-on assignments. +type PlanAddonOrderByOrderingOrderBy = PlanAddonOrderBy + +// PlanOrderByOrderingOrder The order direction. +type PlanOrderByOrderingOrder = SortOrder + +// PlanOrderByOrderingOrderBy Order by options for plans. +type PlanOrderByOrderingOrderBy = PlanOrderBy + +// ListCustomerAppDataParamsType Type of the app. +type ListCustomerAppDataParamsType = AppType + +// QueryCustomerGet defines model for queryCustomerGet. +type QueryCustomerGet = []CustomerExpand + +// QueryCustomerListExpand defines model for queryCustomerList.expand. +type QueryCustomerListExpand = []CustomerExpand + +// QueryCustomerListIncludeDeleted defines model for queryCustomerList.includeDeleted. +type QueryCustomerListIncludeDeleted = bool + +// QueryCustomerListKey defines model for queryCustomerList.key. +type QueryCustomerListKey = string + +// QueryCustomerListName defines model for queryCustomerList.name. +type QueryCustomerListName = string + +// QueryCustomerListPlanKey defines model for queryCustomerList.planKey. +type QueryCustomerListPlanKey = string + +// QueryCustomerListPrimaryEmail defines model for queryCustomerList.primaryEmail. +type QueryCustomerListPrimaryEmail = string + +// QueryCustomerListSubject defines model for queryCustomerList.subject. +type QueryCustomerListSubject = string + +// QueryMeterListIncludeDeleted defines model for queryMeterList.includeDeleted. +type QueryMeterListIncludeDeleted = bool + +// portalTokenAuthContextKey is the context key for PortalTokenAuth security scheme +type portalTokenAuthContextKey string + +// ListAddonsParams defines parameters for ListAddons. +type ListAddonsParams struct { + // IncludeDeleted Include deleted add-ons in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Id Filter by addon.id attribute + Id *[]string `form:"id,omitempty" json:"id,omitempty"` + + // Key Filter by addon.key attribute + Key *[]string `form:"key,omitempty" json:"key,omitempty"` + + // KeyVersion Filter by addon.key and addon.version attributes + KeyVersion *map[string][]int `json:"keyVersion,omitempty"` + + // Status Only return add-ons with the given status. + // + // Usage: + // - `?status=active`: return only the currently active add-ons + // - `?status=draft`: return only the draft add-ons + // - `?status=archived`: return only the archived add-ons + Status *[]AddonStatus `form:"status,omitempty" json:"status,omitempty"` + + // Currency Filter by addon.currency attribute + Currency *[]CurrencyCode `form:"currency,omitempty" json:"currency,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *AddonOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *AddonOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetAddonParams defines parameters for GetAddon. +type GetAddonParams struct { + // IncludeLatest Include latest version of the add-on instead of the version in active state. + // + // Usage: `?includeLatest=true` + IncludeLatest *bool `form:"includeLatest,omitempty" json:"includeLatest,omitempty"` +} + +// ListAppsParams defines parameters for ListApps. +type ListAppsParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// ListBillingProfileCustomerOverridesParams defines parameters for ListBillingProfileCustomerOverrides. +type ListBillingProfileCustomerOverridesParams struct { + // BillingProfile Filter by billing profile. + BillingProfile *BillingProfileListCustomerOverridesParamsBillingProfile `form:"billingProfile,omitempty" json:"billingProfile,omitempty"` + + // CustomersWithoutPinnedProfile Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. + CustomersWithoutPinnedProfile *BillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile `form:"customersWithoutPinnedProfile,omitempty" json:"customersWithoutPinnedProfile,omitempty"` + + // IncludeAllCustomers Include customers without customer overrides. + // + // If set to false only the customers specifically associated with a billing profile will be returned. + // + // If set to true, in case of the default billing profile, all customers will be returned. + IncludeAllCustomers *BillingProfileListCustomerOverridesParamsIncludeAllCustomers `form:"includeAllCustomers,omitempty" json:"includeAllCustomers,omitempty"` + + // CustomerId Filter by customer id. + CustomerId *BillingProfileListCustomerOverridesParamsCustomerId `form:"customerId,omitempty" json:"customerId,omitempty"` + + // CustomerName Filter by customer name. + CustomerName *BillingProfileListCustomerOverridesParamsCustomerName `form:"customerName,omitempty" json:"customerName,omitempty"` + + // CustomerKey Filter by customer key + CustomerKey *BillingProfileListCustomerOverridesParamsCustomerKey `form:"customerKey,omitempty" json:"customerKey,omitempty"` + + // CustomerPrimaryEmail Filter by customer primary email + CustomerPrimaryEmail *BillingProfileListCustomerOverridesParamsCustomerPrimaryEmail `form:"customerPrimaryEmail,omitempty" json:"customerPrimaryEmail,omitempty"` + + // Expand Expand the response with additional details. + Expand *BillingProfileListCustomerOverridesParamsExpand `form:"expand,omitempty" json:"expand,omitempty"` + + // Order The order direction. + Order *BillingProfileCustomerOverrideOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *BillingProfileCustomerOverrideOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// GetBillingProfileCustomerOverrideParams defines parameters for GetBillingProfileCustomerOverride. +type GetBillingProfileCustomerOverrideParams struct { + Expand *[]BillingProfileCustomerOverrideExpand `form:"expand,omitempty" json:"expand,omitempty"` +} + +// ListInvoicesParams defines parameters for ListInvoices. +type ListInvoicesParams struct { + // Statuses Filter by the invoice status. + Statuses *InvoiceListParamsStatuses `form:"statuses,omitempty" json:"statuses,omitempty"` + + // ExtendedStatuses Filter by invoice extended statuses + ExtendedStatuses *InvoiceListParamsExtendedStatuses `form:"extendedStatuses,omitempty" json:"extendedStatuses,omitempty"` + + // IssuedAfter Filter by invoice issued time. + // Inclusive. + IssuedAfter *InvoiceListParamsIssuedAfter `form:"issuedAfter,omitempty" json:"issuedAfter,omitempty"` + + // IssuedBefore Filter by invoice issued time. + // Inclusive. + IssuedBefore *InvoiceListParamsIssuedBefore `form:"issuedBefore,omitempty" json:"issuedBefore,omitempty"` + + // PeriodStartAfter Filter by period start time. + // Inclusive. + PeriodStartAfter *InvoiceListParamsPeriodStartAfter `form:"periodStartAfter,omitempty" json:"periodStartAfter,omitempty"` + + // PeriodStartBefore Filter by period start time. + // Inclusive. + PeriodStartBefore *InvoiceListParamsPeriodStartBefore `form:"periodStartBefore,omitempty" json:"periodStartBefore,omitempty"` + + // CreatedAfter Filter by invoice created time. + // Inclusive. + CreatedAfter *InvoiceListParamsCreatedAfter `form:"createdAfter,omitempty" json:"createdAfter,omitempty"` + + // CreatedBefore Filter by invoice created time. + // Inclusive. + CreatedBefore *InvoiceListParamsCreatedBefore `form:"createdBefore,omitempty" json:"createdBefore,omitempty"` + + // Expand What parts of the list output to expand in listings + Expand *InvoiceListParamsExpand `form:"expand,omitempty" json:"expand,omitempty"` + + // Customers Filter by customer ID + Customers *InvoiceListParamsCustomers `form:"customers,omitempty" json:"customers,omitempty"` + + // IncludeDeleted Include deleted invoices + IncludeDeleted *InvoiceListParamsIncludeDeleted `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *InvoiceOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *InvoiceOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetInvoiceParams defines parameters for GetInvoice. +type GetInvoiceParams struct { + Expand *[]InvoiceExpand `form:"expand,omitempty" json:"expand,omitempty"` + IncludeDeletedLines *bool `form:"includeDeletedLines,omitempty" json:"includeDeletedLines,omitempty"` +} + +// ListBillingProfilesParams defines parameters for ListBillingProfiles. +type ListBillingProfilesParams struct { + IncludeArchived *bool `form:"includeArchived,omitempty" json:"includeArchived,omitempty"` + Expand *[]BillingProfileExpand `form:"expand,omitempty" json:"expand,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *BillingProfileOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *BillingProfileOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetBillingProfileParams defines parameters for GetBillingProfile. +type GetBillingProfileParams struct { + Expand *[]BillingProfileExpand `form:"expand,omitempty" json:"expand,omitempty"` +} + +// ListCustomersParams defines parameters for ListCustomers. +type ListCustomersParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *CustomerOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *CustomerOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // IncludeDeleted Include deleted customers. + IncludeDeleted *QueryCustomerListIncludeDeleted `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Key Filter customers by key. + // Case-insensitive partial match. + Key *QueryCustomerListKey `form:"key,omitempty" json:"key,omitempty"` + + // Name Filter customers by name. + // Case-insensitive partial match. + Name *QueryCustomerListName `form:"name,omitempty" json:"name,omitempty"` + + // PrimaryEmail Filter customers by primary email. + // Case-insensitive partial match. + PrimaryEmail *QueryCustomerListPrimaryEmail `form:"primaryEmail,omitempty" json:"primaryEmail,omitempty"` + + // Subject Filter customers by usage attribution subject. + // Case-insensitive partial match. + Subject *QueryCustomerListSubject `form:"subject,omitempty" json:"subject,omitempty"` + + // PlanKey Filter customers by the plan key of their susbcription. + PlanKey *QueryCustomerListPlanKey `form:"planKey,omitempty" json:"planKey,omitempty"` + + // Expand What parts of the list output to expand in listings + Expand *QueryCustomerListExpand `form:"expand,omitempty" json:"expand,omitempty"` +} + +// GetCustomerParams defines parameters for GetCustomer. +type GetCustomerParams struct { + // Expand What parts of the customer output to expand + Expand *QueryCustomerGet `form:"expand,omitempty" json:"expand,omitempty"` +} + +// ListCustomerAppDataParams defines parameters for ListCustomerAppData. +type ListCustomerAppDataParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Type Filter customer data by app type. + Type *ListCustomerAppDataParamsType `form:"type,omitempty" json:"type,omitempty"` +} + +// UpsertCustomerAppDataJSONBody defines parameters for UpsertCustomerAppData. +type UpsertCustomerAppDataJSONBody = []CustomerAppDataCreateOrUpdateItem + +// GetCustomerEntitlementValueParams defines parameters for GetCustomerEntitlementValue. +type GetCustomerEntitlementValueParams struct { + Time *time.Time `form:"time,omitempty" json:"time,omitempty"` +} + +// ListCustomerSubscriptionsParams defines parameters for ListCustomerSubscriptions. +type ListCustomerSubscriptionsParams struct { + Status *[]SubscriptionStatus `form:"status,omitempty" json:"status,omitempty"` + + // Order The order direction. + Order *CustomerSubscriptionOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *CustomerSubscriptionOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// ListEntitlementsParams defines parameters for ListEntitlements. +type ListEntitlementsParams struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Subject Filtering by multiple subjects. + // + // Usage: `?subject=customer-1&subject=customer-2` + Subject *[]string `form:"subject,omitempty" json:"subject,omitempty"` + + // EntitlementType Filtering by multiple entitlement types. + // + // Usage: `?entitlementType=metered&entitlementType=boolean` + EntitlementType *[]EntitlementType `form:"entitlementType,omitempty" json:"entitlementType,omitempty"` + + // ExcludeInactive Exclude inactive entitlements in the response (those scheduled for later or earlier) + ExcludeInactive *bool `form:"excludeInactive,omitempty" json:"excludeInactive,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *EntitlementOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *EntitlementOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListEventsParams defines parameters for ListEvents. +type ListEventsParams struct { + // ClientId Client ID + // Useful to track progress of a query. + ClientId *string `form:"clientId,omitempty" json:"clientId,omitempty"` + + // IngestedAtFrom Start date-time in RFC 3339 format. + // + // Inclusive. + IngestedAtFrom *time.Time `form:"ingestedAtFrom,omitempty" json:"ingestedAtFrom,omitempty"` + + // IngestedAtTo End date-time in RFC 3339 format. + // + // Inclusive. + IngestedAtTo *time.Time `form:"ingestedAtTo,omitempty" json:"ingestedAtTo,omitempty"` + + // Id The event ID. + // + // Accepts partial ID. + Id *string `form:"id,omitempty" json:"id,omitempty"` + + // Subject The event subject. + // + // Accepts partial subject. + Subject *string `form:"subject,omitempty" json:"subject,omitempty"` + + // CustomerId The event customer ID. + CustomerId *[]string `form:"customerId,omitempty" json:"customerId,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // Limit Number of events to return. + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// IngestEventsApplicationCloudeventsBatchPlusJSONBody defines parameters for IngestEvents. +type IngestEventsApplicationCloudeventsBatchPlusJSONBody = []Event + +// ListFeaturesParams defines parameters for ListFeatures. +type ListFeaturesParams struct { + // MeterSlug Filter by meterSlug + MeterSlug *[]string `form:"meterSlug,omitempty" json:"meterSlug,omitempty"` + + // IncludeArchived Include archived features in response. + IncludeArchived *bool `form:"includeArchived,omitempty" json:"includeArchived,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *FeatureOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *FeatureOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListGrantsParams defines parameters for ListGrants. +type ListGrantsParams struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Subject Filtering by multiple subjects. + // + // Usage: `?subject=customer-1&subject=customer-2` + Subject *[]string `form:"subject,omitempty" json:"subject,omitempty"` + + // IncludeDeleted Include deleted + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *GrantOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *GrantOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// VoidGrantParams defines parameters for VoidGrant. +type VoidGrantParams struct { + // At The time at which the grant should be voided. + // Must not be in the future and must be within the current usage period of the entitlement. + // Defaults to the current time if not specified. + At *time.Time `form:"at,omitempty" json:"at,omitempty"` +} + +// ListMarketplaceListingsParams defines parameters for ListMarketplaceListings. +type ListMarketplaceListingsParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// MarketplaceAppAPIKeyInstallJSONBody defines parameters for MarketplaceAppAPIKeyInstall. +type MarketplaceAppAPIKeyInstallJSONBody struct { + // ApiKey The API key for the provider. + // For example, the Stripe API key. + ApiKey string `json:"apiKey"` + + // CreateBillingProfile If true, a billing profile will be created for the app. + // The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + CreateBillingProfile *bool `json:"createBillingProfile,omitempty"` + + // Name Name of the application to install. + // + // If name is not provided defaults to the marketplace listing's name. + Name *string `json:"name,omitempty"` +} + +// MarketplaceOAuth2InstallAuthorizeParams defines parameters for MarketplaceOAuth2InstallAuthorize. +type MarketplaceOAuth2InstallAuthorizeParams struct { + // State Required if the "state" parameter was present in the client authorization request. + // The exact value received from the client: + // + // Unique, randomly generated, opaque, and non-guessable string that is sent + // when starting an authentication request and validated when processing the response. + State *OAuth2AuthorizationCodeGrantSuccessParamsState `form:"state,omitempty" json:"state,omitempty"` + + // Code Authorization code which the client will later exchange for an access token. + // Required with the success response. + Code *OAuth2AuthorizationCodeGrantSuccessParamsCode `form:"code,omitempty" json:"code,omitempty"` + + // Error Error code. + // Required with the error response. + Error *OAuth2AuthorizationCodeGrantErrorParamsError `form:"error,omitempty" json:"error,omitempty"` + + // ErrorDescription Optional human-readable text providing additional information, + // used to assist the client developer in understanding the error that occurred. + ErrorDescription *OAuth2AuthorizationCodeGrantErrorParamsErrorDescription `form:"error_description,omitempty" json:"error_description,omitempty"` + + // ErrorUri Optional uri identifying a human-readable web page with + // information about the error, used to provide the client + // developer with additional information about the error + ErrorUri *OAuth2AuthorizationCodeGrantErrorParamsErrorUri `form:"error_uri,omitempty" json:"error_uri,omitempty"` +} + +// ListMetersParams defines parameters for ListMeters. +type ListMetersParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *MeterOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *MeterOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // IncludeDeleted Include deleted meters. + IncludeDeleted *QueryMeterListIncludeDeleted `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` +} + +// ListMeterGroupByValuesParams defines parameters for ListMeterGroupByValues. +type ListMeterGroupByValuesParams struct { + // From Start date-time in RFC 3339 format. + // + // Inclusive. Defaults to 24 hours ago. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *time.Time `form:"to,omitempty" json:"to,omitempty"` +} + +// QueryMeterParams defines parameters for QueryMeter. +type QueryMeterParams struct { + // ClientId Client ID + // Useful to track progress of a query. + ClientId *MeterQueryClientId `form:"clientId,omitempty" json:"clientId,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *MeterQueryFrom `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *MeterQueryTo `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + // + // For example: ?windowSize=DAY + WindowSize *MeterQueryWindowSize `form:"windowSize,omitempty" json:"windowSize,omitempty"` + + // WindowTimeZone The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + // If not specified, the UTC timezone will be used. + // + // For example: ?windowTimeZone=UTC + WindowTimeZone *MeterQueryWindowTimeZone `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` + + // Subject Filtering by multiple subjects. + // + // For example: ?subject=subject-1&subject=subject-2 + Subject *MeterQuerySubject `form:"subject,omitempty" json:"subject,omitempty"` + + // FilterCustomerId Filtering by multiple customers. + // + // For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + FilterCustomerId *MeterQueryFilterCustomerId `form:"filterCustomerId,omitempty" json:"filterCustomerId,omitempty"` + + // FilterGroupBy Simple filter for group bys with exact match. + // + // For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + // + // ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + FilterGroupBy *MeterQueryFilterGroupBy `json:"filterGroupBy,omitempty"` + + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *MeterQueryAdvancedMeterGroupByFilters `form:"advancedMeterGroupByFilters,omitempty" json:"advancedMeterGroupByFilters,omitempty"` + + // GroupBy If not specified a single aggregate will be returned for each subject and time window. + // `subject` is a reserved group by value. + // + // For example: ?groupBy=subject&groupBy=model + GroupBy *MeterQueryGroupBy `form:"groupBy,omitempty" json:"groupBy,omitempty"` +} + +// ListMeterSubjectsParams defines parameters for ListMeterSubjects. +type ListMeterSubjectsParams struct { + // From Start date-time in RFC 3339 format. + // + // Inclusive. Defaults to the beginning of time. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *time.Time `form:"to,omitempty" json:"to,omitempty"` +} + +// ListNotificationChannelsParams defines parameters for ListNotificationChannels. +type ListNotificationChannelsParams struct { + // IncludeDeleted Include deleted notification channels in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // IncludeDisabled Include disabled notification channels in response. + // + // Usage: `?includeDisabled=false` + IncludeDisabled *bool `form:"includeDisabled,omitempty" json:"includeDisabled,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *NotificationChannelOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *NotificationChannelOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListNotificationEventsParams defines parameters for ListNotificationEvents. +type ListNotificationEventsParams struct { + // From Start date-time in RFC 3339 format. + // Inclusive. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // Inclusive. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // Feature Filtering by multiple feature ids or keys. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Subject Filtering by multiple subject ids or keys. + // + // Usage: `?subject=subject-1&subject=subject-2` + Subject *[]string `form:"subject,omitempty" json:"subject,omitempty"` + + // Rule Filtering by multiple rule ids. + // + // Usage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5` + Rule *[]string `form:"rule,omitempty" json:"rule,omitempty"` + + // Channel Filtering by multiple channel ids. + // + // Usage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J` + Channel *[]string `form:"channel,omitempty" json:"channel,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *NotificationEventOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *NotificationEventOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListNotificationRulesParams defines parameters for ListNotificationRules. +type ListNotificationRulesParams struct { + // IncludeDeleted Include deleted notification rules in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // IncludeDisabled Include disabled notification rules in response. + // + // Usage: `?includeDisabled=false` + IncludeDisabled *bool `form:"includeDisabled,omitempty" json:"includeDisabled,omitempty"` + + // Feature Filtering by multiple feature ids/keys. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Channel Filtering by multiple notifiaction channel ids. + // + // Usage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3` + Channel *[]string `form:"channel,omitempty" json:"channel,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *NotificationRuleOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *NotificationRuleOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListPlansParams defines parameters for ListPlans. +type ListPlansParams struct { + // IncludeDeleted Include deleted plans in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Id Filter by plan.id attribute + Id *[]string `form:"id,omitempty" json:"id,omitempty"` + + // Key Filter by plan.key attribute + Key *[]string `form:"key,omitempty" json:"key,omitempty"` + + // KeyVersion Filter by plan.key and plan.version attributes + KeyVersion *map[string][]int `json:"keyVersion,omitempty"` + + // Status Only return plans with the given status. + // + // Usage: + // - `?status=active`: return only the currently active plan + // - `?status=draft`: return only the draft plan + // - `?status=archived`: return only the archived plans + Status *[]PlanStatus `form:"status,omitempty" json:"status,omitempty"` + + // Currency Filter by plan.currency attribute + Currency *[]CurrencyCode `form:"currency,omitempty" json:"currency,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *PlanOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *PlanOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetPlanParams defines parameters for GetPlan. +type GetPlanParams struct { + // IncludeLatest Include latest version of the Plan instead of the version in active state. + // + // Usage: `?includeLatest=true` + IncludeLatest *bool `form:"includeLatest,omitempty" json:"includeLatest,omitempty"` +} + +// ListPlanAddonsParams defines parameters for ListPlanAddons. +type ListPlanAddonsParams struct { + // IncludeDeleted Include deleted plan add-on assignments. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Id Filter by addon.id attribute. + Id *[]string `form:"id,omitempty" json:"id,omitempty"` + + // Key Filter by addon.key attribute. + Key *[]string `form:"key,omitempty" json:"key,omitempty"` + + // KeyVersion Filter by addon.key and addon.version attributes. + KeyVersion *map[string][]int `json:"keyVersion,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *PlanAddonOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *PlanAddonOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// QueryPortalMeterParams defines parameters for QueryPortalMeter. +type QueryPortalMeterParams struct { + // ClientId Client ID + // Useful to track progress of a query. + ClientId *MeterQueryClientId `form:"clientId,omitempty" json:"clientId,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *MeterQueryFrom `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *MeterQueryTo `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + // + // For example: ?windowSize=DAY + WindowSize *MeterQueryWindowSize `form:"windowSize,omitempty" json:"windowSize,omitempty"` + + // WindowTimeZone The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + // If not specified, the UTC timezone will be used. + // + // For example: ?windowTimeZone=UTC + WindowTimeZone *MeterQueryWindowTimeZone `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` + + // FilterCustomerId Filtering by multiple customers. + // + // For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + FilterCustomerId *MeterQueryFilterCustomerId `form:"filterCustomerId,omitempty" json:"filterCustomerId,omitempty"` + + // FilterGroupBy Simple filter for group bys with exact match. + // + // For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + // + // ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + FilterGroupBy *MeterQueryFilterGroupBy `json:"filterGroupBy,omitempty"` + + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *MeterQueryAdvancedMeterGroupByFilters `form:"advancedMeterGroupByFilters,omitempty" json:"advancedMeterGroupByFilters,omitempty"` + + // GroupBy If not specified a single aggregate will be returned for each subject and time window. + // `subject` is a reserved group by value. + // + // For example: ?groupBy=subject&groupBy=model + GroupBy *MeterQueryGroupBy `form:"groupBy,omitempty" json:"groupBy,omitempty"` +} + +// ListPortalTokensParams defines parameters for ListPortalTokens. +type ListPortalTokensParams struct { + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// InvalidatePortalTokensJSONBody defines parameters for InvalidatePortalTokens. +type InvalidatePortalTokensJSONBody struct { + // Id Invalidate a portal token by ID. + Id *string `json:"id,omitempty"` + + // Subject Invalidate all portal tokens for a subject. + Subject *string `json:"subject,omitempty"` +} + +// UpsertSubjectJSONBody defines parameters for UpsertSubject. +type UpsertSubjectJSONBody = []SubjectUpsert + +// ListSubjectEntitlementsParams defines parameters for ListSubjectEntitlements. +type ListSubjectEntitlementsParams struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` +} + +// ListEntitlementGrantsParams defines parameters for ListEntitlementGrants. +type ListEntitlementGrantsParams struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + OrderBy *GrantOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetEntitlementValueParams defines parameters for GetEntitlementValue. +type GetEntitlementValueParams struct { + Time *time.Time `form:"time,omitempty" json:"time,omitempty"` +} + +// GetEntitlementHistoryParams defines parameters for GetEntitlementHistory. +type GetEntitlementHistoryParams struct { + // From Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + // If not now then gets truncated to the granularity of the underlying meter. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize Windowsize + WindowSize WindowSize `form:"windowSize" json:"windowSize"` + + // WindowTimeZone The timezone used when calculating the windows. + WindowTimeZone *string `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` +} + +// GetSubscriptionParams defines parameters for GetSubscription. +type GetSubscriptionParams struct { + // At The time at which the subscription should be queried. If not provided the current time is used. + At *time.Time `form:"at,omitempty" json:"at,omitempty"` +} + +// CancelSubscriptionJSONBody defines parameters for CancelSubscription. +type CancelSubscriptionJSONBody struct { + // Timing If not provided the subscription is canceled immediately. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// MigrateSubscriptionJSONBody defines parameters for MigrateSubscription. +type MigrateSubscriptionJSONBody struct { + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // StartingPhase The key of the phase to start the subscription in. + // If not provided, the subscription will start in the first phase of the plan. + StartingPhase *string `json:"startingPhase,omitempty"` + + // TargetVersion The version of the plan to migrate to. + // If not provided, the subscription will migrate to the latest version of the current plan. + TargetVersion *int `json:"targetVersion,omitempty"` + + // Timing Timing configuration for the migration, when the migration should take effect. + // If not supported by the subscription, 400 will be returned. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// ListCustomerEntitlementsV2Params defines parameters for ListCustomerEntitlementsV2. +type ListCustomerEntitlementsV2Params struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *EntitlementOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *EntitlementOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListCustomerEntitlementGrantsV2Params defines parameters for ListCustomerEntitlementGrantsV2. +type ListCustomerEntitlementGrantsV2Params struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *GrantOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *GrantOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetCustomerEntitlementHistoryV2Params defines parameters for GetCustomerEntitlementHistoryV2. +type GetCustomerEntitlementHistoryV2Params struct { + // From Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + // If not now then gets truncated to the granularity of the underlying meter. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize Windowsize + WindowSize WindowSize `form:"windowSize" json:"windowSize"` + + // WindowTimeZone The timezone used when calculating the windows. + WindowTimeZone *string `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` +} + +// GetCustomerEntitlementValueV2Params defines parameters for GetCustomerEntitlementValueV2. +type GetCustomerEntitlementValueV2Params struct { + Time *time.Time `form:"time,omitempty" json:"time,omitempty"` +} + +// ListEntitlementsV2Params defines parameters for ListEntitlementsV2. +type ListEntitlementsV2Params struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // CustomerKeys Filtering by multiple customers. + // + // Usage: `?customerKeys=customer-1&customerKeys=customer-3` + CustomerKeys *[]string `form:"customerKeys,omitempty" json:"customerKeys,omitempty"` + + // CustomerIds Filtering by multiple customers. + // + // Usage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9` + CustomerIds *[]string `form:"customerIds,omitempty" json:"customerIds,omitempty"` + + // EntitlementType Filtering by multiple entitlement types. + // + // Usage: `?entitlementType=metered&entitlementType=boolean` + EntitlementType *[]EntitlementType `form:"entitlementType,omitempty" json:"entitlementType,omitempty"` + + // ExcludeInactive Exclude inactive entitlements in the response (those scheduled for later or earlier) + ExcludeInactive *bool `form:"excludeInactive,omitempty" json:"excludeInactive,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *EntitlementOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *EntitlementOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListEventsV2Params defines parameters for ListEventsV2. +type ListEventsV2Params struct { + // Cursor The cursor after which to start the pagination. + Cursor *CursorPaginationCursor `form:"cursor,omitempty" json:"cursor,omitempty"` + + // Limit The limit of the pagination. + Limit *CursorPaginationLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // ClientId Client ID + // Useful to track progress of a query. + ClientId *string `form:"clientId,omitempty" json:"clientId,omitempty"` + + // Filter The filter for the events encoded as JSON string. + Filter *struct { + // CustomerId A filter for a ID (ULID) field allowing only equality or inclusion. + CustomerId *FilterIDExact `json:"customerId,omitempty"` + + // Id A filter for a string field. + Id *FilterString `json:"id,omitempty"` + + // IngestedAt A filter for a time field. + IngestedAt *FilterTime `json:"ingestedAt,omitempty"` + + // Source A filter for a string field. + Source *FilterString `json:"source,omitempty"` + + // Subject A filter for a string field. + Subject *FilterString `json:"subject,omitempty"` + + // Time A filter for a time field. + Time *FilterTime `json:"time,omitempty"` + + // Type A filter for a string field. + Type *FilterString `json:"type,omitempty"` + } `form:"filter,omitempty" json:"filter,omitempty"` +} + +// ListGrantsV2Params defines parameters for ListGrantsV2. +type ListGrantsV2Params struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Customer Filtering by multiple customers (either by ID or key). + // + // Usage: `?customer=customer-1&customer=customer-2` + Customer *[]ULIDOrExternalKey `form:"customer,omitempty" json:"customer,omitempty"` + + // IncludeDeleted Include deleted + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *GrantOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *GrantOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// CreateAddonJSONRequestBody defines body for CreateAddon for application/json ContentType. +type CreateAddonJSONRequestBody = AddonCreate + +// UpdateAddonJSONRequestBody defines body for UpdateAddon for application/json ContentType. +type UpdateAddonJSONRequestBody = AddonReplaceUpdate + +// AppCustomInvoicingDraftSynchronizedJSONRequestBody defines body for AppCustomInvoicingDraftSynchronized for application/json ContentType. +type AppCustomInvoicingDraftSynchronizedJSONRequestBody = CustomInvoicingDraftSynchronizedRequest + +// AppCustomInvoicingIssuingSynchronizedJSONRequestBody defines body for AppCustomInvoicingIssuingSynchronized for application/json ContentType. +type AppCustomInvoicingIssuingSynchronizedJSONRequestBody = CustomInvoicingFinalizedRequest + +// AppCustomInvoicingUpdatePaymentStatusJSONRequestBody defines body for AppCustomInvoicingUpdatePaymentStatus for application/json ContentType. +type AppCustomInvoicingUpdatePaymentStatusJSONRequestBody = CustomInvoicingUpdatePaymentStatusRequest + +// UpdateAppJSONRequestBody defines body for UpdateApp for application/json ContentType. +type UpdateAppJSONRequestBody = AppReplaceUpdate + +// UpdateStripeAPIKeyJSONRequestBody defines body for UpdateStripeAPIKey for application/json ContentType. +type UpdateStripeAPIKeyJSONRequestBody = StripeAPIKeyInput + +// AppStripeWebhookJSONRequestBody defines body for AppStripeWebhook for application/json ContentType. +type AppStripeWebhookJSONRequestBody = StripeWebhookEvent + +// UpsertBillingProfileCustomerOverrideJSONRequestBody defines body for UpsertBillingProfileCustomerOverride for application/json ContentType. +type UpsertBillingProfileCustomerOverrideJSONRequestBody = BillingProfileCustomerOverrideCreate + +// CreatePendingInvoiceLineJSONRequestBody defines body for CreatePendingInvoiceLine for application/json ContentType. +type CreatePendingInvoiceLineJSONRequestBody = InvoicePendingLineCreateInput + +// SimulateInvoiceJSONRequestBody defines body for SimulateInvoice for application/json ContentType. +type SimulateInvoiceJSONRequestBody = InvoiceSimulationInput + +// InvoicePendingLinesActionJSONRequestBody defines body for InvoicePendingLinesAction for application/json ContentType. +type InvoicePendingLinesActionJSONRequestBody = InvoicePendingLinesActionInput + +// UpdateInvoiceJSONRequestBody defines body for UpdateInvoice for application/json ContentType. +type UpdateInvoiceJSONRequestBody = InvoiceReplaceUpdate + +// VoidInvoiceActionJSONRequestBody defines body for VoidInvoiceAction for application/json ContentType. +type VoidInvoiceActionJSONRequestBody = VoidInvoiceActionInput + +// CreateBillingProfileJSONRequestBody defines body for CreateBillingProfile for application/json ContentType. +type CreateBillingProfileJSONRequestBody = BillingProfileCreate + +// UpdateBillingProfileJSONRequestBody defines body for UpdateBillingProfile for application/json ContentType. +type UpdateBillingProfileJSONRequestBody = BillingProfileReplaceUpdateWithWorkflow + +// CreateCustomerJSONRequestBody defines body for CreateCustomer for application/json ContentType. +type CreateCustomerJSONRequestBody = CustomerCreate + +// UpdateCustomerJSONRequestBody defines body for UpdateCustomer for application/json ContentType. +type UpdateCustomerJSONRequestBody = CustomerReplaceUpdate + +// UpsertCustomerAppDataJSONRequestBody defines body for UpsertCustomerAppData for application/json ContentType. +type UpsertCustomerAppDataJSONRequestBody = UpsertCustomerAppDataJSONBody + +// UpsertCustomerStripeAppDataJSONRequestBody defines body for UpsertCustomerStripeAppData for application/json ContentType. +type UpsertCustomerStripeAppDataJSONRequestBody = StripeCustomerAppDataBase + +// CreateCustomerStripePortalSessionJSONRequestBody defines body for CreateCustomerStripePortalSession for application/json ContentType. +type CreateCustomerStripePortalSessionJSONRequestBody = CreateStripeCustomerPortalSessionParams + +// IngestEventsApplicationCloudeventsPlusJSONRequestBody defines body for IngestEvents for application/cloudevents+json ContentType. +type IngestEventsApplicationCloudeventsPlusJSONRequestBody = Event + +// IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody defines body for IngestEvents for application/cloudevents-batch+json ContentType. +type IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody = IngestEventsApplicationCloudeventsBatchPlusJSONBody + +// IngestEventsJSONRequestBody defines body for IngestEvents for application/json ContentType. +type IngestEventsJSONRequestBody = IngestEventsBody + +// CreateFeatureJSONRequestBody defines body for CreateFeature for application/json ContentType. +type CreateFeatureJSONRequestBody = FeatureCreateInputs + +// MarketplaceAppInstallJSONRequestBody defines body for MarketplaceAppInstall for application/json ContentType. +type MarketplaceAppInstallJSONRequestBody = MarketplaceInstallRequestPayload + +// MarketplaceAppAPIKeyInstallJSONRequestBody defines body for MarketplaceAppAPIKeyInstall for application/json ContentType. +type MarketplaceAppAPIKeyInstallJSONRequestBody MarketplaceAppAPIKeyInstallJSONBody + +// CreateMeterJSONRequestBody defines body for CreateMeter for application/json ContentType. +type CreateMeterJSONRequestBody = MeterCreate + +// UpdateMeterJSONRequestBody defines body for UpdateMeter for application/json ContentType. +type UpdateMeterJSONRequestBody = MeterUpdate + +// QueryMeterPostJSONRequestBody defines body for QueryMeterPost for application/json ContentType. +type QueryMeterPostJSONRequestBody = MeterQueryRequest + +// CreateNotificationChannelJSONRequestBody defines body for CreateNotificationChannel for application/json ContentType. +type CreateNotificationChannelJSONRequestBody = NotificationChannelCreateRequest + +// UpdateNotificationChannelJSONRequestBody defines body for UpdateNotificationChannel for application/json ContentType. +type UpdateNotificationChannelJSONRequestBody = NotificationChannelCreateRequest + +// ResendNotificationEventJSONRequestBody defines body for ResendNotificationEvent for application/json ContentType. +type ResendNotificationEventJSONRequestBody = NotificationEventResendRequest + +// CreateNotificationRuleJSONRequestBody defines body for CreateNotificationRule for application/json ContentType. +type CreateNotificationRuleJSONRequestBody = NotificationRuleCreateRequest + +// UpdateNotificationRuleJSONRequestBody defines body for UpdateNotificationRule for application/json ContentType. +type UpdateNotificationRuleJSONRequestBody = NotificationRuleCreateRequest + +// CreatePlanJSONRequestBody defines body for CreatePlan for application/json ContentType. +type CreatePlanJSONRequestBody = PlanCreate + +// UpdatePlanJSONRequestBody defines body for UpdatePlan for application/json ContentType. +type UpdatePlanJSONRequestBody = PlanReplaceUpdate + +// CreatePlanAddonJSONRequestBody defines body for CreatePlanAddon for application/json ContentType. +type CreatePlanAddonJSONRequestBody = PlanAddonCreate + +// UpdatePlanAddonJSONRequestBody defines body for UpdatePlanAddon for application/json ContentType. +type UpdatePlanAddonJSONRequestBody = PlanAddonReplaceUpdate + +// CreatePortalTokenJSONRequestBody defines body for CreatePortalToken for application/json ContentType. +type CreatePortalTokenJSONRequestBody = PortalToken + +// InvalidatePortalTokensJSONRequestBody defines body for InvalidatePortalTokens for application/json ContentType. +type InvalidatePortalTokensJSONRequestBody InvalidatePortalTokensJSONBody + +// CreateStripeCheckoutSessionJSONRequestBody defines body for CreateStripeCheckoutSession for application/json ContentType. +type CreateStripeCheckoutSessionJSONRequestBody = CreateStripeCheckoutSessionRequest + +// UpsertSubjectJSONRequestBody defines body for UpsertSubject for application/json ContentType. +type UpsertSubjectJSONRequestBody = UpsertSubjectJSONBody + +// CreateEntitlementJSONRequestBody defines body for CreateEntitlement for application/json ContentType. +type CreateEntitlementJSONRequestBody = EntitlementCreateInputs + +// CreateGrantJSONRequestBody defines body for CreateGrant for application/json ContentType. +type CreateGrantJSONRequestBody = EntitlementGrantCreateInput + +// OverrideEntitlementJSONRequestBody defines body for OverrideEntitlement for application/json ContentType. +type OverrideEntitlementJSONRequestBody = EntitlementCreateInputs + +// ResetEntitlementUsageJSONRequestBody defines body for ResetEntitlementUsage for application/json ContentType. +type ResetEntitlementUsageJSONRequestBody = ResetEntitlementUsageInput + +// CreateSubscriptionJSONRequestBody defines body for CreateSubscription for application/json ContentType. +type CreateSubscriptionJSONRequestBody = SubscriptionCreate + +// EditSubscriptionJSONRequestBody defines body for EditSubscription for application/json ContentType. +type EditSubscriptionJSONRequestBody = SubscriptionEdit + +// CreateSubscriptionAddonJSONRequestBody defines body for CreateSubscriptionAddon for application/json ContentType. +type CreateSubscriptionAddonJSONRequestBody = SubscriptionAddonCreate + +// UpdateSubscriptionAddonJSONRequestBody defines body for UpdateSubscriptionAddon for application/json ContentType. +type UpdateSubscriptionAddonJSONRequestBody = SubscriptionAddonUpdate + +// CancelSubscriptionJSONRequestBody defines body for CancelSubscription for application/json ContentType. +type CancelSubscriptionJSONRequestBody CancelSubscriptionJSONBody + +// ChangeSubscriptionJSONRequestBody defines body for ChangeSubscription for application/json ContentType. +type ChangeSubscriptionJSONRequestBody = SubscriptionChange + +// MigrateSubscriptionJSONRequestBody defines body for MigrateSubscription for application/json ContentType. +type MigrateSubscriptionJSONRequestBody MigrateSubscriptionJSONBody + +// CreateCustomerEntitlementV2JSONRequestBody defines body for CreateCustomerEntitlementV2 for application/json ContentType. +type CreateCustomerEntitlementV2JSONRequestBody = EntitlementV2CreateInputs + +// CreateCustomerEntitlementGrantV2JSONRequestBody defines body for CreateCustomerEntitlementGrantV2 for application/json ContentType. +type CreateCustomerEntitlementGrantV2JSONRequestBody = EntitlementGrantCreateInputV2 + +// OverrideCustomerEntitlementV2JSONRequestBody defines body for OverrideCustomerEntitlementV2 for application/json ContentType. +type OverrideCustomerEntitlementV2JSONRequestBody = EntitlementV2CreateInputs + +// ResetCustomerEntitlementUsageV2JSONRequestBody defines body for ResetCustomerEntitlementUsageV2 for application/json ContentType. +type ResetCustomerEntitlementUsageV2JSONRequestBody = ResetEntitlementUsageInput + +// Getter for additional properties for ErrorExtension. Returns the specified +// element and whether it was found +func (a ErrorExtension) Get(fieldName string) (value interface{}, found bool) { + if a.AdditionalProperties != nil { + value, found = a.AdditionalProperties[fieldName] + } + return +} + +// Setter for additional properties for ErrorExtension +func (a *ErrorExtension) Set(fieldName string, value interface{}) { + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]interface{}) + } + a.AdditionalProperties[fieldName] = value +} + +// Override default JSON handling for ErrorExtension to handle AdditionalProperties +func (a *ErrorExtension) UnmarshalJSON(b []byte) error { + object := make(map[string]json.RawMessage) + err := json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["code"]; found { + err = json.Unmarshal(raw, &a.Code) + if err != nil { + return fmt.Errorf("error reading 'code': %w", err) + } + delete(object, "code") + } + + if raw, found := object["field"]; found { + err = json.Unmarshal(raw, &a.Field) + if err != nil { + return fmt.Errorf("error reading 'field': %w", err) + } + delete(object, "field") + } + + if raw, found := object["message"]; found { + err = json.Unmarshal(raw, &a.Message) + if err != nil { + return fmt.Errorf("error reading 'message': %w", err) + } + delete(object, "message") + } + + if len(object) != 0 { + a.AdditionalProperties = make(map[string]interface{}) + for fieldName, fieldBuf := range object { + var fieldVal interface{} + err := json.Unmarshal(fieldBuf, &fieldVal) + if err != nil { + return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) + } + a.AdditionalProperties[fieldName] = fieldVal + } + } + return nil +} + +// Override default JSON handling for ErrorExtension to handle AdditionalProperties +func (a ErrorExtension) MarshalJSON() ([]byte, error) { + var err error + object := make(map[string]json.RawMessage) + + object["code"], err = json.Marshal(a.Code) + if err != nil { + return nil, fmt.Errorf("error marshaling 'code': %w", err) + } + + object["field"], err = json.Marshal(a.Field) + if err != nil { + return nil, fmt.Errorf("error marshaling 'field': %w", err) + } + + object["message"], err = json.Marshal(a.Message) + if err != nil { + return nil, fmt.Errorf("error marshaling 'message': %w", err) + } + + for fieldName, field := range a.AdditionalProperties { + object[fieldName], err = json.Marshal(field) + if err != nil { + return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) + } + } + return json.Marshal(object) +} + +// AsStripeApp returns the union data inside the App as a StripeApp +func (t App) AsStripeApp() (StripeApp, error) { + var body StripeApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeApp overwrites any union data inside the App as the provided StripeApp +func (t *App) FromStripeApp(v StripeApp) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeApp performs a merge with any union data inside the App, using the provided StripeApp +func (t *App) MergeStripeApp(v StripeApp) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxApp returns the union data inside the App as a SandboxApp +func (t App) AsSandboxApp() (SandboxApp, error) { + var body SandboxApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxApp overwrites any union data inside the App as the provided SandboxApp +func (t *App) FromSandboxApp(v SandboxApp) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxApp performs a merge with any union data inside the App, using the provided SandboxApp +func (t *App) MergeSandboxApp(v SandboxApp) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingApp returns the union data inside the App as a CustomInvoicingApp +func (t App) AsCustomInvoicingApp() (CustomInvoicingApp, error) { + var body CustomInvoicingApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingApp overwrites any union data inside the App as the provided CustomInvoicingApp +func (t *App) FromCustomInvoicingApp(v CustomInvoicingApp) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingApp performs a merge with any union data inside the App, using the provided CustomInvoicingApp +func (t *App) MergeCustomInvoicingApp(v CustomInvoicingApp) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t App) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t App) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingApp() + case "sandbox": + return t.AsSandboxApp() + case "stripe": + return t.AsStripeApp() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t App) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *App) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeAppReadOrCreateOrUpdateOrDeleteOrQuery returns the union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery as a StripeAppReadOrCreateOrUpdateOrDeleteOrQuery +func (t AppReadOrCreateOrUpdateOrDeleteOrQuery) AsStripeAppReadOrCreateOrUpdateOrDeleteOrQuery() (StripeAppReadOrCreateOrUpdateOrDeleteOrQuery, error) { + var body StripeAppReadOrCreateOrUpdateOrDeleteOrQuery + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeAppReadOrCreateOrUpdateOrDeleteOrQuery overwrites any union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery as the provided StripeAppReadOrCreateOrUpdateOrDeleteOrQuery +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) FromStripeAppReadOrCreateOrUpdateOrDeleteOrQuery(v StripeAppReadOrCreateOrUpdateOrDeleteOrQuery) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeAppReadOrCreateOrUpdateOrDeleteOrQuery performs a merge with any union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery, using the provided StripeAppReadOrCreateOrUpdateOrDeleteOrQuery +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) MergeStripeAppReadOrCreateOrUpdateOrDeleteOrQuery(v StripeAppReadOrCreateOrUpdateOrDeleteOrQuery) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxApp returns the union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery as a SandboxApp +func (t AppReadOrCreateOrUpdateOrDeleteOrQuery) AsSandboxApp() (SandboxApp, error) { + var body SandboxApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxApp overwrites any union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery as the provided SandboxApp +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) FromSandboxApp(v SandboxApp) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxApp performs a merge with any union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery, using the provided SandboxApp +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) MergeSandboxApp(v SandboxApp) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingApp returns the union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery as a CustomInvoicingApp +func (t AppReadOrCreateOrUpdateOrDeleteOrQuery) AsCustomInvoicingApp() (CustomInvoicingApp, error) { + var body CustomInvoicingApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingApp overwrites any union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery as the provided CustomInvoicingApp +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) FromCustomInvoicingApp(v CustomInvoicingApp) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingApp performs a merge with any union data inside the AppReadOrCreateOrUpdateOrDeleteOrQuery, using the provided CustomInvoicingApp +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) MergeCustomInvoicingApp(v CustomInvoicingApp) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t AppReadOrCreateOrUpdateOrDeleteOrQuery) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t AppReadOrCreateOrUpdateOrDeleteOrQuery) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingApp() + case "sandbox": + return t.AsSandboxApp() + case "stripe": + return t.AsStripeAppReadOrCreateOrUpdateOrDeleteOrQuery() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t AppReadOrCreateOrUpdateOrDeleteOrQuery) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *AppReadOrCreateOrUpdateOrDeleteOrQuery) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeAppReplaceUpdate returns the union data inside the AppReplaceUpdate as a StripeAppReplaceUpdate +func (t AppReplaceUpdate) AsStripeAppReplaceUpdate() (StripeAppReplaceUpdate, error) { + var body StripeAppReplaceUpdate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeAppReplaceUpdate overwrites any union data inside the AppReplaceUpdate as the provided StripeAppReplaceUpdate +func (t *AppReplaceUpdate) FromStripeAppReplaceUpdate(v StripeAppReplaceUpdate) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeAppReplaceUpdate performs a merge with any union data inside the AppReplaceUpdate, using the provided StripeAppReplaceUpdate +func (t *AppReplaceUpdate) MergeStripeAppReplaceUpdate(v StripeAppReplaceUpdate) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxAppReplaceUpdate returns the union data inside the AppReplaceUpdate as a SandboxAppReplaceUpdate +func (t AppReplaceUpdate) AsSandboxAppReplaceUpdate() (SandboxAppReplaceUpdate, error) { + var body SandboxAppReplaceUpdate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxAppReplaceUpdate overwrites any union data inside the AppReplaceUpdate as the provided SandboxAppReplaceUpdate +func (t *AppReplaceUpdate) FromSandboxAppReplaceUpdate(v SandboxAppReplaceUpdate) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxAppReplaceUpdate performs a merge with any union data inside the AppReplaceUpdate, using the provided SandboxAppReplaceUpdate +func (t *AppReplaceUpdate) MergeSandboxAppReplaceUpdate(v SandboxAppReplaceUpdate) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingAppReplaceUpdate returns the union data inside the AppReplaceUpdate as a CustomInvoicingAppReplaceUpdate +func (t AppReplaceUpdate) AsCustomInvoicingAppReplaceUpdate() (CustomInvoicingAppReplaceUpdate, error) { + var body CustomInvoicingAppReplaceUpdate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingAppReplaceUpdate overwrites any union data inside the AppReplaceUpdate as the provided CustomInvoicingAppReplaceUpdate +func (t *AppReplaceUpdate) FromCustomInvoicingAppReplaceUpdate(v CustomInvoicingAppReplaceUpdate) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingAppReplaceUpdate performs a merge with any union data inside the AppReplaceUpdate, using the provided CustomInvoicingAppReplaceUpdate +func (t *AppReplaceUpdate) MergeCustomInvoicingAppReplaceUpdate(v CustomInvoicingAppReplaceUpdate) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t AppReplaceUpdate) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t AppReplaceUpdate) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingAppReplaceUpdate() + case "sandbox": + return t.AsSandboxAppReplaceUpdate() + case "stripe": + return t.AsStripeAppReplaceUpdate() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t AppReplaceUpdate) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *AppReplaceUpdate) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsDiscountReasonMaximumSpend returns the union data inside the BillingDiscountReason as a DiscountReasonMaximumSpend +func (t BillingDiscountReason) AsDiscountReasonMaximumSpend() (DiscountReasonMaximumSpend, error) { + var body DiscountReasonMaximumSpend + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscountReasonMaximumSpend overwrites any union data inside the BillingDiscountReason as the provided DiscountReasonMaximumSpend +func (t *BillingDiscountReason) FromDiscountReasonMaximumSpend(v DiscountReasonMaximumSpend) error { + v.Type = "maximum_spend" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscountReasonMaximumSpend performs a merge with any union data inside the BillingDiscountReason, using the provided DiscountReasonMaximumSpend +func (t *BillingDiscountReason) MergeDiscountReasonMaximumSpend(v DiscountReasonMaximumSpend) error { + v.Type = "maximum_spend" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDiscountReasonRatecardPercentage returns the union data inside the BillingDiscountReason as a DiscountReasonRatecardPercentage +func (t BillingDiscountReason) AsDiscountReasonRatecardPercentage() (DiscountReasonRatecardPercentage, error) { + var body DiscountReasonRatecardPercentage + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscountReasonRatecardPercentage overwrites any union data inside the BillingDiscountReason as the provided DiscountReasonRatecardPercentage +func (t *BillingDiscountReason) FromDiscountReasonRatecardPercentage(v DiscountReasonRatecardPercentage) error { + v.Type = "ratecard_percentage" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscountReasonRatecardPercentage performs a merge with any union data inside the BillingDiscountReason, using the provided DiscountReasonRatecardPercentage +func (t *BillingDiscountReason) MergeDiscountReasonRatecardPercentage(v DiscountReasonRatecardPercentage) error { + v.Type = "ratecard_percentage" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDiscountReasonRatecardUsage returns the union data inside the BillingDiscountReason as a DiscountReasonRatecardUsage +func (t BillingDiscountReason) AsDiscountReasonRatecardUsage() (DiscountReasonRatecardUsage, error) { + var body DiscountReasonRatecardUsage + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscountReasonRatecardUsage overwrites any union data inside the BillingDiscountReason as the provided DiscountReasonRatecardUsage +func (t *BillingDiscountReason) FromDiscountReasonRatecardUsage(v DiscountReasonRatecardUsage) error { + v.Type = "ratecard_usage" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscountReasonRatecardUsage performs a merge with any union data inside the BillingDiscountReason, using the provided DiscountReasonRatecardUsage +func (t *BillingDiscountReason) MergeDiscountReasonRatecardUsage(v DiscountReasonRatecardUsage) error { + v.Type = "ratecard_usage" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BillingDiscountReason) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t BillingDiscountReason) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "maximum_spend": + return t.AsDiscountReasonMaximumSpend() + case "ratecard_percentage": + return t.AsDiscountReasonRatecardPercentage() + case "ratecard_usage": + return t.AsDiscountReasonRatecardUsage() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t BillingDiscountReason) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BillingDiscountReason) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsBillingProfileApps returns the union data inside the BillingProfileAppsOrReference as a BillingProfileApps +func (t BillingProfileAppsOrReference) AsBillingProfileApps() (BillingProfileApps, error) { + var body BillingProfileApps + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingProfileApps overwrites any union data inside the BillingProfileAppsOrReference as the provided BillingProfileApps +func (t *BillingProfileAppsOrReference) FromBillingProfileApps(v BillingProfileApps) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingProfileApps performs a merge with any union data inside the BillingProfileAppsOrReference, using the provided BillingProfileApps +func (t *BillingProfileAppsOrReference) MergeBillingProfileApps(v BillingProfileApps) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsBillingProfileAppReferences returns the union data inside the BillingProfileAppsOrReference as a BillingProfileAppReferences +func (t BillingProfileAppsOrReference) AsBillingProfileAppReferences() (BillingProfileAppReferences, error) { + var body BillingProfileAppReferences + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingProfileAppReferences overwrites any union data inside the BillingProfileAppsOrReference as the provided BillingProfileAppReferences +func (t *BillingProfileAppsOrReference) FromBillingProfileAppReferences(v BillingProfileAppReferences) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingProfileAppReferences performs a merge with any union data inside the BillingProfileAppsOrReference, using the provided BillingProfileAppReferences +func (t *BillingProfileAppsOrReference) MergeBillingProfileAppReferences(v BillingProfileAppReferences) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BillingProfileAppsOrReference) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BillingProfileAppsOrReference) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsBillingWorkflowCollectionAlignmentSubscription returns the union data inside the BillingWorkflowCollectionAlignment as a BillingWorkflowCollectionAlignmentSubscription +func (t BillingWorkflowCollectionAlignment) AsBillingWorkflowCollectionAlignmentSubscription() (BillingWorkflowCollectionAlignmentSubscription, error) { + var body BillingWorkflowCollectionAlignmentSubscription + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingWorkflowCollectionAlignmentSubscription overwrites any union data inside the BillingWorkflowCollectionAlignment as the provided BillingWorkflowCollectionAlignmentSubscription +func (t *BillingWorkflowCollectionAlignment) FromBillingWorkflowCollectionAlignmentSubscription(v BillingWorkflowCollectionAlignmentSubscription) error { + v.Type = "subscription" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingWorkflowCollectionAlignmentSubscription performs a merge with any union data inside the BillingWorkflowCollectionAlignment, using the provided BillingWorkflowCollectionAlignmentSubscription +func (t *BillingWorkflowCollectionAlignment) MergeBillingWorkflowCollectionAlignmentSubscription(v BillingWorkflowCollectionAlignmentSubscription) error { + v.Type = "subscription" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsBillingWorkflowCollectionAlignmentAnchored returns the union data inside the BillingWorkflowCollectionAlignment as a BillingWorkflowCollectionAlignmentAnchored +func (t BillingWorkflowCollectionAlignment) AsBillingWorkflowCollectionAlignmentAnchored() (BillingWorkflowCollectionAlignmentAnchored, error) { + var body BillingWorkflowCollectionAlignmentAnchored + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingWorkflowCollectionAlignmentAnchored overwrites any union data inside the BillingWorkflowCollectionAlignment as the provided BillingWorkflowCollectionAlignmentAnchored +func (t *BillingWorkflowCollectionAlignment) FromBillingWorkflowCollectionAlignmentAnchored(v BillingWorkflowCollectionAlignmentAnchored) error { + v.Type = "anchored" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingWorkflowCollectionAlignmentAnchored performs a merge with any union data inside the BillingWorkflowCollectionAlignment, using the provided BillingWorkflowCollectionAlignmentAnchored +func (t *BillingWorkflowCollectionAlignment) MergeBillingWorkflowCollectionAlignmentAnchored(v BillingWorkflowCollectionAlignmentAnchored) error { + v.Type = "anchored" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BillingWorkflowCollectionAlignment) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t BillingWorkflowCollectionAlignment) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "anchored": + return t.AsBillingWorkflowCollectionAlignmentAnchored() + case "subscription": + return t.AsBillingWorkflowCollectionAlignmentSubscription() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t BillingWorkflowCollectionAlignment) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BillingWorkflowCollectionAlignment) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsCustomerId returns the union data inside the CreateStripeCheckoutSessionRequest_Customer as a CustomerId +func (t CreateStripeCheckoutSessionRequest_Customer) AsCustomerId() (CustomerId, error) { + var body CustomerId + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomerId overwrites any union data inside the CreateStripeCheckoutSessionRequest_Customer as the provided CustomerId +func (t *CreateStripeCheckoutSessionRequest_Customer) FromCustomerId(v CustomerId) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomerId performs a merge with any union data inside the CreateStripeCheckoutSessionRequest_Customer, using the provided CustomerId +func (t *CreateStripeCheckoutSessionRequest_Customer) MergeCustomerId(v CustomerId) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomerKey returns the union data inside the CreateStripeCheckoutSessionRequest_Customer as a CustomerKey +func (t CreateStripeCheckoutSessionRequest_Customer) AsCustomerKey() (CustomerKey, error) { + var body CustomerKey + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomerKey overwrites any union data inside the CreateStripeCheckoutSessionRequest_Customer as the provided CustomerKey +func (t *CreateStripeCheckoutSessionRequest_Customer) FromCustomerKey(v CustomerKey) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomerKey performs a merge with any union data inside the CreateStripeCheckoutSessionRequest_Customer, using the provided CustomerKey +func (t *CreateStripeCheckoutSessionRequest_Customer) MergeCustomerKey(v CustomerKey) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomerCreate returns the union data inside the CreateStripeCheckoutSessionRequest_Customer as a CustomerCreate +func (t CreateStripeCheckoutSessionRequest_Customer) AsCustomerCreate() (CustomerCreate, error) { + var body CustomerCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomerCreate overwrites any union data inside the CreateStripeCheckoutSessionRequest_Customer as the provided CustomerCreate +func (t *CreateStripeCheckoutSessionRequest_Customer) FromCustomerCreate(v CustomerCreate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomerCreate performs a merge with any union data inside the CreateStripeCheckoutSessionRequest_Customer, using the provided CustomerCreate +func (t *CreateStripeCheckoutSessionRequest_Customer) MergeCustomerCreate(v CustomerCreate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CreateStripeCheckoutSessionRequest_Customer) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CreateStripeCheckoutSessionRequest_Customer) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeCustomerAppData returns the union data inside the CustomerAppData as a StripeCustomerAppData +func (t CustomerAppData) AsStripeCustomerAppData() (StripeCustomerAppData, error) { + var body StripeCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeCustomerAppData overwrites any union data inside the CustomerAppData as the provided StripeCustomerAppData +func (t *CustomerAppData) FromStripeCustomerAppData(v StripeCustomerAppData) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeCustomerAppData performs a merge with any union data inside the CustomerAppData, using the provided StripeCustomerAppData +func (t *CustomerAppData) MergeStripeCustomerAppData(v StripeCustomerAppData) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxCustomerAppData returns the union data inside the CustomerAppData as a SandboxCustomerAppData +func (t CustomerAppData) AsSandboxCustomerAppData() (SandboxCustomerAppData, error) { + var body SandboxCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxCustomerAppData overwrites any union data inside the CustomerAppData as the provided SandboxCustomerAppData +func (t *CustomerAppData) FromSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxCustomerAppData performs a merge with any union data inside the CustomerAppData, using the provided SandboxCustomerAppData +func (t *CustomerAppData) MergeSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingCustomerAppData returns the union data inside the CustomerAppData as a CustomInvoicingCustomerAppData +func (t CustomerAppData) AsCustomInvoicingCustomerAppData() (CustomInvoicingCustomerAppData, error) { + var body CustomInvoicingCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingCustomerAppData overwrites any union data inside the CustomerAppData as the provided CustomInvoicingCustomerAppData +func (t *CustomerAppData) FromCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingCustomerAppData performs a merge with any union data inside the CustomerAppData, using the provided CustomInvoicingCustomerAppData +func (t *CustomerAppData) MergeCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CustomerAppData) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t CustomerAppData) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingCustomerAppData() + case "sandbox": + return t.AsSandboxCustomerAppData() + case "stripe": + return t.AsStripeCustomerAppData() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t CustomerAppData) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CustomerAppData) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeCustomerAppDataCreateOrUpdateItem returns the union data inside the CustomerAppDataCreateOrUpdateItem as a StripeCustomerAppDataCreateOrUpdateItem +func (t CustomerAppDataCreateOrUpdateItem) AsStripeCustomerAppDataCreateOrUpdateItem() (StripeCustomerAppDataCreateOrUpdateItem, error) { + var body StripeCustomerAppDataCreateOrUpdateItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeCustomerAppDataCreateOrUpdateItem overwrites any union data inside the CustomerAppDataCreateOrUpdateItem as the provided StripeCustomerAppDataCreateOrUpdateItem +func (t *CustomerAppDataCreateOrUpdateItem) FromStripeCustomerAppDataCreateOrUpdateItem(v StripeCustomerAppDataCreateOrUpdateItem) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeCustomerAppDataCreateOrUpdateItem performs a merge with any union data inside the CustomerAppDataCreateOrUpdateItem, using the provided StripeCustomerAppDataCreateOrUpdateItem +func (t *CustomerAppDataCreateOrUpdateItem) MergeStripeCustomerAppDataCreateOrUpdateItem(v StripeCustomerAppDataCreateOrUpdateItem) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxCustomerAppData returns the union data inside the CustomerAppDataCreateOrUpdateItem as a SandboxCustomerAppData +func (t CustomerAppDataCreateOrUpdateItem) AsSandboxCustomerAppData() (SandboxCustomerAppData, error) { + var body SandboxCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxCustomerAppData overwrites any union data inside the CustomerAppDataCreateOrUpdateItem as the provided SandboxCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) FromSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxCustomerAppData performs a merge with any union data inside the CustomerAppDataCreateOrUpdateItem, using the provided SandboxCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) MergeSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingCustomerAppData returns the union data inside the CustomerAppDataCreateOrUpdateItem as a CustomInvoicingCustomerAppData +func (t CustomerAppDataCreateOrUpdateItem) AsCustomInvoicingCustomerAppData() (CustomInvoicingCustomerAppData, error) { + var body CustomInvoicingCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingCustomerAppData overwrites any union data inside the CustomerAppDataCreateOrUpdateItem as the provided CustomInvoicingCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) FromCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingCustomerAppData performs a merge with any union data inside the CustomerAppDataCreateOrUpdateItem, using the provided CustomInvoicingCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) MergeCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CustomerAppDataCreateOrUpdateItem) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t CustomerAppDataCreateOrUpdateItem) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingCustomerAppData() + case "sandbox": + return t.AsSandboxCustomerAppData() + case "stripe": + return t.AsStripeCustomerAppDataCreateOrUpdateItem() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t CustomerAppDataCreateOrUpdateItem) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CustomerAppDataCreateOrUpdateItem) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMetered returns the union data inside the Entitlement as a EntitlementMetered +func (t Entitlement) AsEntitlementMetered() (EntitlementMetered, error) { + var body EntitlementMetered + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMetered overwrites any union data inside the Entitlement as the provided EntitlementMetered +func (t *Entitlement) FromEntitlementMetered(v EntitlementMetered) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMetered performs a merge with any union data inside the Entitlement, using the provided EntitlementMetered +func (t *Entitlement) MergeEntitlementMetered(v EntitlementMetered) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStatic returns the union data inside the Entitlement as a EntitlementStatic +func (t Entitlement) AsEntitlementStatic() (EntitlementStatic, error) { + var body EntitlementStatic + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStatic overwrites any union data inside the Entitlement as the provided EntitlementStatic +func (t *Entitlement) FromEntitlementStatic(v EntitlementStatic) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStatic performs a merge with any union data inside the Entitlement, using the provided EntitlementStatic +func (t *Entitlement) MergeEntitlementStatic(v EntitlementStatic) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBoolean returns the union data inside the Entitlement as a EntitlementBoolean +func (t Entitlement) AsEntitlementBoolean() (EntitlementBoolean, error) { + var body EntitlementBoolean + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBoolean overwrites any union data inside the Entitlement as the provided EntitlementBoolean +func (t *Entitlement) FromEntitlementBoolean(v EntitlementBoolean) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBoolean performs a merge with any union data inside the Entitlement, using the provided EntitlementBoolean +func (t *Entitlement) MergeEntitlementBoolean(v EntitlementBoolean) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t Entitlement) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t Entitlement) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBoolean() + case "metered": + return t.AsEntitlementMetered() + case "static": + return t.AsEntitlementStatic() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t Entitlement) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *Entitlement) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMeteredCreateInputs returns the union data inside the EntitlementCreateInputs as a EntitlementMeteredCreateInputs +func (t EntitlementCreateInputs) AsEntitlementMeteredCreateInputs() (EntitlementMeteredCreateInputs, error) { + var body EntitlementMeteredCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMeteredCreateInputs overwrites any union data inside the EntitlementCreateInputs as the provided EntitlementMeteredCreateInputs +func (t *EntitlementCreateInputs) FromEntitlementMeteredCreateInputs(v EntitlementMeteredCreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMeteredCreateInputs performs a merge with any union data inside the EntitlementCreateInputs, using the provided EntitlementMeteredCreateInputs +func (t *EntitlementCreateInputs) MergeEntitlementMeteredCreateInputs(v EntitlementMeteredCreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStaticCreateInputs returns the union data inside the EntitlementCreateInputs as a EntitlementStaticCreateInputs +func (t EntitlementCreateInputs) AsEntitlementStaticCreateInputs() (EntitlementStaticCreateInputs, error) { + var body EntitlementStaticCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStaticCreateInputs overwrites any union data inside the EntitlementCreateInputs as the provided EntitlementStaticCreateInputs +func (t *EntitlementCreateInputs) FromEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStaticCreateInputs performs a merge with any union data inside the EntitlementCreateInputs, using the provided EntitlementStaticCreateInputs +func (t *EntitlementCreateInputs) MergeEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBooleanCreateInputs returns the union data inside the EntitlementCreateInputs as a EntitlementBooleanCreateInputs +func (t EntitlementCreateInputs) AsEntitlementBooleanCreateInputs() (EntitlementBooleanCreateInputs, error) { + var body EntitlementBooleanCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBooleanCreateInputs overwrites any union data inside the EntitlementCreateInputs as the provided EntitlementBooleanCreateInputs +func (t *EntitlementCreateInputs) FromEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBooleanCreateInputs performs a merge with any union data inside the EntitlementCreateInputs, using the provided EntitlementBooleanCreateInputs +func (t *EntitlementCreateInputs) MergeEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t EntitlementCreateInputs) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t EntitlementCreateInputs) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBooleanCreateInputs() + case "metered": + return t.AsEntitlementMeteredCreateInputs() + case "static": + return t.AsEntitlementStaticCreateInputs() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t EntitlementCreateInputs) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *EntitlementCreateInputs) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMeteredV2 returns the union data inside the EntitlementV2 as a EntitlementMeteredV2 +func (t EntitlementV2) AsEntitlementMeteredV2() (EntitlementMeteredV2, error) { + var body EntitlementMeteredV2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMeteredV2 overwrites any union data inside the EntitlementV2 as the provided EntitlementMeteredV2 +func (t *EntitlementV2) FromEntitlementMeteredV2(v EntitlementMeteredV2) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMeteredV2 performs a merge with any union data inside the EntitlementV2, using the provided EntitlementMeteredV2 +func (t *EntitlementV2) MergeEntitlementMeteredV2(v EntitlementMeteredV2) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStaticV2 returns the union data inside the EntitlementV2 as a EntitlementStaticV2 +func (t EntitlementV2) AsEntitlementStaticV2() (EntitlementStaticV2, error) { + var body EntitlementStaticV2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStaticV2 overwrites any union data inside the EntitlementV2 as the provided EntitlementStaticV2 +func (t *EntitlementV2) FromEntitlementStaticV2(v EntitlementStaticV2) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStaticV2 performs a merge with any union data inside the EntitlementV2, using the provided EntitlementStaticV2 +func (t *EntitlementV2) MergeEntitlementStaticV2(v EntitlementStaticV2) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBooleanV2 returns the union data inside the EntitlementV2 as a EntitlementBooleanV2 +func (t EntitlementV2) AsEntitlementBooleanV2() (EntitlementBooleanV2, error) { + var body EntitlementBooleanV2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBooleanV2 overwrites any union data inside the EntitlementV2 as the provided EntitlementBooleanV2 +func (t *EntitlementV2) FromEntitlementBooleanV2(v EntitlementBooleanV2) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBooleanV2 performs a merge with any union data inside the EntitlementV2, using the provided EntitlementBooleanV2 +func (t *EntitlementV2) MergeEntitlementBooleanV2(v EntitlementBooleanV2) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t EntitlementV2) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t EntitlementV2) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBooleanV2() + case "metered": + return t.AsEntitlementMeteredV2() + case "static": + return t.AsEntitlementStaticV2() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t EntitlementV2) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *EntitlementV2) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMeteredV2CreateInputs returns the union data inside the EntitlementV2CreateInputs as a EntitlementMeteredV2CreateInputs +func (t EntitlementV2CreateInputs) AsEntitlementMeteredV2CreateInputs() (EntitlementMeteredV2CreateInputs, error) { + var body EntitlementMeteredV2CreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMeteredV2CreateInputs overwrites any union data inside the EntitlementV2CreateInputs as the provided EntitlementMeteredV2CreateInputs +func (t *EntitlementV2CreateInputs) FromEntitlementMeteredV2CreateInputs(v EntitlementMeteredV2CreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMeteredV2CreateInputs performs a merge with any union data inside the EntitlementV2CreateInputs, using the provided EntitlementMeteredV2CreateInputs +func (t *EntitlementV2CreateInputs) MergeEntitlementMeteredV2CreateInputs(v EntitlementMeteredV2CreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStaticCreateInputs returns the union data inside the EntitlementV2CreateInputs as a EntitlementStaticCreateInputs +func (t EntitlementV2CreateInputs) AsEntitlementStaticCreateInputs() (EntitlementStaticCreateInputs, error) { + var body EntitlementStaticCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStaticCreateInputs overwrites any union data inside the EntitlementV2CreateInputs as the provided EntitlementStaticCreateInputs +func (t *EntitlementV2CreateInputs) FromEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStaticCreateInputs performs a merge with any union data inside the EntitlementV2CreateInputs, using the provided EntitlementStaticCreateInputs +func (t *EntitlementV2CreateInputs) MergeEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBooleanCreateInputs returns the union data inside the EntitlementV2CreateInputs as a EntitlementBooleanCreateInputs +func (t EntitlementV2CreateInputs) AsEntitlementBooleanCreateInputs() (EntitlementBooleanCreateInputs, error) { + var body EntitlementBooleanCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBooleanCreateInputs overwrites any union data inside the EntitlementV2CreateInputs as the provided EntitlementBooleanCreateInputs +func (t *EntitlementV2CreateInputs) FromEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBooleanCreateInputs performs a merge with any union data inside the EntitlementV2CreateInputs, using the provided EntitlementBooleanCreateInputs +func (t *EntitlementV2CreateInputs) MergeEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t EntitlementV2CreateInputs) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t EntitlementV2CreateInputs) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBooleanCreateInputs() + case "metered": + return t.AsEntitlementMeteredV2CreateInputs() + case "static": + return t.AsEntitlementStaticCreateInputs() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t EntitlementV2CreateInputs) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *EntitlementV2CreateInputs) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsFeatureManualUnitCost returns the union data inside the FeatureUnitCost as a FeatureManualUnitCost +func (t FeatureUnitCost) AsFeatureManualUnitCost() (FeatureManualUnitCost, error) { + var body FeatureManualUnitCost + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFeatureManualUnitCost overwrites any union data inside the FeatureUnitCost as the provided FeatureManualUnitCost +func (t *FeatureUnitCost) FromFeatureManualUnitCost(v FeatureManualUnitCost) error { + v.Type = "manual" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFeatureManualUnitCost performs a merge with any union data inside the FeatureUnitCost, using the provided FeatureManualUnitCost +func (t *FeatureUnitCost) MergeFeatureManualUnitCost(v FeatureManualUnitCost) error { + v.Type = "manual" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsFeatureLLMUnitCost returns the union data inside the FeatureUnitCost as a FeatureLLMUnitCost +func (t FeatureUnitCost) AsFeatureLLMUnitCost() (FeatureLLMUnitCost, error) { + var body FeatureLLMUnitCost + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFeatureLLMUnitCost overwrites any union data inside the FeatureUnitCost as the provided FeatureLLMUnitCost +func (t *FeatureUnitCost) FromFeatureLLMUnitCost(v FeatureLLMUnitCost) error { + v.Type = "llm" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFeatureLLMUnitCost performs a merge with any union data inside the FeatureUnitCost, using the provided FeatureLLMUnitCost +func (t *FeatureUnitCost) MergeFeatureLLMUnitCost(v FeatureLLMUnitCost) error { + v.Type = "llm" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t FeatureUnitCost) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t FeatureUnitCost) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "llm": + return t.AsFeatureLLMUnitCost() + case "manual": + return t.AsFeatureManualUnitCost() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t FeatureUnitCost) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *FeatureUnitCost) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEvent returns the union data inside the IngestEventsBody as a Event +func (t IngestEventsBody) AsEvent() (Event, error) { + var body Event + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEvent overwrites any union data inside the IngestEventsBody as the provided Event +func (t *IngestEventsBody) FromEvent(v Event) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEvent performs a merge with any union data inside the IngestEventsBody, using the provided Event +func (t *IngestEventsBody) MergeEvent(v Event) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsIngestEventsBody1 returns the union data inside the IngestEventsBody as a IngestEventsBody1 +func (t IngestEventsBody) AsIngestEventsBody1() (IngestEventsBody1, error) { + var body IngestEventsBody1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromIngestEventsBody1 overwrites any union data inside the IngestEventsBody as the provided IngestEventsBody1 +func (t *IngestEventsBody) FromIngestEventsBody1(v IngestEventsBody1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeIngestEventsBody1 performs a merge with any union data inside the IngestEventsBody, using the provided IngestEventsBody1 +func (t *IngestEventsBody) MergeIngestEventsBody1(v IngestEventsBody1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t IngestEventsBody) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *IngestEventsBody) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsListEntitlementsResult0 returns the union data inside the ListEntitlementsResult as a ListEntitlementsResult0 +func (t ListEntitlementsResult) AsListEntitlementsResult0() (ListEntitlementsResult0, error) { + var body ListEntitlementsResult0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromListEntitlementsResult0 overwrites any union data inside the ListEntitlementsResult as the provided ListEntitlementsResult0 +func (t *ListEntitlementsResult) FromListEntitlementsResult0(v ListEntitlementsResult0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeListEntitlementsResult0 performs a merge with any union data inside the ListEntitlementsResult, using the provided ListEntitlementsResult0 +func (t *ListEntitlementsResult) MergeListEntitlementsResult0(v ListEntitlementsResult0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementPaginatedResponse returns the union data inside the ListEntitlementsResult as a EntitlementPaginatedResponse +func (t ListEntitlementsResult) AsEntitlementPaginatedResponse() (EntitlementPaginatedResponse, error) { + var body EntitlementPaginatedResponse + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementPaginatedResponse overwrites any union data inside the ListEntitlementsResult as the provided EntitlementPaginatedResponse +func (t *ListEntitlementsResult) FromEntitlementPaginatedResponse(v EntitlementPaginatedResponse) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementPaginatedResponse performs a merge with any union data inside the ListEntitlementsResult, using the provided EntitlementPaginatedResponse +func (t *ListEntitlementsResult) MergeEntitlementPaginatedResponse(v EntitlementPaginatedResponse) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t ListEntitlementsResult) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *ListEntitlementsResult) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsListFeaturesResult0 returns the union data inside the ListFeaturesResult as a ListFeaturesResult0 +func (t ListFeaturesResult) AsListFeaturesResult0() (ListFeaturesResult0, error) { + var body ListFeaturesResult0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromListFeaturesResult0 overwrites any union data inside the ListFeaturesResult as the provided ListFeaturesResult0 +func (t *ListFeaturesResult) FromListFeaturesResult0(v ListFeaturesResult0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeListFeaturesResult0 performs a merge with any union data inside the ListFeaturesResult, using the provided ListFeaturesResult0 +func (t *ListFeaturesResult) MergeListFeaturesResult0(v ListFeaturesResult0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsFeaturePaginatedResponse returns the union data inside the ListFeaturesResult as a FeaturePaginatedResponse +func (t ListFeaturesResult) AsFeaturePaginatedResponse() (FeaturePaginatedResponse, error) { + var body FeaturePaginatedResponse + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFeaturePaginatedResponse overwrites any union data inside the ListFeaturesResult as the provided FeaturePaginatedResponse +func (t *ListFeaturesResult) FromFeaturePaginatedResponse(v FeaturePaginatedResponse) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFeaturePaginatedResponse performs a merge with any union data inside the ListFeaturesResult, using the provided FeaturePaginatedResponse +func (t *ListFeaturesResult) MergeFeaturePaginatedResponse(v FeaturePaginatedResponse) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t ListFeaturesResult) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *ListFeaturesResult) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsMeasureUsageFromPreset returns the union data inside the MeasureUsageFrom as a MeasureUsageFromPreset +func (t MeasureUsageFrom) AsMeasureUsageFromPreset() (MeasureUsageFromPreset, error) { + var body MeasureUsageFromPreset + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromMeasureUsageFromPreset overwrites any union data inside the MeasureUsageFrom as the provided MeasureUsageFromPreset +func (t *MeasureUsageFrom) FromMeasureUsageFromPreset(v MeasureUsageFromPreset) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeMeasureUsageFromPreset performs a merge with any union data inside the MeasureUsageFrom, using the provided MeasureUsageFromPreset +func (t *MeasureUsageFrom) MergeMeasureUsageFromPreset(v MeasureUsageFromPreset) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsMeasureUsageFromTime returns the union data inside the MeasureUsageFrom as a MeasureUsageFromTime +func (t MeasureUsageFrom) AsMeasureUsageFromTime() (MeasureUsageFromTime, error) { + var body MeasureUsageFromTime + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromMeasureUsageFromTime overwrites any union data inside the MeasureUsageFrom as the provided MeasureUsageFromTime +func (t *MeasureUsageFrom) FromMeasureUsageFromTime(v MeasureUsageFromTime) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeMeasureUsageFromTime performs a merge with any union data inside the MeasureUsageFrom, using the provided MeasureUsageFromTime +func (t *MeasureUsageFrom) MergeMeasureUsageFromTime(v MeasureUsageFromTime) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t MeasureUsageFrom) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *MeasureUsageFrom) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsNotificationEventResetPayload returns the union data inside the NotificationEventPayload as a NotificationEventResetPayload +func (t NotificationEventPayload) AsNotificationEventResetPayload() (NotificationEventResetPayload, error) { + var body NotificationEventResetPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventResetPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventResetPayload +func (t *NotificationEventPayload) FromNotificationEventResetPayload(v NotificationEventResetPayload) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventResetPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventResetPayload +func (t *NotificationEventPayload) MergeNotificationEventResetPayload(v NotificationEventResetPayload) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationEventBalanceThresholdPayload returns the union data inside the NotificationEventPayload as a NotificationEventBalanceThresholdPayload +func (t NotificationEventPayload) AsNotificationEventBalanceThresholdPayload() (NotificationEventBalanceThresholdPayload, error) { + var body NotificationEventBalanceThresholdPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventBalanceThresholdPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventBalanceThresholdPayload +func (t *NotificationEventPayload) FromNotificationEventBalanceThresholdPayload(v NotificationEventBalanceThresholdPayload) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventBalanceThresholdPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventBalanceThresholdPayload +func (t *NotificationEventPayload) MergeNotificationEventBalanceThresholdPayload(v NotificationEventBalanceThresholdPayload) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationEventInvoiceCreatedPayload returns the union data inside the NotificationEventPayload as a NotificationEventInvoiceCreatedPayload +func (t NotificationEventPayload) AsNotificationEventInvoiceCreatedPayload() (NotificationEventInvoiceCreatedPayload, error) { + var body NotificationEventInvoiceCreatedPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventInvoiceCreatedPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventInvoiceCreatedPayload +func (t *NotificationEventPayload) FromNotificationEventInvoiceCreatedPayload(v NotificationEventInvoiceCreatedPayload) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventInvoiceCreatedPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventInvoiceCreatedPayload +func (t *NotificationEventPayload) MergeNotificationEventInvoiceCreatedPayload(v NotificationEventInvoiceCreatedPayload) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationEventInvoiceUpdatedPayload returns the union data inside the NotificationEventPayload as a NotificationEventInvoiceUpdatedPayload +func (t NotificationEventPayload) AsNotificationEventInvoiceUpdatedPayload() (NotificationEventInvoiceUpdatedPayload, error) { + var body NotificationEventInvoiceUpdatedPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventInvoiceUpdatedPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventInvoiceUpdatedPayload +func (t *NotificationEventPayload) FromNotificationEventInvoiceUpdatedPayload(v NotificationEventInvoiceUpdatedPayload) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventInvoiceUpdatedPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventInvoiceUpdatedPayload +func (t *NotificationEventPayload) MergeNotificationEventInvoiceUpdatedPayload(v NotificationEventInvoiceUpdatedPayload) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t NotificationEventPayload) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t NotificationEventPayload) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "entitlements.balance.threshold": + return t.AsNotificationEventBalanceThresholdPayload() + case "entitlements.reset": + return t.AsNotificationEventResetPayload() + case "invoice.created": + return t.AsNotificationEventInvoiceCreatedPayload() + case "invoice.updated": + return t.AsNotificationEventInvoiceUpdatedPayload() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t NotificationEventPayload) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *NotificationEventPayload) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsNotificationRuleBalanceThreshold returns the union data inside the NotificationRule as a NotificationRuleBalanceThreshold +func (t NotificationRule) AsNotificationRuleBalanceThreshold() (NotificationRuleBalanceThreshold, error) { + var body NotificationRuleBalanceThreshold + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleBalanceThreshold overwrites any union data inside the NotificationRule as the provided NotificationRuleBalanceThreshold +func (t *NotificationRule) FromNotificationRuleBalanceThreshold(v NotificationRuleBalanceThreshold) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleBalanceThreshold performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleBalanceThreshold +func (t *NotificationRule) MergeNotificationRuleBalanceThreshold(v NotificationRuleBalanceThreshold) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleEntitlementReset returns the union data inside the NotificationRule as a NotificationRuleEntitlementReset +func (t NotificationRule) AsNotificationRuleEntitlementReset() (NotificationRuleEntitlementReset, error) { + var body NotificationRuleEntitlementReset + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleEntitlementReset overwrites any union data inside the NotificationRule as the provided NotificationRuleEntitlementReset +func (t *NotificationRule) FromNotificationRuleEntitlementReset(v NotificationRuleEntitlementReset) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleEntitlementReset performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleEntitlementReset +func (t *NotificationRule) MergeNotificationRuleEntitlementReset(v NotificationRuleEntitlementReset) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceCreated returns the union data inside the NotificationRule as a NotificationRuleInvoiceCreated +func (t NotificationRule) AsNotificationRuleInvoiceCreated() (NotificationRuleInvoiceCreated, error) { + var body NotificationRuleInvoiceCreated + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceCreated overwrites any union data inside the NotificationRule as the provided NotificationRuleInvoiceCreated +func (t *NotificationRule) FromNotificationRuleInvoiceCreated(v NotificationRuleInvoiceCreated) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceCreated performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleInvoiceCreated +func (t *NotificationRule) MergeNotificationRuleInvoiceCreated(v NotificationRuleInvoiceCreated) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceUpdated returns the union data inside the NotificationRule as a NotificationRuleInvoiceUpdated +func (t NotificationRule) AsNotificationRuleInvoiceUpdated() (NotificationRuleInvoiceUpdated, error) { + var body NotificationRuleInvoiceUpdated + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceUpdated overwrites any union data inside the NotificationRule as the provided NotificationRuleInvoiceUpdated +func (t *NotificationRule) FromNotificationRuleInvoiceUpdated(v NotificationRuleInvoiceUpdated) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceUpdated performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleInvoiceUpdated +func (t *NotificationRule) MergeNotificationRuleInvoiceUpdated(v NotificationRuleInvoiceUpdated) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t NotificationRule) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t NotificationRule) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "entitlements.balance.threshold": + return t.AsNotificationRuleBalanceThreshold() + case "entitlements.reset": + return t.AsNotificationRuleEntitlementReset() + case "invoice.created": + return t.AsNotificationRuleInvoiceCreated() + case "invoice.updated": + return t.AsNotificationRuleInvoiceUpdated() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t NotificationRule) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *NotificationRule) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsNotificationRuleBalanceThresholdCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleBalanceThresholdCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleBalanceThresholdCreateRequest() (NotificationRuleBalanceThresholdCreateRequest, error) { + var body NotificationRuleBalanceThresholdCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleBalanceThresholdCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleBalanceThresholdCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleBalanceThresholdCreateRequest(v NotificationRuleBalanceThresholdCreateRequest) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleBalanceThresholdCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleBalanceThresholdCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleBalanceThresholdCreateRequest(v NotificationRuleBalanceThresholdCreateRequest) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleEntitlementResetCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleEntitlementResetCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleEntitlementResetCreateRequest() (NotificationRuleEntitlementResetCreateRequest, error) { + var body NotificationRuleEntitlementResetCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleEntitlementResetCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleEntitlementResetCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleEntitlementResetCreateRequest(v NotificationRuleEntitlementResetCreateRequest) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleEntitlementResetCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleEntitlementResetCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleEntitlementResetCreateRequest(v NotificationRuleEntitlementResetCreateRequest) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceCreatedCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleInvoiceCreatedCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleInvoiceCreatedCreateRequest() (NotificationRuleInvoiceCreatedCreateRequest, error) { + var body NotificationRuleInvoiceCreatedCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceCreatedCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleInvoiceCreatedCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleInvoiceCreatedCreateRequest(v NotificationRuleInvoiceCreatedCreateRequest) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceCreatedCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleInvoiceCreatedCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleInvoiceCreatedCreateRequest(v NotificationRuleInvoiceCreatedCreateRequest) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceUpdatedCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleInvoiceUpdatedCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleInvoiceUpdatedCreateRequest() (NotificationRuleInvoiceUpdatedCreateRequest, error) { + var body NotificationRuleInvoiceUpdatedCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceUpdatedCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleInvoiceUpdatedCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleInvoiceUpdatedCreateRequest(v NotificationRuleInvoiceUpdatedCreateRequest) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceUpdatedCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleInvoiceUpdatedCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleInvoiceUpdatedCreateRequest(v NotificationRuleInvoiceUpdatedCreateRequest) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t NotificationRuleCreateRequest) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t NotificationRuleCreateRequest) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "entitlements.balance.threshold": + return t.AsNotificationRuleBalanceThresholdCreateRequest() + case "entitlements.reset": + return t.AsNotificationRuleEntitlementResetCreateRequest() + case "invoice.created": + return t.AsNotificationRuleInvoiceCreatedCreateRequest() + case "invoice.updated": + return t.AsNotificationRuleInvoiceUpdatedCreateRequest() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t NotificationRuleCreateRequest) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *NotificationRuleCreateRequest) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsPaymentTermInstant returns the union data inside the PaymentTerms as a PaymentTermInstant +func (t PaymentTerms) AsPaymentTermInstant() (PaymentTermInstant, error) { + var body PaymentTermInstant + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPaymentTermInstant overwrites any union data inside the PaymentTerms as the provided PaymentTermInstant +func (t *PaymentTerms) FromPaymentTermInstant(v PaymentTermInstant) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePaymentTermInstant performs a merge with any union data inside the PaymentTerms, using the provided PaymentTermInstant +func (t *PaymentTerms) MergePaymentTermInstant(v PaymentTermInstant) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPaymentTermDueDate returns the union data inside the PaymentTerms as a PaymentTermDueDate +func (t PaymentTerms) AsPaymentTermDueDate() (PaymentTermDueDate, error) { + var body PaymentTermDueDate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPaymentTermDueDate overwrites any union data inside the PaymentTerms as the provided PaymentTermDueDate +func (t *PaymentTerms) FromPaymentTermDueDate(v PaymentTermDueDate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePaymentTermDueDate performs a merge with any union data inside the PaymentTerms, using the provided PaymentTermDueDate +func (t *PaymentTerms) MergePaymentTermDueDate(v PaymentTermDueDate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t PaymentTerms) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *PaymentTerms) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsFlatPrice returns the union data inside the Price as a FlatPrice +func (t Price) AsFlatPrice() (FlatPrice, error) { + var body FlatPrice + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFlatPrice overwrites any union data inside the Price as the provided FlatPrice +func (t *Price) FromFlatPrice(v FlatPrice) error { + v.Type = "flat" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFlatPrice performs a merge with any union data inside the Price, using the provided FlatPrice +func (t *Price) MergeFlatPrice(v FlatPrice) error { + v.Type = "flat" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsUnitPrice returns the union data inside the Price as a UnitPrice +func (t Price) AsUnitPrice() (UnitPrice, error) { + var body UnitPrice + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromUnitPrice overwrites any union data inside the Price as the provided UnitPrice +func (t *Price) FromUnitPrice(v UnitPrice) error { + v.Type = "unit" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeUnitPrice performs a merge with any union data inside the Price, using the provided UnitPrice +func (t *Price) MergeUnitPrice(v UnitPrice) error { + v.Type = "unit" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsTieredPrice returns the union data inside the Price as a TieredPrice +func (t Price) AsTieredPrice() (TieredPrice, error) { + var body TieredPrice + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromTieredPrice overwrites any union data inside the Price as the provided TieredPrice +func (t *Price) FromTieredPrice(v TieredPrice) error { + v.Type = "tiered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeTieredPrice performs a merge with any union data inside the Price, using the provided TieredPrice +func (t *Price) MergeTieredPrice(v TieredPrice) error { + v.Type = "tiered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDynamicPrice returns the union data inside the Price as a DynamicPrice +func (t Price) AsDynamicPrice() (DynamicPrice, error) { + var body DynamicPrice + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDynamicPrice overwrites any union data inside the Price as the provided DynamicPrice +func (t *Price) FromDynamicPrice(v DynamicPrice) error { + v.Type = "dynamic" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDynamicPrice performs a merge with any union data inside the Price, using the provided DynamicPrice +func (t *Price) MergeDynamicPrice(v DynamicPrice) error { + v.Type = "dynamic" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPackagePrice returns the union data inside the Price as a PackagePrice +func (t Price) AsPackagePrice() (PackagePrice, error) { + var body PackagePrice + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPackagePrice overwrites any union data inside the Price as the provided PackagePrice +func (t *Price) FromPackagePrice(v PackagePrice) error { + v.Type = "package" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePackagePrice performs a merge with any union data inside the Price, using the provided PackagePrice +func (t *Price) MergePackagePrice(v PackagePrice) error { + v.Type = "package" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t Price) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t Price) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "dynamic": + return t.AsDynamicPrice() + case "flat": + return t.AsFlatPrice() + case "package": + return t.AsPackagePrice() + case "tiered": + return t.AsTieredPrice() + case "unit": + return t.AsUnitPrice() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t Price) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *Price) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsRateCardFlatFee returns the union data inside the RateCard as a RateCardFlatFee +func (t RateCard) AsRateCardFlatFee() (RateCardFlatFee, error) { + var body RateCardFlatFee + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardFlatFee overwrites any union data inside the RateCard as the provided RateCardFlatFee +func (t *RateCard) FromRateCardFlatFee(v RateCardFlatFee) error { + v.Type = "flat_fee" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardFlatFee performs a merge with any union data inside the RateCard, using the provided RateCardFlatFee +func (t *RateCard) MergeRateCardFlatFee(v RateCardFlatFee) error { + v.Type = "flat_fee" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRateCardUsageBased returns the union data inside the RateCard as a RateCardUsageBased +func (t RateCard) AsRateCardUsageBased() (RateCardUsageBased, error) { + var body RateCardUsageBased + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardUsageBased overwrites any union data inside the RateCard as the provided RateCardUsageBased +func (t *RateCard) FromRateCardUsageBased(v RateCardUsageBased) error { + v.Type = "usage_based" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardUsageBased performs a merge with any union data inside the RateCard, using the provided RateCardUsageBased +func (t *RateCard) MergeRateCardUsageBased(v RateCardUsageBased) error { + v.Type = "usage_based" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RateCard) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t RateCard) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "flat_fee": + return t.AsRateCardFlatFee() + case "usage_based": + return t.AsRateCardUsageBased() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t RateCard) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RateCard) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsRateCardMeteredEntitlement returns the union data inside the RateCardEntitlement as a RateCardMeteredEntitlement +func (t RateCardEntitlement) AsRateCardMeteredEntitlement() (RateCardMeteredEntitlement, error) { + var body RateCardMeteredEntitlement + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardMeteredEntitlement overwrites any union data inside the RateCardEntitlement as the provided RateCardMeteredEntitlement +func (t *RateCardEntitlement) FromRateCardMeteredEntitlement(v RateCardMeteredEntitlement) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardMeteredEntitlement performs a merge with any union data inside the RateCardEntitlement, using the provided RateCardMeteredEntitlement +func (t *RateCardEntitlement) MergeRateCardMeteredEntitlement(v RateCardMeteredEntitlement) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRateCardStaticEntitlement returns the union data inside the RateCardEntitlement as a RateCardStaticEntitlement +func (t RateCardEntitlement) AsRateCardStaticEntitlement() (RateCardStaticEntitlement, error) { + var body RateCardStaticEntitlement + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardStaticEntitlement overwrites any union data inside the RateCardEntitlement as the provided RateCardStaticEntitlement +func (t *RateCardEntitlement) FromRateCardStaticEntitlement(v RateCardStaticEntitlement) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardStaticEntitlement performs a merge with any union data inside the RateCardEntitlement, using the provided RateCardStaticEntitlement +func (t *RateCardEntitlement) MergeRateCardStaticEntitlement(v RateCardStaticEntitlement) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRateCardBooleanEntitlement returns the union data inside the RateCardEntitlement as a RateCardBooleanEntitlement +func (t RateCardEntitlement) AsRateCardBooleanEntitlement() (RateCardBooleanEntitlement, error) { + var body RateCardBooleanEntitlement + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardBooleanEntitlement overwrites any union data inside the RateCardEntitlement as the provided RateCardBooleanEntitlement +func (t *RateCardEntitlement) FromRateCardBooleanEntitlement(v RateCardBooleanEntitlement) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardBooleanEntitlement performs a merge with any union data inside the RateCardEntitlement, using the provided RateCardBooleanEntitlement +func (t *RateCardEntitlement) MergeRateCardBooleanEntitlement(v RateCardBooleanEntitlement) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RateCardEntitlement) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t RateCardEntitlement) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsRateCardBooleanEntitlement() + case "metered": + return t.AsRateCardMeteredEntitlement() + case "static": + return t.AsRateCardStaticEntitlement() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t RateCardEntitlement) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RateCardEntitlement) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsFlatPriceWithPaymentTerm returns the union data inside the RateCardUsageBasedPrice as a FlatPriceWithPaymentTerm +func (t RateCardUsageBasedPrice) AsFlatPriceWithPaymentTerm() (FlatPriceWithPaymentTerm, error) { + var body FlatPriceWithPaymentTerm + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFlatPriceWithPaymentTerm overwrites any union data inside the RateCardUsageBasedPrice as the provided FlatPriceWithPaymentTerm +func (t *RateCardUsageBasedPrice) FromFlatPriceWithPaymentTerm(v FlatPriceWithPaymentTerm) error { + v.Type = "flat" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFlatPriceWithPaymentTerm performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided FlatPriceWithPaymentTerm +func (t *RateCardUsageBasedPrice) MergeFlatPriceWithPaymentTerm(v FlatPriceWithPaymentTerm) error { + v.Type = "flat" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsUnitPriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a UnitPriceWithCommitments +func (t RateCardUsageBasedPrice) AsUnitPriceWithCommitments() (UnitPriceWithCommitments, error) { + var body UnitPriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromUnitPriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided UnitPriceWithCommitments +func (t *RateCardUsageBasedPrice) FromUnitPriceWithCommitments(v UnitPriceWithCommitments) error { + v.Type = "unit" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeUnitPriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided UnitPriceWithCommitments +func (t *RateCardUsageBasedPrice) MergeUnitPriceWithCommitments(v UnitPriceWithCommitments) error { + v.Type = "unit" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsTieredPriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a TieredPriceWithCommitments +func (t RateCardUsageBasedPrice) AsTieredPriceWithCommitments() (TieredPriceWithCommitments, error) { + var body TieredPriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromTieredPriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided TieredPriceWithCommitments +func (t *RateCardUsageBasedPrice) FromTieredPriceWithCommitments(v TieredPriceWithCommitments) error { + v.Type = "tiered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeTieredPriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided TieredPriceWithCommitments +func (t *RateCardUsageBasedPrice) MergeTieredPriceWithCommitments(v TieredPriceWithCommitments) error { + v.Type = "tiered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDynamicPriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a DynamicPriceWithCommitments +func (t RateCardUsageBasedPrice) AsDynamicPriceWithCommitments() (DynamicPriceWithCommitments, error) { + var body DynamicPriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDynamicPriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided DynamicPriceWithCommitments +func (t *RateCardUsageBasedPrice) FromDynamicPriceWithCommitments(v DynamicPriceWithCommitments) error { + v.Type = "dynamic" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDynamicPriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided DynamicPriceWithCommitments +func (t *RateCardUsageBasedPrice) MergeDynamicPriceWithCommitments(v DynamicPriceWithCommitments) error { + v.Type = "dynamic" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPackagePriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a PackagePriceWithCommitments +func (t RateCardUsageBasedPrice) AsPackagePriceWithCommitments() (PackagePriceWithCommitments, error) { + var body PackagePriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPackagePriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided PackagePriceWithCommitments +func (t *RateCardUsageBasedPrice) FromPackagePriceWithCommitments(v PackagePriceWithCommitments) error { + v.Type = "package" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePackagePriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided PackagePriceWithCommitments +func (t *RateCardUsageBasedPrice) MergePackagePriceWithCommitments(v PackagePriceWithCommitments) error { + v.Type = "package" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RateCardUsageBasedPrice) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t RateCardUsageBasedPrice) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "dynamic": + return t.AsDynamicPriceWithCommitments() + case "flat": + return t.AsFlatPriceWithPaymentTerm() + case "package": + return t.AsPackagePriceWithCommitments() + case "tiered": + return t.AsTieredPriceWithCommitments() + case "unit": + return t.AsUnitPriceWithCommitments() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t RateCardUsageBasedPrice) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RateCardUsageBasedPrice) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsRecurringPeriodInterval0 returns the union data inside the RecurringPeriodInterval as a RecurringPeriodInterval0 +func (t RecurringPeriodInterval) AsRecurringPeriodInterval0() (RecurringPeriodInterval0, error) { + var body RecurringPeriodInterval0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRecurringPeriodInterval0 overwrites any union data inside the RecurringPeriodInterval as the provided RecurringPeriodInterval0 +func (t *RecurringPeriodInterval) FromRecurringPeriodInterval0(v RecurringPeriodInterval0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRecurringPeriodInterval0 performs a merge with any union data inside the RecurringPeriodInterval, using the provided RecurringPeriodInterval0 +func (t *RecurringPeriodInterval) MergeRecurringPeriodInterval0(v RecurringPeriodInterval0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRecurringPeriodIntervalEnum returns the union data inside the RecurringPeriodInterval as a RecurringPeriodIntervalEnum +func (t RecurringPeriodInterval) AsRecurringPeriodIntervalEnum() (RecurringPeriodIntervalEnum, error) { + var body RecurringPeriodIntervalEnum + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRecurringPeriodIntervalEnum overwrites any union data inside the RecurringPeriodInterval as the provided RecurringPeriodIntervalEnum +func (t *RecurringPeriodInterval) FromRecurringPeriodIntervalEnum(v RecurringPeriodIntervalEnum) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRecurringPeriodIntervalEnum performs a merge with any union data inside the RecurringPeriodInterval, using the provided RecurringPeriodIntervalEnum +func (t *RecurringPeriodInterval) MergeRecurringPeriodIntervalEnum(v RecurringPeriodIntervalEnum) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RecurringPeriodInterval) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RecurringPeriodInterval) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsPlanSubscriptionChange returns the union data inside the SubscriptionChange as a PlanSubscriptionChange +func (t SubscriptionChange) AsPlanSubscriptionChange() (PlanSubscriptionChange, error) { + var body PlanSubscriptionChange + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPlanSubscriptionChange overwrites any union data inside the SubscriptionChange as the provided PlanSubscriptionChange +func (t *SubscriptionChange) FromPlanSubscriptionChange(v PlanSubscriptionChange) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePlanSubscriptionChange performs a merge with any union data inside the SubscriptionChange, using the provided PlanSubscriptionChange +func (t *SubscriptionChange) MergePlanSubscriptionChange(v PlanSubscriptionChange) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomSubscriptionChange returns the union data inside the SubscriptionChange as a CustomSubscriptionChange +func (t SubscriptionChange) AsCustomSubscriptionChange() (CustomSubscriptionChange, error) { + var body CustomSubscriptionChange + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomSubscriptionChange overwrites any union data inside the SubscriptionChange as the provided CustomSubscriptionChange +func (t *SubscriptionChange) FromCustomSubscriptionChange(v CustomSubscriptionChange) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomSubscriptionChange performs a merge with any union data inside the SubscriptionChange, using the provided CustomSubscriptionChange +func (t *SubscriptionChange) MergeCustomSubscriptionChange(v CustomSubscriptionChange) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionChange) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionChange) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsPlanSubscriptionCreate returns the union data inside the SubscriptionCreate as a PlanSubscriptionCreate +func (t SubscriptionCreate) AsPlanSubscriptionCreate() (PlanSubscriptionCreate, error) { + var body PlanSubscriptionCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPlanSubscriptionCreate overwrites any union data inside the SubscriptionCreate as the provided PlanSubscriptionCreate +func (t *SubscriptionCreate) FromPlanSubscriptionCreate(v PlanSubscriptionCreate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePlanSubscriptionCreate performs a merge with any union data inside the SubscriptionCreate, using the provided PlanSubscriptionCreate +func (t *SubscriptionCreate) MergePlanSubscriptionCreate(v PlanSubscriptionCreate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomSubscriptionCreate returns the union data inside the SubscriptionCreate as a CustomSubscriptionCreate +func (t SubscriptionCreate) AsCustomSubscriptionCreate() (CustomSubscriptionCreate, error) { + var body CustomSubscriptionCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomSubscriptionCreate overwrites any union data inside the SubscriptionCreate as the provided CustomSubscriptionCreate +func (t *SubscriptionCreate) FromCustomSubscriptionCreate(v CustomSubscriptionCreate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomSubscriptionCreate performs a merge with any union data inside the SubscriptionCreate, using the provided CustomSubscriptionCreate +func (t *SubscriptionCreate) MergeCustomSubscriptionCreate(v CustomSubscriptionCreate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionCreate) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionCreate) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEditSubscriptionAddItem returns the union data inside the SubscriptionEditOperation as a EditSubscriptionAddItem +func (t SubscriptionEditOperation) AsEditSubscriptionAddItem() (EditSubscriptionAddItem, error) { + var body EditSubscriptionAddItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionAddItem overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionAddItem +func (t *SubscriptionEditOperation) FromEditSubscriptionAddItem(v EditSubscriptionAddItem) error { + v.Op = "add_item" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionAddItem performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionAddItem +func (t *SubscriptionEditOperation) MergeEditSubscriptionAddItem(v EditSubscriptionAddItem) error { + v.Op = "add_item" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionRemoveItem returns the union data inside the SubscriptionEditOperation as a EditSubscriptionRemoveItem +func (t SubscriptionEditOperation) AsEditSubscriptionRemoveItem() (EditSubscriptionRemoveItem, error) { + var body EditSubscriptionRemoveItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionRemoveItem overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionRemoveItem +func (t *SubscriptionEditOperation) FromEditSubscriptionRemoveItem(v EditSubscriptionRemoveItem) error { + v.Op = "remove_item" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionRemoveItem performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionRemoveItem +func (t *SubscriptionEditOperation) MergeEditSubscriptionRemoveItem(v EditSubscriptionRemoveItem) error { + v.Op = "remove_item" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionAddPhase returns the union data inside the SubscriptionEditOperation as a EditSubscriptionAddPhase +func (t SubscriptionEditOperation) AsEditSubscriptionAddPhase() (EditSubscriptionAddPhase, error) { + var body EditSubscriptionAddPhase + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionAddPhase overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionAddPhase +func (t *SubscriptionEditOperation) FromEditSubscriptionAddPhase(v EditSubscriptionAddPhase) error { + v.Op = "add_phase" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionAddPhase performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionAddPhase +func (t *SubscriptionEditOperation) MergeEditSubscriptionAddPhase(v EditSubscriptionAddPhase) error { + v.Op = "add_phase" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionRemovePhase returns the union data inside the SubscriptionEditOperation as a EditSubscriptionRemovePhase +func (t SubscriptionEditOperation) AsEditSubscriptionRemovePhase() (EditSubscriptionRemovePhase, error) { + var body EditSubscriptionRemovePhase + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionRemovePhase overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionRemovePhase +func (t *SubscriptionEditOperation) FromEditSubscriptionRemovePhase(v EditSubscriptionRemovePhase) error { + v.Op = "remove_phase" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionRemovePhase performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionRemovePhase +func (t *SubscriptionEditOperation) MergeEditSubscriptionRemovePhase(v EditSubscriptionRemovePhase) error { + v.Op = "remove_phase" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionStretchPhase returns the union data inside the SubscriptionEditOperation as a EditSubscriptionStretchPhase +func (t SubscriptionEditOperation) AsEditSubscriptionStretchPhase() (EditSubscriptionStretchPhase, error) { + var body EditSubscriptionStretchPhase + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionStretchPhase overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionStretchPhase +func (t *SubscriptionEditOperation) FromEditSubscriptionStretchPhase(v EditSubscriptionStretchPhase) error { + v.Op = "stretch_phase" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionStretchPhase performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionStretchPhase +func (t *SubscriptionEditOperation) MergeEditSubscriptionStretchPhase(v EditSubscriptionStretchPhase) error { + v.Op = "stretch_phase" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionUnscheduleEdit returns the union data inside the SubscriptionEditOperation as a EditSubscriptionUnscheduleEdit +func (t SubscriptionEditOperation) AsEditSubscriptionUnscheduleEdit() (EditSubscriptionUnscheduleEdit, error) { + var body EditSubscriptionUnscheduleEdit + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionUnscheduleEdit overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionUnscheduleEdit +func (t *SubscriptionEditOperation) FromEditSubscriptionUnscheduleEdit(v EditSubscriptionUnscheduleEdit) error { + v.Op = "unschedule_edit" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionUnscheduleEdit performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionUnscheduleEdit +func (t *SubscriptionEditOperation) MergeEditSubscriptionUnscheduleEdit(v EditSubscriptionUnscheduleEdit) error { + v.Op = "unschedule_edit" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionEditOperation) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"op"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t SubscriptionEditOperation) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "add_item": + return t.AsEditSubscriptionAddItem() + case "add_phase": + return t.AsEditSubscriptionAddPhase() + case "remove_item": + return t.AsEditSubscriptionRemoveItem() + case "remove_phase": + return t.AsEditSubscriptionRemovePhase() + case "stretch_phase": + return t.AsEditSubscriptionStretchPhase() + case "unschedule_edit": + return t.AsEditSubscriptionUnscheduleEdit() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t SubscriptionEditOperation) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionEditOperation) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsSubscriptionTimingEnum returns the union data inside the SubscriptionTiming as a SubscriptionTimingEnum +func (t SubscriptionTiming) AsSubscriptionTimingEnum() (SubscriptionTimingEnum, error) { + var body SubscriptionTimingEnum + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSubscriptionTimingEnum overwrites any union data inside the SubscriptionTiming as the provided SubscriptionTimingEnum +func (t *SubscriptionTiming) FromSubscriptionTimingEnum(v SubscriptionTimingEnum) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSubscriptionTimingEnum performs a merge with any union data inside the SubscriptionTiming, using the provided SubscriptionTimingEnum +func (t *SubscriptionTiming) MergeSubscriptionTimingEnum(v SubscriptionTimingEnum) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSubscriptionTiming1 returns the union data inside the SubscriptionTiming as a SubscriptionTiming1 +func (t SubscriptionTiming) AsSubscriptionTiming1() (SubscriptionTiming1, error) { + var body SubscriptionTiming1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSubscriptionTiming1 overwrites any union data inside the SubscriptionTiming as the provided SubscriptionTiming1 +func (t *SubscriptionTiming) FromSubscriptionTiming1(v SubscriptionTiming1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSubscriptionTiming1 performs a merge with any union data inside the SubscriptionTiming, using the provided SubscriptionTiming1 +func (t *SubscriptionTiming) MergeSubscriptionTiming1(v SubscriptionTiming1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionTiming) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionTiming) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsVoidInvoiceLineDiscardAction returns the union data inside the VoidInvoiceLineActionCreate as a VoidInvoiceLineDiscardAction +func (t VoidInvoiceLineActionCreate) AsVoidInvoiceLineDiscardAction() (VoidInvoiceLineDiscardAction, error) { + var body VoidInvoiceLineDiscardAction + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLineDiscardAction overwrites any union data inside the VoidInvoiceLineActionCreate as the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreate) FromVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLineDiscardAction performs a merge with any union data inside the VoidInvoiceLineActionCreate, using the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreate) MergeVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVoidInvoiceLinePendingActionCreate returns the union data inside the VoidInvoiceLineActionCreate as a VoidInvoiceLinePendingActionCreate +func (t VoidInvoiceLineActionCreate) AsVoidInvoiceLinePendingActionCreate() (VoidInvoiceLinePendingActionCreate, error) { + var body VoidInvoiceLinePendingActionCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLinePendingActionCreate overwrites any union data inside the VoidInvoiceLineActionCreate as the provided VoidInvoiceLinePendingActionCreate +func (t *VoidInvoiceLineActionCreate) FromVoidInvoiceLinePendingActionCreate(v VoidInvoiceLinePendingActionCreate) error { + v.Type = "pending" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLinePendingActionCreate performs a merge with any union data inside the VoidInvoiceLineActionCreate, using the provided VoidInvoiceLinePendingActionCreate +func (t *VoidInvoiceLineActionCreate) MergeVoidInvoiceLinePendingActionCreate(v VoidInvoiceLinePendingActionCreate) error { + v.Type = "pending" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t VoidInvoiceLineActionCreate) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t VoidInvoiceLineActionCreate) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "discard": + return t.AsVoidInvoiceLineDiscardAction() + case "pending": + return t.AsVoidInvoiceLinePendingActionCreate() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t VoidInvoiceLineActionCreate) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *VoidInvoiceLineActionCreate) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsVoidInvoiceLineDiscardAction returns the union data inside the VoidInvoiceLineActionCreateItem as a VoidInvoiceLineDiscardAction +func (t VoidInvoiceLineActionCreateItem) AsVoidInvoiceLineDiscardAction() (VoidInvoiceLineDiscardAction, error) { + var body VoidInvoiceLineDiscardAction + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLineDiscardAction overwrites any union data inside the VoidInvoiceLineActionCreateItem as the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreateItem) FromVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLineDiscardAction performs a merge with any union data inside the VoidInvoiceLineActionCreateItem, using the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreateItem) MergeVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVoidInvoiceLinePendingActionCreateItem returns the union data inside the VoidInvoiceLineActionCreateItem as a VoidInvoiceLinePendingActionCreateItem +func (t VoidInvoiceLineActionCreateItem) AsVoidInvoiceLinePendingActionCreateItem() (VoidInvoiceLinePendingActionCreateItem, error) { + var body VoidInvoiceLinePendingActionCreateItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLinePendingActionCreateItem overwrites any union data inside the VoidInvoiceLineActionCreateItem as the provided VoidInvoiceLinePendingActionCreateItem +func (t *VoidInvoiceLineActionCreateItem) FromVoidInvoiceLinePendingActionCreateItem(v VoidInvoiceLinePendingActionCreateItem) error { + v.Type = "pending" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLinePendingActionCreateItem performs a merge with any union data inside the VoidInvoiceLineActionCreateItem, using the provided VoidInvoiceLinePendingActionCreateItem +func (t *VoidInvoiceLineActionCreateItem) MergeVoidInvoiceLinePendingActionCreateItem(v VoidInvoiceLinePendingActionCreateItem) error { + v.Type = "pending" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t VoidInvoiceLineActionCreateItem) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t VoidInvoiceLineActionCreateItem) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "discard": + return t.AsVoidInvoiceLineDiscardAction() + case "pending": + return t.AsVoidInvoiceLinePendingActionCreateItem() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t VoidInvoiceLineActionCreateItem) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *VoidInvoiceLineActionCreateItem) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + // List add-ons + // (GET /api/v1/addons) + ListAddons(w http.ResponseWriter, r *http.Request, params ListAddonsParams) + // Create an add-on + // (POST /api/v1/addons) + CreateAddon(w http.ResponseWriter, r *http.Request) + // Delete add-on + // (DELETE /api/v1/addons/{addonId}) + DeleteAddon(w http.ResponseWriter, r *http.Request, addonId string) + // Get add-on + // (GET /api/v1/addons/{addonId}) + GetAddon(w http.ResponseWriter, r *http.Request, addonId string, params GetAddonParams) + // Update add-on + // (PUT /api/v1/addons/{addonId}) + UpdateAddon(w http.ResponseWriter, r *http.Request, addonId string) + // Archive add-on version + // (POST /api/v1/addons/{addonId}/archive) + ArchiveAddon(w http.ResponseWriter, r *http.Request, addonId string) + // Publish add-on + // (POST /api/v1/addons/{addonId}/publish) + PublishAddon(w http.ResponseWriter, r *http.Request, addonId string) + // List apps + // (GET /api/v1/apps) + ListApps(w http.ResponseWriter, r *http.Request, params ListAppsParams) + // Submit draft synchronization results + // (POST /api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized) + AppCustomInvoicingDraftSynchronized(w http.ResponseWriter, r *http.Request, invoiceId string) + // Submit issuing synchronization results + // (POST /api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized) + AppCustomInvoicingIssuingSynchronized(w http.ResponseWriter, r *http.Request, invoiceId string) + // Update payment status + // (POST /api/v1/apps/custom-invoicing/{invoiceId}/payment/status) + AppCustomInvoicingUpdatePaymentStatus(w http.ResponseWriter, r *http.Request, invoiceId string) + // Uninstall app + // (DELETE /api/v1/apps/{id}) + UninstallApp(w http.ResponseWriter, r *http.Request, id string) + // Get app + // (GET /api/v1/apps/{id}) + GetApp(w http.ResponseWriter, r *http.Request, id string) + // Update app + // (PUT /api/v1/apps/{id}) + UpdateApp(w http.ResponseWriter, r *http.Request, id string) + // Update Stripe API key + // (PUT /api/v1/apps/{id}/stripe/api-key) + UpdateStripeAPIKey(w http.ResponseWriter, r *http.Request, id string) + // Stripe webhook + // (POST /api/v1/apps/{id}/stripe/webhook) + AppStripeWebhook(w http.ResponseWriter, r *http.Request, id string) + // List customer overrides + // (GET /api/v1/billing/customers) + ListBillingProfileCustomerOverrides(w http.ResponseWriter, r *http.Request, params ListBillingProfileCustomerOverridesParams) + // Delete a customer override + // (DELETE /api/v1/billing/customers/{customerId}) + DeleteBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request, customerId string) + // Get a customer override + // (GET /api/v1/billing/customers/{customerId}) + GetBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request, customerId string, params GetBillingProfileCustomerOverrideParams) + // Create a new or update a customer override + // (PUT /api/v1/billing/customers/{customerId}) + UpsertBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request, customerId string) + // Create pending line items + // (POST /api/v1/billing/customers/{customerId}/invoices/pending-lines) + CreatePendingInvoiceLine(w http.ResponseWriter, r *http.Request, customerId string) + // Simulate an invoice for a customer + // (POST /api/v1/billing/customers/{customerId}/invoices/simulate) + SimulateInvoice(w http.ResponseWriter, r *http.Request, customerId string) + // List invoices + // (GET /api/v1/billing/invoices) + ListInvoices(w http.ResponseWriter, r *http.Request, params ListInvoicesParams) + // Invoice a customer based on the pending line items + // (POST /api/v1/billing/invoices/invoice) + InvoicePendingLinesAction(w http.ResponseWriter, r *http.Request) + // Delete an invoice + // (DELETE /api/v1/billing/invoices/{invoiceId}) + DeleteInvoice(w http.ResponseWriter, r *http.Request, invoiceId string) + // Get an invoice + // (GET /api/v1/billing/invoices/{invoiceId}) + GetInvoice(w http.ResponseWriter, r *http.Request, invoiceId string, params GetInvoiceParams) + // Update an invoice + // (PUT /api/v1/billing/invoices/{invoiceId}) + UpdateInvoice(w http.ResponseWriter, r *http.Request, invoiceId string) + // Advance the invoice's state to the next status + // (POST /api/v1/billing/invoices/{invoiceId}/advance) + AdvanceInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) + // Send the invoice to the customer + // (POST /api/v1/billing/invoices/{invoiceId}/approve) + ApproveInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) + // Retry advancing the invoice after a failed attempt. + // (POST /api/v1/billing/invoices/{invoiceId}/retry) + RetryInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) + // Snapshot quantities for usage based line items + // (POST /api/v1/billing/invoices/{invoiceId}/snapshot-quantities) + SnapshotQuantitiesInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) + // Recalculate an invoice's tax amounts + // (POST /api/v1/billing/invoices/{invoiceId}/taxes/recalculate) + RecalculateInvoiceTaxAction(w http.ResponseWriter, r *http.Request, invoiceId string) + // Void an invoice + // (POST /api/v1/billing/invoices/{invoiceId}/void) + VoidInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) + // List billing profiles + // (GET /api/v1/billing/profiles) + ListBillingProfiles(w http.ResponseWriter, r *http.Request, params ListBillingProfilesParams) + // Create a new billing profile + // (POST /api/v1/billing/profiles) + CreateBillingProfile(w http.ResponseWriter, r *http.Request) + // Delete a billing profile + // (DELETE /api/v1/billing/profiles/{id}) + DeleteBillingProfile(w http.ResponseWriter, r *http.Request, id string) + // Get a billing profile + // (GET /api/v1/billing/profiles/{id}) + GetBillingProfile(w http.ResponseWriter, r *http.Request, id string, params GetBillingProfileParams) + // Update a billing profile + // (PUT /api/v1/billing/profiles/{id}) + UpdateBillingProfile(w http.ResponseWriter, r *http.Request, id string) + // List customers + // (GET /api/v1/customers) + ListCustomers(w http.ResponseWriter, r *http.Request, params ListCustomersParams) + // Create customer + // (POST /api/v1/customers) + CreateCustomer(w http.ResponseWriter, r *http.Request) + // Delete customer + // (DELETE /api/v1/customers/{customerIdOrKey}) + DeleteCustomer(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // Get customer + // (GET /api/v1/customers/{customerIdOrKey}) + GetCustomer(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params GetCustomerParams) + // Update customer + // (PUT /api/v1/customers/{customerIdOrKey}) + UpdateCustomer(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // Get customer access + // (GET /api/v1/customers/{customerIdOrKey}/access) + GetCustomerAccess(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // List customer app data + // (GET /api/v1/customers/{customerIdOrKey}/apps) + ListCustomerAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params ListCustomerAppDataParams) + // Upsert customer app data + // (PUT /api/v1/customers/{customerIdOrKey}/apps) + UpsertCustomerAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // Delete customer app data + // (DELETE /api/v1/customers/{customerIdOrKey}/apps/{appId}) + DeleteCustomerAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, appId string) + // Get customer entitlement value + // (GET /api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value) + GetCustomerEntitlementValue(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, featureKey string, params GetCustomerEntitlementValueParams) + // Get customer stripe app data + // (GET /api/v1/customers/{customerIdOrKey}/stripe) + GetCustomerStripeAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // Upsert customer stripe app data + // (PUT /api/v1/customers/{customerIdOrKey}/stripe) + UpsertCustomerStripeAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // Create Stripe customer portal session + // (POST /api/v1/customers/{customerIdOrKey}/stripe/portal) + CreateCustomerStripePortalSession(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // List customer subscriptions + // (GET /api/v1/customers/{customerIdOrKey}/subscriptions) + ListCustomerSubscriptions(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params ListCustomerSubscriptionsParams) + // Get event metrics + // (GET /api/v1/debug/metrics) + GetDebugMetrics(w http.ResponseWriter, r *http.Request) + // List all entitlements + // (GET /api/v1/entitlements) + ListEntitlements(w http.ResponseWriter, r *http.Request, params ListEntitlementsParams) + // Get entitlement by ID + // (GET /api/v1/entitlements/{entitlementId}) + GetEntitlementById(w http.ResponseWriter, r *http.Request, entitlementId string) + // List ingested events + // (GET /api/v1/events) + ListEvents(w http.ResponseWriter, r *http.Request, params ListEventsParams) + // Ingest events + // (POST /api/v1/events) + IngestEvents(w http.ResponseWriter, r *http.Request) + // List features + // (GET /api/v1/features) + ListFeatures(w http.ResponseWriter, r *http.Request, params ListFeaturesParams) + // Create feature + // (POST /api/v1/features) + CreateFeature(w http.ResponseWriter, r *http.Request) + // Delete feature + // (DELETE /api/v1/features/{featureId}) + DeleteFeature(w http.ResponseWriter, r *http.Request, featureId string) + // Get feature + // (GET /api/v1/features/{featureId}) + GetFeature(w http.ResponseWriter, r *http.Request, featureId string) + // List grants + // (GET /api/v1/grants) + ListGrants(w http.ResponseWriter, r *http.Request, params ListGrantsParams) + // Void grant + // (DELETE /api/v1/grants/{grantId}) + VoidGrant(w http.ResponseWriter, r *http.Request, grantId string, params VoidGrantParams) + // List supported currencies + // (GET /api/v1/info/currencies) + ListCurrencies(w http.ResponseWriter, r *http.Request) + // Get progress + // (GET /api/v1/info/progress/{id}) + GetProgress(w http.ResponseWriter, r *http.Request, id string) + // List available apps + // (GET /api/v1/marketplace/listings) + ListMarketplaceListings(w http.ResponseWriter, r *http.Request, params ListMarketplaceListingsParams) + // Get app details by type + // (GET /api/v1/marketplace/listings/{type}) + GetMarketplaceListing(w http.ResponseWriter, r *http.Request, pType AppType) + // Install app + // (POST /api/v1/marketplace/listings/{type}/install) + MarketplaceAppInstall(w http.ResponseWriter, r *http.Request, pType MarketplaceInstallRequestType) + // Install app via API key + // (POST /api/v1/marketplace/listings/{type}/install/apikey) + MarketplaceAppAPIKeyInstall(w http.ResponseWriter, r *http.Request, pType MarketplaceApiKeyInstallRequestType) + // Get OAuth2 install URL + // (GET /api/v1/marketplace/listings/{type}/install/oauth2) + MarketplaceOAuth2InstallGetURL(w http.ResponseWriter, r *http.Request, pType AppType) + // Install app via OAuth2 + // (GET /api/v1/marketplace/listings/{type}/install/oauth2/authorize) + MarketplaceOAuth2InstallAuthorize(w http.ResponseWriter, r *http.Request, pType MarketplaceOAuth2InstallAuthorizeRequestType, params MarketplaceOAuth2InstallAuthorizeParams) + // List meters + // (GET /api/v1/meters) + ListMeters(w http.ResponseWriter, r *http.Request, params ListMetersParams) + // Create meter + // (POST /api/v1/meters) + CreateMeter(w http.ResponseWriter, r *http.Request) + // Delete meter + // (DELETE /api/v1/meters/{meterIdOrSlug}) + DeleteMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) + // Get meter + // (GET /api/v1/meters/{meterIdOrSlug}) + GetMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) + // Update meter + // (PUT /api/v1/meters/{meterIdOrSlug}) + UpdateMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) + // List meter group by values + // (GET /api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values) + ListMeterGroupByValues(w http.ResponseWriter, r *http.Request, meterIdOrSlug string, groupByKey string, params ListMeterGroupByValuesParams) + // Query meter + // (GET /api/v1/meters/{meterIdOrSlug}/query) + QueryMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string, params QueryMeterParams) + // Query meter + // (POST /api/v1/meters/{meterIdOrSlug}/query) + QueryMeterPost(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) + // List meter subjects + // (GET /api/v1/meters/{meterIdOrSlug}/subjects) + ListMeterSubjects(w http.ResponseWriter, r *http.Request, meterIdOrSlug string, params ListMeterSubjectsParams) + // List notification channels + // (GET /api/v1/notification/channels) + ListNotificationChannels(w http.ResponseWriter, r *http.Request, params ListNotificationChannelsParams) + // Create a notification channel + // (POST /api/v1/notification/channels) + CreateNotificationChannel(w http.ResponseWriter, r *http.Request) + // Delete a notification channel + // (DELETE /api/v1/notification/channels/{channelId}) + DeleteNotificationChannel(w http.ResponseWriter, r *http.Request, channelId string) + // Get notification channel + // (GET /api/v1/notification/channels/{channelId}) + GetNotificationChannel(w http.ResponseWriter, r *http.Request, channelId string) + // Update a notification channel + // (PUT /api/v1/notification/channels/{channelId}) + UpdateNotificationChannel(w http.ResponseWriter, r *http.Request, channelId string) + // List notification events + // (GET /api/v1/notification/events) + ListNotificationEvents(w http.ResponseWriter, r *http.Request, params ListNotificationEventsParams) + // Get notification event + // (GET /api/v1/notification/events/{eventId}) + GetNotificationEvent(w http.ResponseWriter, r *http.Request, eventId string) + // Re-send notification event + // (POST /api/v1/notification/events/{eventId}/resend) + ResendNotificationEvent(w http.ResponseWriter, r *http.Request, eventId string) + // List notification rules + // (GET /api/v1/notification/rules) + ListNotificationRules(w http.ResponseWriter, r *http.Request, params ListNotificationRulesParams) + // Create a notification rule + // (POST /api/v1/notification/rules) + CreateNotificationRule(w http.ResponseWriter, r *http.Request) + // Delete a notification rule + // (DELETE /api/v1/notification/rules/{ruleId}) + DeleteNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) + // Get notification rule + // (GET /api/v1/notification/rules/{ruleId}) + GetNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) + // Update a notification rule + // (PUT /api/v1/notification/rules/{ruleId}) + UpdateNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) + // Test notification rule + // (POST /api/v1/notification/rules/{ruleId}/test) + TestNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) + // List plans + // (GET /api/v1/plans) + ListPlans(w http.ResponseWriter, r *http.Request, params ListPlansParams) + // Create a plan + // (POST /api/v1/plans) + CreatePlan(w http.ResponseWriter, r *http.Request) + // New draft plan + // (POST /api/v1/plans/{planIdOrKey}/next) + NextPlan(w http.ResponseWriter, r *http.Request, planIdOrKey string) + // Delete plan + // (DELETE /api/v1/plans/{planId}) + DeletePlan(w http.ResponseWriter, r *http.Request, planId string) + // Get plan + // (GET /api/v1/plans/{planId}) + GetPlan(w http.ResponseWriter, r *http.Request, planId string, params GetPlanParams) + // Update a plan + // (PUT /api/v1/plans/{planId}) + UpdatePlan(w http.ResponseWriter, r *http.Request, planId string) + // List all available add-ons for plan + // (GET /api/v1/plans/{planId}/addons) + ListPlanAddons(w http.ResponseWriter, r *http.Request, planId string, params ListPlanAddonsParams) + // Create new add-on assignment for plan + // (POST /api/v1/plans/{planId}/addons) + CreatePlanAddon(w http.ResponseWriter, r *http.Request, planId string) + // Delete add-on assignment for plan + // (DELETE /api/v1/plans/{planId}/addons/{planAddonId}) + DeletePlanAddon(w http.ResponseWriter, r *http.Request, planId string, planAddonId string) + // Get add-on assignment for plan + // (GET /api/v1/plans/{planId}/addons/{planAddonId}) + GetPlanAddon(w http.ResponseWriter, r *http.Request, planId string, planAddonId string) + // Update add-on assignment for plan + // (PUT /api/v1/plans/{planId}/addons/{planAddonId}) + UpdatePlanAddon(w http.ResponseWriter, r *http.Request, planId string, planAddonId string) + // Archive plan version + // (POST /api/v1/plans/{planId}/archive) + ArchivePlan(w http.ResponseWriter, r *http.Request, planId string) + // Publish plan + // (POST /api/v1/plans/{planId}/publish) + PublishPlan(w http.ResponseWriter, r *http.Request, planId string) + // Query meter Query meter + // (GET /api/v1/portal/meters/{meterSlug}/query) + QueryPortalMeter(w http.ResponseWriter, r *http.Request, meterSlug string, params QueryPortalMeterParams) + // List consumer portal tokens + // (GET /api/v1/portal/tokens) + ListPortalTokens(w http.ResponseWriter, r *http.Request, params ListPortalTokensParams) + // Create consumer portal token + // (POST /api/v1/portal/tokens) + CreatePortalToken(w http.ResponseWriter, r *http.Request) + // Invalidate portal tokens + // (POST /api/v1/portal/tokens/invalidate) + InvalidatePortalTokens(w http.ResponseWriter, r *http.Request) + // Create checkout session + // (POST /api/v1/stripe/checkout/sessions) + CreateStripeCheckoutSession(w http.ResponseWriter, r *http.Request) + // List subjects + // (GET /api/v1/subjects) + ListSubjects(w http.ResponseWriter, r *http.Request) + // Upsert subject + // (POST /api/v1/subjects) + UpsertSubject(w http.ResponseWriter, r *http.Request) + // Delete subject + // (DELETE /api/v1/subjects/{subjectIdOrKey}) + DeleteSubject(w http.ResponseWriter, r *http.Request, subjectIdOrKey string) + // Get subject + // (GET /api/v1/subjects/{subjectIdOrKey}) + GetSubject(w http.ResponseWriter, r *http.Request, subjectIdOrKey string) + // List subject entitlements + // (GET /api/v1/subjects/{subjectIdOrKey}/entitlements) + ListSubjectEntitlements(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, params ListSubjectEntitlementsParams) + // Create a subject entitlement + // (POST /api/v1/subjects/{subjectIdOrKey}/entitlements) + CreateEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string) + // List subject entitlement grants + // (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) + ListEntitlementGrants(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string, params ListEntitlementGrantsParams) + // Create subject entitlement grant + // (POST /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) + CreateGrant(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string) + // Override subject entitlement + // (PUT /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) + OverrideEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string) + // Get subject entitlement value + // (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) + GetEntitlementValue(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string, params GetEntitlementValueParams) + // Delete subject entitlement + // (DELETE /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}) + DeleteEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string) + // Get subject entitlement + // (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}) + GetEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string) + // Get subject entitlement history + // (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history) + GetEntitlementHistory(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string, params GetEntitlementHistoryParams) + // Reset subject entitlement + // (POST /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset) + ResetEntitlementUsage(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string) + // Create subscription + // (POST /api/v1/subscriptions) + CreateSubscription(w http.ResponseWriter, r *http.Request) + // Delete subscription + // (DELETE /api/v1/subscriptions/{subscriptionId}) + DeleteSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Get subscription + // (GET /api/v1/subscriptions/{subscriptionId}) + GetSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string, params GetSubscriptionParams) + // Edit subscription + // (PATCH /api/v1/subscriptions/{subscriptionId}) + EditSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) + // List subscription addons + // (GET /api/v1/subscriptions/{subscriptionId}/addons) + ListSubscriptionAddons(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Create subscription addon + // (POST /api/v1/subscriptions/{subscriptionId}/addons) + CreateSubscriptionAddon(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Get subscription addon + // (GET /api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}) + GetSubscriptionAddon(w http.ResponseWriter, r *http.Request, subscriptionId string, subscriptionAddonId string) + // Update subscription addon + // (PATCH /api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}) + UpdateSubscriptionAddon(w http.ResponseWriter, r *http.Request, subscriptionId string, subscriptionAddonId string) + // Cancel subscription + // (POST /api/v1/subscriptions/{subscriptionId}/cancel) + CancelSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Change subscription + // (POST /api/v1/subscriptions/{subscriptionId}/change) + ChangeSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Migrate subscription + // (POST /api/v1/subscriptions/{subscriptionId}/migrate) + MigrateSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Restore subscription + // (POST /api/v1/subscriptions/{subscriptionId}/restore) + RestoreSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) + // Unschedule cancelation + // (POST /api/v1/subscriptions/{subscriptionId}/unschedule-cancelation) + UnscheduleCancelation(w http.ResponseWriter, r *http.Request, subscriptionId string) + // List customer entitlements + // (GET /api/v2/customers/{customerIdOrKey}/entitlements) + ListCustomerEntitlementsV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params ListCustomerEntitlementsV2Params) + // Create a customer entitlement + // (POST /api/v2/customers/{customerIdOrKey}/entitlements) + CreateCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) + // Delete customer entitlement + // (DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) + DeleteCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) + // Get customer entitlement + // (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) + GetCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) + // List customer entitlement grants + // (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) + ListCustomerEntitlementGrantsV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params ListCustomerEntitlementGrantsV2Params) + // Create customer entitlement grant + // (POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) + CreateCustomerEntitlementGrantV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) + // Get customer entitlement history + // (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) + GetCustomerEntitlementHistoryV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params GetCustomerEntitlementHistoryV2Params) + // Override customer entitlement + // (PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) + OverrideCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey) + // Reset customer entitlement + // (POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) + ResetCustomerEntitlementUsageV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) + // Get customer entitlement value + // (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) + GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params GetCustomerEntitlementValueV2Params) + // List all entitlements + // (GET /api/v2/entitlements) + ListEntitlementsV2(w http.ResponseWriter, r *http.Request, params ListEntitlementsV2Params) + // Get entitlement by ID + // (GET /api/v2/entitlements/{entitlementId}) + GetEntitlementByIdV2(w http.ResponseWriter, r *http.Request, entitlementId string) + // List ingested events + // (GET /api/v2/events) + ListEventsV2(w http.ResponseWriter, r *http.Request, params ListEventsV2Params) + // List grants + // (GET /api/v2/grants) + ListGrantsV2(w http.ResponseWriter, r *http.Request, params ListGrantsV2Params) +} + +// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint. + +type Unimplemented struct{} + +// List add-ons +// (GET /api/v1/addons) +func (_ Unimplemented) ListAddons(w http.ResponseWriter, r *http.Request, params ListAddonsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create an add-on +// (POST /api/v1/addons) +func (_ Unimplemented) CreateAddon(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete add-on +// (DELETE /api/v1/addons/{addonId}) +func (_ Unimplemented) DeleteAddon(w http.ResponseWriter, r *http.Request, addonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get add-on +// (GET /api/v1/addons/{addonId}) +func (_ Unimplemented) GetAddon(w http.ResponseWriter, r *http.Request, addonId string, params GetAddonParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update add-on +// (PUT /api/v1/addons/{addonId}) +func (_ Unimplemented) UpdateAddon(w http.ResponseWriter, r *http.Request, addonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Archive add-on version +// (POST /api/v1/addons/{addonId}/archive) +func (_ Unimplemented) ArchiveAddon(w http.ResponseWriter, r *http.Request, addonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Publish add-on +// (POST /api/v1/addons/{addonId}/publish) +func (_ Unimplemented) PublishAddon(w http.ResponseWriter, r *http.Request, addonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List apps +// (GET /api/v1/apps) +func (_ Unimplemented) ListApps(w http.ResponseWriter, r *http.Request, params ListAppsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Submit draft synchronization results +// (POST /api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized) +func (_ Unimplemented) AppCustomInvoicingDraftSynchronized(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Submit issuing synchronization results +// (POST /api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized) +func (_ Unimplemented) AppCustomInvoicingIssuingSynchronized(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update payment status +// (POST /api/v1/apps/custom-invoicing/{invoiceId}/payment/status) +func (_ Unimplemented) AppCustomInvoicingUpdatePaymentStatus(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Uninstall app +// (DELETE /api/v1/apps/{id}) +func (_ Unimplemented) UninstallApp(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get app +// (GET /api/v1/apps/{id}) +func (_ Unimplemented) GetApp(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update app +// (PUT /api/v1/apps/{id}) +func (_ Unimplemented) UpdateApp(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update Stripe API key +// (PUT /api/v1/apps/{id}/stripe/api-key) +func (_ Unimplemented) UpdateStripeAPIKey(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Stripe webhook +// (POST /api/v1/apps/{id}/stripe/webhook) +func (_ Unimplemented) AppStripeWebhook(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List customer overrides +// (GET /api/v1/billing/customers) +func (_ Unimplemented) ListBillingProfileCustomerOverrides(w http.ResponseWriter, r *http.Request, params ListBillingProfileCustomerOverridesParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete a customer override +// (DELETE /api/v1/billing/customers/{customerId}) +func (_ Unimplemented) DeleteBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request, customerId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get a customer override +// (GET /api/v1/billing/customers/{customerId}) +func (_ Unimplemented) GetBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request, customerId string, params GetBillingProfileCustomerOverrideParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a new or update a customer override +// (PUT /api/v1/billing/customers/{customerId}) +func (_ Unimplemented) UpsertBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request, customerId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create pending line items +// (POST /api/v1/billing/customers/{customerId}/invoices/pending-lines) +func (_ Unimplemented) CreatePendingInvoiceLine(w http.ResponseWriter, r *http.Request, customerId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Simulate an invoice for a customer +// (POST /api/v1/billing/customers/{customerId}/invoices/simulate) +func (_ Unimplemented) SimulateInvoice(w http.ResponseWriter, r *http.Request, customerId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List invoices +// (GET /api/v1/billing/invoices) +func (_ Unimplemented) ListInvoices(w http.ResponseWriter, r *http.Request, params ListInvoicesParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Invoice a customer based on the pending line items +// (POST /api/v1/billing/invoices/invoice) +func (_ Unimplemented) InvoicePendingLinesAction(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete an invoice +// (DELETE /api/v1/billing/invoices/{invoiceId}) +func (_ Unimplemented) DeleteInvoice(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get an invoice +// (GET /api/v1/billing/invoices/{invoiceId}) +func (_ Unimplemented) GetInvoice(w http.ResponseWriter, r *http.Request, invoiceId string, params GetInvoiceParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update an invoice +// (PUT /api/v1/billing/invoices/{invoiceId}) +func (_ Unimplemented) UpdateInvoice(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Advance the invoice's state to the next status +// (POST /api/v1/billing/invoices/{invoiceId}/advance) +func (_ Unimplemented) AdvanceInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Send the invoice to the customer +// (POST /api/v1/billing/invoices/{invoiceId}/approve) +func (_ Unimplemented) ApproveInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Retry advancing the invoice after a failed attempt. +// (POST /api/v1/billing/invoices/{invoiceId}/retry) +func (_ Unimplemented) RetryInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Snapshot quantities for usage based line items +// (POST /api/v1/billing/invoices/{invoiceId}/snapshot-quantities) +func (_ Unimplemented) SnapshotQuantitiesInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Recalculate an invoice's tax amounts +// (POST /api/v1/billing/invoices/{invoiceId}/taxes/recalculate) +func (_ Unimplemented) RecalculateInvoiceTaxAction(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Void an invoice +// (POST /api/v1/billing/invoices/{invoiceId}/void) +func (_ Unimplemented) VoidInvoiceAction(w http.ResponseWriter, r *http.Request, invoiceId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List billing profiles +// (GET /api/v1/billing/profiles) +func (_ Unimplemented) ListBillingProfiles(w http.ResponseWriter, r *http.Request, params ListBillingProfilesParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a new billing profile +// (POST /api/v1/billing/profiles) +func (_ Unimplemented) CreateBillingProfile(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete a billing profile +// (DELETE /api/v1/billing/profiles/{id}) +func (_ Unimplemented) DeleteBillingProfile(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get a billing profile +// (GET /api/v1/billing/profiles/{id}) +func (_ Unimplemented) GetBillingProfile(w http.ResponseWriter, r *http.Request, id string, params GetBillingProfileParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update a billing profile +// (PUT /api/v1/billing/profiles/{id}) +func (_ Unimplemented) UpdateBillingProfile(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List customers +// (GET /api/v1/customers) +func (_ Unimplemented) ListCustomers(w http.ResponseWriter, r *http.Request, params ListCustomersParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create customer +// (POST /api/v1/customers) +func (_ Unimplemented) CreateCustomer(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete customer +// (DELETE /api/v1/customers/{customerIdOrKey}) +func (_ Unimplemented) DeleteCustomer(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer +// (GET /api/v1/customers/{customerIdOrKey}) +func (_ Unimplemented) GetCustomer(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params GetCustomerParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update customer +// (PUT /api/v1/customers/{customerIdOrKey}) +func (_ Unimplemented) UpdateCustomer(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer access +// (GET /api/v1/customers/{customerIdOrKey}/access) +func (_ Unimplemented) GetCustomerAccess(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List customer app data +// (GET /api/v1/customers/{customerIdOrKey}/apps) +func (_ Unimplemented) ListCustomerAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params ListCustomerAppDataParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Upsert customer app data +// (PUT /api/v1/customers/{customerIdOrKey}/apps) +func (_ Unimplemented) UpsertCustomerAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete customer app data +// (DELETE /api/v1/customers/{customerIdOrKey}/apps/{appId}) +func (_ Unimplemented) DeleteCustomerAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, appId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer entitlement value +// (GET /api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value) +func (_ Unimplemented) GetCustomerEntitlementValue(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, featureKey string, params GetCustomerEntitlementValueParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer stripe app data +// (GET /api/v1/customers/{customerIdOrKey}/stripe) +func (_ Unimplemented) GetCustomerStripeAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Upsert customer stripe app data +// (PUT /api/v1/customers/{customerIdOrKey}/stripe) +func (_ Unimplemented) UpsertCustomerStripeAppData(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create Stripe customer portal session +// (POST /api/v1/customers/{customerIdOrKey}/stripe/portal) +func (_ Unimplemented) CreateCustomerStripePortalSession(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List customer subscriptions +// (GET /api/v1/customers/{customerIdOrKey}/subscriptions) +func (_ Unimplemented) ListCustomerSubscriptions(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params ListCustomerSubscriptionsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get event metrics +// (GET /api/v1/debug/metrics) +func (_ Unimplemented) GetDebugMetrics(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List all entitlements +// (GET /api/v1/entitlements) +func (_ Unimplemented) ListEntitlements(w http.ResponseWriter, r *http.Request, params ListEntitlementsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get entitlement by ID +// (GET /api/v1/entitlements/{entitlementId}) +func (_ Unimplemented) GetEntitlementById(w http.ResponseWriter, r *http.Request, entitlementId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List ingested events +// (GET /api/v1/events) +func (_ Unimplemented) ListEvents(w http.ResponseWriter, r *http.Request, params ListEventsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Ingest events +// (POST /api/v1/events) +func (_ Unimplemented) IngestEvents(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List features +// (GET /api/v1/features) +func (_ Unimplemented) ListFeatures(w http.ResponseWriter, r *http.Request, params ListFeaturesParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create feature +// (POST /api/v1/features) +func (_ Unimplemented) CreateFeature(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete feature +// (DELETE /api/v1/features/{featureId}) +func (_ Unimplemented) DeleteFeature(w http.ResponseWriter, r *http.Request, featureId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get feature +// (GET /api/v1/features/{featureId}) +func (_ Unimplemented) GetFeature(w http.ResponseWriter, r *http.Request, featureId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List grants +// (GET /api/v1/grants) +func (_ Unimplemented) ListGrants(w http.ResponseWriter, r *http.Request, params ListGrantsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Void grant +// (DELETE /api/v1/grants/{grantId}) +func (_ Unimplemented) VoidGrant(w http.ResponseWriter, r *http.Request, grantId string, params VoidGrantParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List supported currencies +// (GET /api/v1/info/currencies) +func (_ Unimplemented) ListCurrencies(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get progress +// (GET /api/v1/info/progress/{id}) +func (_ Unimplemented) GetProgress(w http.ResponseWriter, r *http.Request, id string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List available apps +// (GET /api/v1/marketplace/listings) +func (_ Unimplemented) ListMarketplaceListings(w http.ResponseWriter, r *http.Request, params ListMarketplaceListingsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get app details by type +// (GET /api/v1/marketplace/listings/{type}) +func (_ Unimplemented) GetMarketplaceListing(w http.ResponseWriter, r *http.Request, pType AppType) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Install app +// (POST /api/v1/marketplace/listings/{type}/install) +func (_ Unimplemented) MarketplaceAppInstall(w http.ResponseWriter, r *http.Request, pType MarketplaceInstallRequestType) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Install app via API key +// (POST /api/v1/marketplace/listings/{type}/install/apikey) +func (_ Unimplemented) MarketplaceAppAPIKeyInstall(w http.ResponseWriter, r *http.Request, pType MarketplaceApiKeyInstallRequestType) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get OAuth2 install URL +// (GET /api/v1/marketplace/listings/{type}/install/oauth2) +func (_ Unimplemented) MarketplaceOAuth2InstallGetURL(w http.ResponseWriter, r *http.Request, pType AppType) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Install app via OAuth2 +// (GET /api/v1/marketplace/listings/{type}/install/oauth2/authorize) +func (_ Unimplemented) MarketplaceOAuth2InstallAuthorize(w http.ResponseWriter, r *http.Request, pType MarketplaceOAuth2InstallAuthorizeRequestType, params MarketplaceOAuth2InstallAuthorizeParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List meters +// (GET /api/v1/meters) +func (_ Unimplemented) ListMeters(w http.ResponseWriter, r *http.Request, params ListMetersParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create meter +// (POST /api/v1/meters) +func (_ Unimplemented) CreateMeter(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete meter +// (DELETE /api/v1/meters/{meterIdOrSlug}) +func (_ Unimplemented) DeleteMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get meter +// (GET /api/v1/meters/{meterIdOrSlug}) +func (_ Unimplemented) GetMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update meter +// (PUT /api/v1/meters/{meterIdOrSlug}) +func (_ Unimplemented) UpdateMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List meter group by values +// (GET /api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values) +func (_ Unimplemented) ListMeterGroupByValues(w http.ResponseWriter, r *http.Request, meterIdOrSlug string, groupByKey string, params ListMeterGroupByValuesParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Query meter +// (GET /api/v1/meters/{meterIdOrSlug}/query) +func (_ Unimplemented) QueryMeter(w http.ResponseWriter, r *http.Request, meterIdOrSlug string, params QueryMeterParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Query meter +// (POST /api/v1/meters/{meterIdOrSlug}/query) +func (_ Unimplemented) QueryMeterPost(w http.ResponseWriter, r *http.Request, meterIdOrSlug string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List meter subjects +// (GET /api/v1/meters/{meterIdOrSlug}/subjects) +func (_ Unimplemented) ListMeterSubjects(w http.ResponseWriter, r *http.Request, meterIdOrSlug string, params ListMeterSubjectsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List notification channels +// (GET /api/v1/notification/channels) +func (_ Unimplemented) ListNotificationChannels(w http.ResponseWriter, r *http.Request, params ListNotificationChannelsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a notification channel +// (POST /api/v1/notification/channels) +func (_ Unimplemented) CreateNotificationChannel(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete a notification channel +// (DELETE /api/v1/notification/channels/{channelId}) +func (_ Unimplemented) DeleteNotificationChannel(w http.ResponseWriter, r *http.Request, channelId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get notification channel +// (GET /api/v1/notification/channels/{channelId}) +func (_ Unimplemented) GetNotificationChannel(w http.ResponseWriter, r *http.Request, channelId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update a notification channel +// (PUT /api/v1/notification/channels/{channelId}) +func (_ Unimplemented) UpdateNotificationChannel(w http.ResponseWriter, r *http.Request, channelId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List notification events +// (GET /api/v1/notification/events) +func (_ Unimplemented) ListNotificationEvents(w http.ResponseWriter, r *http.Request, params ListNotificationEventsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get notification event +// (GET /api/v1/notification/events/{eventId}) +func (_ Unimplemented) GetNotificationEvent(w http.ResponseWriter, r *http.Request, eventId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Re-send notification event +// (POST /api/v1/notification/events/{eventId}/resend) +func (_ Unimplemented) ResendNotificationEvent(w http.ResponseWriter, r *http.Request, eventId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List notification rules +// (GET /api/v1/notification/rules) +func (_ Unimplemented) ListNotificationRules(w http.ResponseWriter, r *http.Request, params ListNotificationRulesParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a notification rule +// (POST /api/v1/notification/rules) +func (_ Unimplemented) CreateNotificationRule(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete a notification rule +// (DELETE /api/v1/notification/rules/{ruleId}) +func (_ Unimplemented) DeleteNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get notification rule +// (GET /api/v1/notification/rules/{ruleId}) +func (_ Unimplemented) GetNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update a notification rule +// (PUT /api/v1/notification/rules/{ruleId}) +func (_ Unimplemented) UpdateNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Test notification rule +// (POST /api/v1/notification/rules/{ruleId}/test) +func (_ Unimplemented) TestNotificationRule(w http.ResponseWriter, r *http.Request, ruleId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List plans +// (GET /api/v1/plans) +func (_ Unimplemented) ListPlans(w http.ResponseWriter, r *http.Request, params ListPlansParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a plan +// (POST /api/v1/plans) +func (_ Unimplemented) CreatePlan(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// New draft plan +// (POST /api/v1/plans/{planIdOrKey}/next) +func (_ Unimplemented) NextPlan(w http.ResponseWriter, r *http.Request, planIdOrKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete plan +// (DELETE /api/v1/plans/{planId}) +func (_ Unimplemented) DeletePlan(w http.ResponseWriter, r *http.Request, planId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get plan +// (GET /api/v1/plans/{planId}) +func (_ Unimplemented) GetPlan(w http.ResponseWriter, r *http.Request, planId string, params GetPlanParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update a plan +// (PUT /api/v1/plans/{planId}) +func (_ Unimplemented) UpdatePlan(w http.ResponseWriter, r *http.Request, planId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List all available add-ons for plan +// (GET /api/v1/plans/{planId}/addons) +func (_ Unimplemented) ListPlanAddons(w http.ResponseWriter, r *http.Request, planId string, params ListPlanAddonsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create new add-on assignment for plan +// (POST /api/v1/plans/{planId}/addons) +func (_ Unimplemented) CreatePlanAddon(w http.ResponseWriter, r *http.Request, planId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete add-on assignment for plan +// (DELETE /api/v1/plans/{planId}/addons/{planAddonId}) +func (_ Unimplemented) DeletePlanAddon(w http.ResponseWriter, r *http.Request, planId string, planAddonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get add-on assignment for plan +// (GET /api/v1/plans/{planId}/addons/{planAddonId}) +func (_ Unimplemented) GetPlanAddon(w http.ResponseWriter, r *http.Request, planId string, planAddonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update add-on assignment for plan +// (PUT /api/v1/plans/{planId}/addons/{planAddonId}) +func (_ Unimplemented) UpdatePlanAddon(w http.ResponseWriter, r *http.Request, planId string, planAddonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Archive plan version +// (POST /api/v1/plans/{planId}/archive) +func (_ Unimplemented) ArchivePlan(w http.ResponseWriter, r *http.Request, planId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Publish plan +// (POST /api/v1/plans/{planId}/publish) +func (_ Unimplemented) PublishPlan(w http.ResponseWriter, r *http.Request, planId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Query meter Query meter +// (GET /api/v1/portal/meters/{meterSlug}/query) +func (_ Unimplemented) QueryPortalMeter(w http.ResponseWriter, r *http.Request, meterSlug string, params QueryPortalMeterParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List consumer portal tokens +// (GET /api/v1/portal/tokens) +func (_ Unimplemented) ListPortalTokens(w http.ResponseWriter, r *http.Request, params ListPortalTokensParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create consumer portal token +// (POST /api/v1/portal/tokens) +func (_ Unimplemented) CreatePortalToken(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Invalidate portal tokens +// (POST /api/v1/portal/tokens/invalidate) +func (_ Unimplemented) InvalidatePortalTokens(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create checkout session +// (POST /api/v1/stripe/checkout/sessions) +func (_ Unimplemented) CreateStripeCheckoutSession(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List subjects +// (GET /api/v1/subjects) +func (_ Unimplemented) ListSubjects(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Upsert subject +// (POST /api/v1/subjects) +func (_ Unimplemented) UpsertSubject(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete subject +// (DELETE /api/v1/subjects/{subjectIdOrKey}) +func (_ Unimplemented) DeleteSubject(w http.ResponseWriter, r *http.Request, subjectIdOrKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get subject +// (GET /api/v1/subjects/{subjectIdOrKey}) +func (_ Unimplemented) GetSubject(w http.ResponseWriter, r *http.Request, subjectIdOrKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List subject entitlements +// (GET /api/v1/subjects/{subjectIdOrKey}/entitlements) +func (_ Unimplemented) ListSubjectEntitlements(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, params ListSubjectEntitlementsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a subject entitlement +// (POST /api/v1/subjects/{subjectIdOrKey}/entitlements) +func (_ Unimplemented) CreateEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List subject entitlement grants +// (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) +func (_ Unimplemented) ListEntitlementGrants(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string, params ListEntitlementGrantsParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create subject entitlement grant +// (POST /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) +func (_ Unimplemented) CreateGrant(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Override subject entitlement +// (PUT /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) +func (_ Unimplemented) OverrideEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get subject entitlement value +// (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) +func (_ Unimplemented) GetEntitlementValue(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string, params GetEntitlementValueParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete subject entitlement +// (DELETE /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}) +func (_ Unimplemented) DeleteEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get subject entitlement +// (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}) +func (_ Unimplemented) GetEntitlement(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get subject entitlement history +// (GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history) +func (_ Unimplemented) GetEntitlementHistory(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string, params GetEntitlementHistoryParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Reset subject entitlement +// (POST /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset) +func (_ Unimplemented) ResetEntitlementUsage(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create subscription +// (POST /api/v1/subscriptions) +func (_ Unimplemented) CreateSubscription(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete subscription +// (DELETE /api/v1/subscriptions/{subscriptionId}) +func (_ Unimplemented) DeleteSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get subscription +// (GET /api/v1/subscriptions/{subscriptionId}) +func (_ Unimplemented) GetSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string, params GetSubscriptionParams) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Edit subscription +// (PATCH /api/v1/subscriptions/{subscriptionId}) +func (_ Unimplemented) EditSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List subscription addons +// (GET /api/v1/subscriptions/{subscriptionId}/addons) +func (_ Unimplemented) ListSubscriptionAddons(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create subscription addon +// (POST /api/v1/subscriptions/{subscriptionId}/addons) +func (_ Unimplemented) CreateSubscriptionAddon(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get subscription addon +// (GET /api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}) +func (_ Unimplemented) GetSubscriptionAddon(w http.ResponseWriter, r *http.Request, subscriptionId string, subscriptionAddonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Update subscription addon +// (PATCH /api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}) +func (_ Unimplemented) UpdateSubscriptionAddon(w http.ResponseWriter, r *http.Request, subscriptionId string, subscriptionAddonId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Cancel subscription +// (POST /api/v1/subscriptions/{subscriptionId}/cancel) +func (_ Unimplemented) CancelSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Change subscription +// (POST /api/v1/subscriptions/{subscriptionId}/change) +func (_ Unimplemented) ChangeSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Migrate subscription +// (POST /api/v1/subscriptions/{subscriptionId}/migrate) +func (_ Unimplemented) MigrateSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Restore subscription +// (POST /api/v1/subscriptions/{subscriptionId}/restore) +func (_ Unimplemented) RestoreSubscription(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Unschedule cancelation +// (POST /api/v1/subscriptions/{subscriptionId}/unschedule-cancelation) +func (_ Unimplemented) UnscheduleCancelation(w http.ResponseWriter, r *http.Request, subscriptionId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List customer entitlements +// (GET /api/v2/customers/{customerIdOrKey}/entitlements) +func (_ Unimplemented) ListCustomerEntitlementsV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, params ListCustomerEntitlementsV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create a customer entitlement +// (POST /api/v2/customers/{customerIdOrKey}/entitlements) +func (_ Unimplemented) CreateCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Delete customer entitlement +// (DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) +func (_ Unimplemented) DeleteCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer entitlement +// (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) +func (_ Unimplemented) GetCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List customer entitlement grants +// (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) +func (_ Unimplemented) ListCustomerEntitlementGrantsV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params ListCustomerEntitlementGrantsV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Create customer entitlement grant +// (POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) +func (_ Unimplemented) CreateCustomerEntitlementGrantV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer entitlement history +// (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) +func (_ Unimplemented) GetCustomerEntitlementHistoryV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params GetCustomerEntitlementHistoryV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Override customer entitlement +// (PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) +func (_ Unimplemented) OverrideCustomerEntitlementV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Reset customer entitlement +// (POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) +func (_ Unimplemented) ResetCustomerEntitlementUsageV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get customer entitlement value +// (GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) +func (_ Unimplemented) GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params GetCustomerEntitlementValueV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List all entitlements +// (GET /api/v2/entitlements) +func (_ Unimplemented) ListEntitlementsV2(w http.ResponseWriter, r *http.Request, params ListEntitlementsV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// Get entitlement by ID +// (GET /api/v2/entitlements/{entitlementId}) +func (_ Unimplemented) GetEntitlementByIdV2(w http.ResponseWriter, r *http.Request, entitlementId string) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List ingested events +// (GET /api/v2/events) +func (_ Unimplemented) ListEventsV2(w http.ResponseWriter, r *http.Request, params ListEventsV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// List grants +// (GET /api/v2/grants) +func (_ Unimplemented) ListGrantsV2(w http.ResponseWriter, r *http.Request, params ListGrantsV2Params) { + w.WriteHeader(http.StatusNotImplemented) +} + +// ServerInterfaceWrapper converts contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface + HandlerMiddlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +type MiddlewareFunc func(http.Handler) http.Handler + +// ListAddons operation middleware +func (siw *ServerInterfaceWrapper) ListAddons(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListAddonsParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "id" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "id", r.URL.Query(), ¶ms.Id, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // ------------- Optional query parameter "key" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "key", r.URL.Query(), ¶ms.Key, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "key", Err: err}) + return + } + + // ------------- Optional query parameter "keyVersion" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, false, "keyVersion", r.URL.Query(), ¶ms.KeyVersion, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "keyVersion", Err: err}) + return + } + + // ------------- Optional query parameter "status" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "status", r.URL.Query(), ¶ms.Status, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "status", Err: err}) + return + } + + // ------------- Optional query parameter "currency" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "currency", r.URL.Query(), ¶ms.Currency, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "currency", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListAddons(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateAddon operation middleware +func (siw *ServerInterfaceWrapper) CreateAddon(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateAddon(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteAddon operation middleware +func (siw *ServerInterfaceWrapper) DeleteAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "addonId" ------------- + var addonId string + + err = runtime.BindStyledParameterWithOptions("simple", "addonId", chi.URLParam(r, "addonId"), &addonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "addonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteAddon(w, r, addonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetAddon operation middleware +func (siw *ServerInterfaceWrapper) GetAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "addonId" ------------- + var addonId string + + err = runtime.BindStyledParameterWithOptions("simple", "addonId", chi.URLParam(r, "addonId"), &addonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "addonId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetAddonParams + + // ------------- Optional query parameter "includeLatest" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeLatest", r.URL.Query(), ¶ms.IncludeLatest, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeLatest", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetAddon(w, r, addonId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateAddon operation middleware +func (siw *ServerInterfaceWrapper) UpdateAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "addonId" ------------- + var addonId string + + err = runtime.BindStyledParameterWithOptions("simple", "addonId", chi.URLParam(r, "addonId"), &addonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "addonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateAddon(w, r, addonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ArchiveAddon operation middleware +func (siw *ServerInterfaceWrapper) ArchiveAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "addonId" ------------- + var addonId string + + err = runtime.BindStyledParameterWithOptions("simple", "addonId", chi.URLParam(r, "addonId"), &addonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "addonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ArchiveAddon(w, r, addonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// PublishAddon operation middleware +func (siw *ServerInterfaceWrapper) PublishAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "addonId" ------------- + var addonId string + + err = runtime.BindStyledParameterWithOptions("simple", "addonId", chi.URLParam(r, "addonId"), &addonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "addonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PublishAddon(w, r, addonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListApps operation middleware +func (siw *ServerInterfaceWrapper) ListApps(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListAppsParams + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListApps(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// AppCustomInvoicingDraftSynchronized operation middleware +func (siw *ServerInterfaceWrapper) AppCustomInvoicingDraftSynchronized(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AppCustomInvoicingDraftSynchronized(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// AppCustomInvoicingIssuingSynchronized operation middleware +func (siw *ServerInterfaceWrapper) AppCustomInvoicingIssuingSynchronized(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AppCustomInvoicingIssuingSynchronized(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// AppCustomInvoicingUpdatePaymentStatus operation middleware +func (siw *ServerInterfaceWrapper) AppCustomInvoicingUpdatePaymentStatus(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AppCustomInvoicingUpdatePaymentStatus(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UninstallApp operation middleware +func (siw *ServerInterfaceWrapper) UninstallApp(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UninstallApp(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetApp operation middleware +func (siw *ServerInterfaceWrapper) GetApp(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetApp(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateApp operation middleware +func (siw *ServerInterfaceWrapper) UpdateApp(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateApp(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateStripeAPIKey operation middleware +func (siw *ServerInterfaceWrapper) UpdateStripeAPIKey(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateStripeAPIKey(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// AppStripeWebhook operation middleware +func (siw *ServerInterfaceWrapper) AppStripeWebhook(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AppStripeWebhook(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListBillingProfileCustomerOverrides operation middleware +func (siw *ServerInterfaceWrapper) ListBillingProfileCustomerOverrides(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListBillingProfileCustomerOverridesParams + + // ------------- Optional query parameter "billingProfile" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "billingProfile", r.URL.Query(), ¶ms.BillingProfile, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "billingProfile", Err: err}) + return + } + + // ------------- Optional query parameter "customersWithoutPinnedProfile" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customersWithoutPinnedProfile", r.URL.Query(), ¶ms.CustomersWithoutPinnedProfile, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customersWithoutPinnedProfile", Err: err}) + return + } + + // ------------- Optional query parameter "includeAllCustomers" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "includeAllCustomers", r.URL.Query(), ¶ms.IncludeAllCustomers, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeAllCustomers", Err: err}) + return + } + + // ------------- Optional query parameter "customerId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customerId", r.URL.Query(), ¶ms.CustomerId, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + // ------------- Optional query parameter "customerName" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "customerName", r.URL.Query(), ¶ms.CustomerName, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerName", Err: err}) + return + } + + // ------------- Optional query parameter "customerKey" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "customerKey", r.URL.Query(), ¶ms.CustomerKey, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerKey", Err: err}) + return + } + + // ------------- Optional query parameter "customerPrimaryEmail" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "customerPrimaryEmail", r.URL.Query(), ¶ms.CustomerPrimaryEmail, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerPrimaryEmail", Err: err}) + return + } + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListBillingProfileCustomerOverrides(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteBillingProfileCustomerOverride operation middleware +func (siw *ServerInterfaceWrapper) DeleteBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerId" ------------- + var customerId string + + err = runtime.BindStyledParameterWithOptions("simple", "customerId", chi.URLParam(r, "customerId"), &customerId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteBillingProfileCustomerOverride(w, r, customerId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetBillingProfileCustomerOverride operation middleware +func (siw *ServerInterfaceWrapper) GetBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerId" ------------- + var customerId string + + err = runtime.BindStyledParameterWithOptions("simple", "customerId", chi.URLParam(r, "customerId"), &customerId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetBillingProfileCustomerOverrideParams + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetBillingProfileCustomerOverride(w, r, customerId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpsertBillingProfileCustomerOverride operation middleware +func (siw *ServerInterfaceWrapper) UpsertBillingProfileCustomerOverride(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerId" ------------- + var customerId string + + err = runtime.BindStyledParameterWithOptions("simple", "customerId", chi.URLParam(r, "customerId"), &customerId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpsertBillingProfileCustomerOverride(w, r, customerId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreatePendingInvoiceLine operation middleware +func (siw *ServerInterfaceWrapper) CreatePendingInvoiceLine(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerId" ------------- + var customerId string + + err = runtime.BindStyledParameterWithOptions("simple", "customerId", chi.URLParam(r, "customerId"), &customerId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreatePendingInvoiceLine(w, r, customerId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// SimulateInvoice operation middleware +func (siw *ServerInterfaceWrapper) SimulateInvoice(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerId" ------------- + var customerId string + + err = runtime.BindStyledParameterWithOptions("simple", "customerId", chi.URLParam(r, "customerId"), &customerId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.SimulateInvoice(w, r, customerId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListInvoices operation middleware +func (siw *ServerInterfaceWrapper) ListInvoices(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListInvoicesParams + + // ------------- Optional query parameter "statuses" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "statuses", r.URL.Query(), ¶ms.Statuses, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "statuses", Err: err}) + return + } + + // ------------- Optional query parameter "extendedStatuses" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "extendedStatuses", r.URL.Query(), ¶ms.ExtendedStatuses, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "extendedStatuses", Err: err}) + return + } + + // ------------- Optional query parameter "issuedAfter" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "issuedAfter", r.URL.Query(), ¶ms.IssuedAfter, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "issuedAfter", Err: err}) + return + } + + // ------------- Optional query parameter "issuedBefore" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "issuedBefore", r.URL.Query(), ¶ms.IssuedBefore, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "issuedBefore", Err: err}) + return + } + + // ------------- Optional query parameter "periodStartAfter" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "periodStartAfter", r.URL.Query(), ¶ms.PeriodStartAfter, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "periodStartAfter", Err: err}) + return + } + + // ------------- Optional query parameter "periodStartBefore" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "periodStartBefore", r.URL.Query(), ¶ms.PeriodStartBefore, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "periodStartBefore", Err: err}) + return + } + + // ------------- Optional query parameter "createdAfter" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "createdAfter", r.URL.Query(), ¶ms.CreatedAfter, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "createdAfter", Err: err}) + return + } + + // ------------- Optional query parameter "createdBefore" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "createdBefore", r.URL.Query(), ¶ms.CreatedBefore, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "createdBefore", Err: err}) + return + } + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + // ------------- Optional query parameter "customers" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customers", r.URL.Query(), ¶ms.Customers, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customers", Err: err}) + return + } + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListInvoices(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// InvoicePendingLinesAction operation middleware +func (siw *ServerInterfaceWrapper) InvoicePendingLinesAction(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.InvoicePendingLinesAction(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteInvoice operation middleware +func (siw *ServerInterfaceWrapper) DeleteInvoice(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteInvoice(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetInvoice operation middleware +func (siw *ServerInterfaceWrapper) GetInvoice(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetInvoiceParams + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + // ------------- Optional query parameter "includeDeletedLines" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeletedLines", r.URL.Query(), ¶ms.IncludeDeletedLines, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeletedLines", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetInvoice(w, r, invoiceId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateInvoice operation middleware +func (siw *ServerInterfaceWrapper) UpdateInvoice(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateInvoice(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// AdvanceInvoiceAction operation middleware +func (siw *ServerInterfaceWrapper) AdvanceInvoiceAction(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.AdvanceInvoiceAction(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ApproveInvoiceAction operation middleware +func (siw *ServerInterfaceWrapper) ApproveInvoiceAction(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ApproveInvoiceAction(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// RetryInvoiceAction operation middleware +func (siw *ServerInterfaceWrapper) RetryInvoiceAction(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.RetryInvoiceAction(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// SnapshotQuantitiesInvoiceAction operation middleware +func (siw *ServerInterfaceWrapper) SnapshotQuantitiesInvoiceAction(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.SnapshotQuantitiesInvoiceAction(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// RecalculateInvoiceTaxAction operation middleware +func (siw *ServerInterfaceWrapper) RecalculateInvoiceTaxAction(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.RecalculateInvoiceTaxAction(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// VoidInvoiceAction operation middleware +func (siw *ServerInterfaceWrapper) VoidInvoiceAction(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "invoiceId" ------------- + var invoiceId string + + err = runtime.BindStyledParameterWithOptions("simple", "invoiceId", chi.URLParam(r, "invoiceId"), &invoiceId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "invoiceId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.VoidInvoiceAction(w, r, invoiceId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListBillingProfiles operation middleware +func (siw *ServerInterfaceWrapper) ListBillingProfiles(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListBillingProfilesParams + + // ------------- Optional query parameter "includeArchived" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeArchived", r.URL.Query(), ¶ms.IncludeArchived, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeArchived", Err: err}) + return + } + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListBillingProfiles(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateBillingProfile operation middleware +func (siw *ServerInterfaceWrapper) CreateBillingProfile(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateBillingProfile(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteBillingProfile operation middleware +func (siw *ServerInterfaceWrapper) DeleteBillingProfile(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteBillingProfile(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetBillingProfile operation middleware +func (siw *ServerInterfaceWrapper) GetBillingProfile(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetBillingProfileParams + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetBillingProfile(w, r, id, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateBillingProfile operation middleware +func (siw *ServerInterfaceWrapper) UpdateBillingProfile(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateBillingProfile(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListCustomers operation middleware +func (siw *ServerInterfaceWrapper) ListCustomers(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListCustomersParams + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "key" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "key", r.URL.Query(), ¶ms.Key, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "key", Err: err}) + return + } + + // ------------- Optional query parameter "name" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "name", r.URL.Query(), ¶ms.Name, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "name", Err: err}) + return + } + + // ------------- Optional query parameter "primaryEmail" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "primaryEmail", r.URL.Query(), ¶ms.PrimaryEmail, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "primaryEmail", Err: err}) + return + } + + // ------------- Optional query parameter "subject" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "subject", r.URL.Query(), ¶ms.Subject, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subject", Err: err}) + return + } + + // ------------- Optional query parameter "planKey" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "planKey", r.URL.Query(), ¶ms.PlanKey, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planKey", Err: err}) + return + } + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListCustomers(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateCustomer operation middleware +func (siw *ServerInterfaceWrapper) CreateCustomer(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateCustomer(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteCustomer operation middleware +func (siw *ServerInterfaceWrapper) DeleteCustomer(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteCustomer(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomer operation middleware +func (siw *ServerInterfaceWrapper) GetCustomer(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetCustomerParams + + // ------------- Optional query parameter "expand" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "expand", r.URL.Query(), ¶ms.Expand, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "expand", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomer(w, r, customerIdOrKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateCustomer operation middleware +func (siw *ServerInterfaceWrapper) UpdateCustomer(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateCustomer(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomerAccess operation middleware +func (siw *ServerInterfaceWrapper) GetCustomerAccess(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomerAccess(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListCustomerAppData operation middleware +func (siw *ServerInterfaceWrapper) ListCustomerAppData(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListCustomerAppDataParams + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "type" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "type", r.URL.Query(), ¶ms.Type, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListCustomerAppData(w, r, customerIdOrKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpsertCustomerAppData operation middleware +func (siw *ServerInterfaceWrapper) UpsertCustomerAppData(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpsertCustomerAppData(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteCustomerAppData operation middleware +func (siw *ServerInterfaceWrapper) DeleteCustomerAppData(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "appId" ------------- + var appId string + + err = runtime.BindStyledParameterWithOptions("simple", "appId", chi.URLParam(r, "appId"), &appId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "appId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteCustomerAppData(w, r, customerIdOrKey, appId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomerEntitlementValue operation middleware +func (siw *ServerInterfaceWrapper) GetCustomerEntitlementValue(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "featureKey" ------------- + var featureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "featureKey", chi.URLParam(r, "featureKey"), &featureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "featureKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetCustomerEntitlementValueParams + + // ------------- Optional query parameter "time" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "time", r.URL.Query(), ¶ms.Time, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "time", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomerEntitlementValue(w, r, customerIdOrKey, featureKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomerStripeAppData operation middleware +func (siw *ServerInterfaceWrapper) GetCustomerStripeAppData(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomerStripeAppData(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpsertCustomerStripeAppData operation middleware +func (siw *ServerInterfaceWrapper) UpsertCustomerStripeAppData(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpsertCustomerStripeAppData(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateCustomerStripePortalSession operation middleware +func (siw *ServerInterfaceWrapper) CreateCustomerStripePortalSession(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateCustomerStripePortalSession(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListCustomerSubscriptions operation middleware +func (siw *ServerInterfaceWrapper) ListCustomerSubscriptions(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListCustomerSubscriptionsParams + + // ------------- Optional query parameter "status" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "status", r.URL.Query(), ¶ms.Status, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "status", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListCustomerSubscriptions(w, r, customerIdOrKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetDebugMetrics operation middleware +func (siw *ServerInterfaceWrapper) GetDebugMetrics(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetDebugMetrics(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListEntitlements operation middleware +func (siw *ServerInterfaceWrapper) ListEntitlements(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListEntitlementsParams + + // ------------- Optional query parameter "feature" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "feature", r.URL.Query(), ¶ms.Feature, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "feature", Err: err}) + return + } + + // ------------- Optional query parameter "subject" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "subject", r.URL.Query(), ¶ms.Subject, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subject", Err: err}) + return + } + + // ------------- Optional query parameter "entitlementType" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "entitlementType", r.URL.Query(), ¶ms.EntitlementType, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementType", Err: err}) + return + } + + // ------------- Optional query parameter "excludeInactive" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "excludeInactive", r.URL.Query(), ¶ms.ExcludeInactive, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "excludeInactive", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "offset", r.URL.Query(), ¶ms.Offset, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListEntitlements(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetEntitlementById operation middleware +func (siw *ServerInterfaceWrapper) GetEntitlementById(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "entitlementId" ------------- + var entitlementId string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementId", chi.URLParam(r, "entitlementId"), &entitlementId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetEntitlementById(w, r, entitlementId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListEvents operation middleware +func (siw *ServerInterfaceWrapper) ListEvents(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListEventsParams + + // ------------- Optional query parameter "clientId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "clientId", r.URL.Query(), ¶ms.ClientId, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "clientId", Err: err}) + return + } + + // ------------- Optional query parameter "ingestedAtFrom" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "ingestedAtFrom", r.URL.Query(), ¶ms.IngestedAtFrom, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "ingestedAtFrom", Err: err}) + return + } + + // ------------- Optional query parameter "ingestedAtTo" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "ingestedAtTo", r.URL.Query(), ¶ms.IngestedAtTo, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "ingestedAtTo", Err: err}) + return + } + + // ------------- Optional query parameter "id" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "id", r.URL.Query(), ¶ms.Id, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // ------------- Optional query parameter "subject" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "subject", r.URL.Query(), ¶ms.Subject, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subject", Err: err}) + return + } + + // ------------- Optional query parameter "customerId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customerId", r.URL.Query(), ¶ms.CustomerId, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerId", Err: err}) + return + } + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListEvents(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// IngestEvents operation middleware +func (siw *ServerInterfaceWrapper) IngestEvents(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.IngestEvents(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListFeatures operation middleware +func (siw *ServerInterfaceWrapper) ListFeatures(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListFeaturesParams + + // ------------- Optional query parameter "meterSlug" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "meterSlug", r.URL.Query(), ¶ms.MeterSlug, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterSlug", Err: err}) + return + } + + // ------------- Optional query parameter "includeArchived" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeArchived", r.URL.Query(), ¶ms.IncludeArchived, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeArchived", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "offset", r.URL.Query(), ¶ms.Offset, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListFeatures(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateFeature operation middleware +func (siw *ServerInterfaceWrapper) CreateFeature(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateFeature(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteFeature operation middleware +func (siw *ServerInterfaceWrapper) DeleteFeature(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "featureId" ------------- + var featureId string + + err = runtime.BindStyledParameterWithOptions("simple", "featureId", chi.URLParam(r, "featureId"), &featureId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "featureId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteFeature(w, r, featureId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetFeature operation middleware +func (siw *ServerInterfaceWrapper) GetFeature(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "featureId" ------------- + var featureId string + + err = runtime.BindStyledParameterWithOptions("simple", "featureId", chi.URLParam(r, "featureId"), &featureId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "featureId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetFeature(w, r, featureId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListGrants operation middleware +func (siw *ServerInterfaceWrapper) ListGrants(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListGrantsParams + + // ------------- Optional query parameter "feature" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "feature", r.URL.Query(), ¶ms.Feature, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "feature", Err: err}) + return + } + + // ------------- Optional query parameter "subject" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "subject", r.URL.Query(), ¶ms.Subject, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subject", Err: err}) + return + } + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "offset", r.URL.Query(), ¶ms.Offset, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListGrants(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// VoidGrant operation middleware +func (siw *ServerInterfaceWrapper) VoidGrant(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "grantId" ------------- + var grantId string + + err = runtime.BindStyledParameterWithOptions("simple", "grantId", chi.URLParam(r, "grantId"), &grantId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "grantId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params VoidGrantParams + + // ------------- Optional query parameter "at" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "at", r.URL.Query(), ¶ms.At, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "at", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.VoidGrant(w, r, grantId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListCurrencies operation middleware +func (siw *ServerInterfaceWrapper) ListCurrencies(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListCurrencies(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetProgress operation middleware +func (siw *ServerInterfaceWrapper) GetProgress(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "id" ------------- + var id string + + err = runtime.BindStyledParameterWithOptions("simple", "id", chi.URLParam(r, "id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetProgress(w, r, id) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListMarketplaceListings operation middleware +func (siw *ServerInterfaceWrapper) ListMarketplaceListings(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListMarketplaceListingsParams + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListMarketplaceListings(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetMarketplaceListing operation middleware +func (siw *ServerInterfaceWrapper) GetMarketplaceListing(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "type" ------------- + var pType AppType + + err = runtime.BindStyledParameterWithOptions("simple", "type", chi.URLParam(r, "type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetMarketplaceListing(w, r, pType) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// MarketplaceAppInstall operation middleware +func (siw *ServerInterfaceWrapper) MarketplaceAppInstall(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "type" ------------- + var pType MarketplaceInstallRequestType + + err = runtime.BindStyledParameterWithOptions("simple", "type", chi.URLParam(r, "type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.MarketplaceAppInstall(w, r, pType) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// MarketplaceAppAPIKeyInstall operation middleware +func (siw *ServerInterfaceWrapper) MarketplaceAppAPIKeyInstall(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "type" ------------- + var pType MarketplaceApiKeyInstallRequestType + + err = runtime.BindStyledParameterWithOptions("simple", "type", chi.URLParam(r, "type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.MarketplaceAppAPIKeyInstall(w, r, pType) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// MarketplaceOAuth2InstallGetURL operation middleware +func (siw *ServerInterfaceWrapper) MarketplaceOAuth2InstallGetURL(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "type" ------------- + var pType AppType + + err = runtime.BindStyledParameterWithOptions("simple", "type", chi.URLParam(r, "type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.MarketplaceOAuth2InstallGetURL(w, r, pType) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// MarketplaceOAuth2InstallAuthorize operation middleware +func (siw *ServerInterfaceWrapper) MarketplaceOAuth2InstallAuthorize(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "type" ------------- + var pType MarketplaceOAuth2InstallAuthorizeRequestType + + err = runtime.BindStyledParameterWithOptions("simple", "type", chi.URLParam(r, "type"), &pType, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params MarketplaceOAuth2InstallAuthorizeParams + + // ------------- Optional query parameter "state" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "state", r.URL.Query(), ¶ms.State, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "state", Err: err}) + return + } + + // ------------- Optional query parameter "code" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "code", r.URL.Query(), ¶ms.Code, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "code", Err: err}) + return + } + + // ------------- Optional query parameter "error" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "error", r.URL.Query(), ¶ms.Error, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "error", Err: err}) + return + } + + // ------------- Optional query parameter "error_description" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "error_description", r.URL.Query(), ¶ms.ErrorDescription, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "error_description", Err: err}) + return + } + + // ------------- Optional query parameter "error_uri" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "error_uri", r.URL.Query(), ¶ms.ErrorUri, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "error_uri", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.MarketplaceOAuth2InstallAuthorize(w, r, pType, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListMeters operation middleware +func (siw *ServerInterfaceWrapper) ListMeters(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListMetersParams + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListMeters(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateMeter operation middleware +func (siw *ServerInterfaceWrapper) CreateMeter(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateMeter(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteMeter operation middleware +func (siw *ServerInterfaceWrapper) DeleteMeter(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteMeter(w, r, meterIdOrSlug) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetMeter operation middleware +func (siw *ServerInterfaceWrapper) GetMeter(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetMeter(w, r, meterIdOrSlug) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateMeter operation middleware +func (siw *ServerInterfaceWrapper) UpdateMeter(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateMeter(w, r, meterIdOrSlug) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListMeterGroupByValues operation middleware +func (siw *ServerInterfaceWrapper) ListMeterGroupByValues(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + // ------------- Path parameter "groupByKey" ------------- + var groupByKey string + + err = runtime.BindStyledParameterWithOptions("simple", "groupByKey", chi.URLParam(r, "groupByKey"), &groupByKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "groupByKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListMeterGroupByValuesParams + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListMeterGroupByValues(w, r, meterIdOrSlug, groupByKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// QueryMeter operation middleware +func (siw *ServerInterfaceWrapper) QueryMeter(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params QueryMeterParams + + // ------------- Optional query parameter "clientId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "clientId", r.URL.Query(), ¶ms.ClientId, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "clientId", Err: err}) + return + } + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + // ------------- Optional query parameter "windowSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "windowSize", r.URL.Query(), ¶ms.WindowSize, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowSize", Err: err}) + return + } + + // ------------- Optional query parameter "windowTimeZone" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "windowTimeZone", r.URL.Query(), ¶ms.WindowTimeZone, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowTimeZone", Err: err}) + return + } + + // ------------- Optional query parameter "subject" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "subject", r.URL.Query(), ¶ms.Subject, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subject", Err: err}) + return + } + + // ------------- Optional query parameter "filterCustomerId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "filterCustomerId", r.URL.Query(), ¶ms.FilterCustomerId, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "filterCustomerId", Err: err}) + return + } + + // ------------- Optional query parameter "filterGroupBy" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, false, "filterGroupBy", r.URL.Query(), ¶ms.FilterGroupBy, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "filterGroupBy", Err: err}) + return + } + + // ------------- Optional query parameter "advancedMeterGroupByFilters" ------------- + + if paramValue := r.URL.Query().Get("advancedMeterGroupByFilters"); paramValue != "" { + + var value MeterQueryAdvancedMeterGroupByFilters + err = json.Unmarshal([]byte(paramValue), &value) + if err != nil { + siw.ErrorHandlerFunc(w, r, &UnmarshalingParamError{ParamName: "advancedMeterGroupByFilters", Err: err}) + return + } + + params.AdvancedMeterGroupByFilters = &value + + } + + // ------------- Optional query parameter "groupBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "groupBy", r.URL.Query(), ¶ms.GroupBy, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "groupBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.QueryMeter(w, r, meterIdOrSlug, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// QueryMeterPost operation middleware +func (siw *ServerInterfaceWrapper) QueryMeterPost(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.QueryMeterPost(w, r, meterIdOrSlug) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListMeterSubjects operation middleware +func (siw *ServerInterfaceWrapper) ListMeterSubjects(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterIdOrSlug" ------------- + var meterIdOrSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterIdOrSlug", chi.URLParam(r, "meterIdOrSlug"), &meterIdOrSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterIdOrSlug", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListMeterSubjectsParams + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListMeterSubjects(w, r, meterIdOrSlug, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListNotificationChannels operation middleware +func (siw *ServerInterfaceWrapper) ListNotificationChannels(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListNotificationChannelsParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "includeDisabled" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDisabled", r.URL.Query(), ¶ms.IncludeDisabled, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDisabled", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListNotificationChannels(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateNotificationChannel operation middleware +func (siw *ServerInterfaceWrapper) CreateNotificationChannel(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateNotificationChannel(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteNotificationChannel operation middleware +func (siw *ServerInterfaceWrapper) DeleteNotificationChannel(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "channelId" ------------- + var channelId string + + err = runtime.BindStyledParameterWithOptions("simple", "channelId", chi.URLParam(r, "channelId"), &channelId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "channelId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteNotificationChannel(w, r, channelId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetNotificationChannel operation middleware +func (siw *ServerInterfaceWrapper) GetNotificationChannel(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "channelId" ------------- + var channelId string + + err = runtime.BindStyledParameterWithOptions("simple", "channelId", chi.URLParam(r, "channelId"), &channelId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "channelId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetNotificationChannel(w, r, channelId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateNotificationChannel operation middleware +func (siw *ServerInterfaceWrapper) UpdateNotificationChannel(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "channelId" ------------- + var channelId string + + err = runtime.BindStyledParameterWithOptions("simple", "channelId", chi.URLParam(r, "channelId"), &channelId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "channelId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateNotificationChannel(w, r, channelId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListNotificationEvents operation middleware +func (siw *ServerInterfaceWrapper) ListNotificationEvents(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListNotificationEventsParams + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + // ------------- Optional query parameter "feature" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "feature", r.URL.Query(), ¶ms.Feature, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "feature", Err: err}) + return + } + + // ------------- Optional query parameter "subject" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "subject", r.URL.Query(), ¶ms.Subject, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subject", Err: err}) + return + } + + // ------------- Optional query parameter "rule" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "rule", r.URL.Query(), ¶ms.Rule, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "rule", Err: err}) + return + } + + // ------------- Optional query parameter "channel" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "channel", r.URL.Query(), ¶ms.Channel, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "channel", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListNotificationEvents(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetNotificationEvent operation middleware +func (siw *ServerInterfaceWrapper) GetNotificationEvent(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "eventId" ------------- + var eventId string + + err = runtime.BindStyledParameterWithOptions("simple", "eventId", chi.URLParam(r, "eventId"), &eventId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "eventId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetNotificationEvent(w, r, eventId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ResendNotificationEvent operation middleware +func (siw *ServerInterfaceWrapper) ResendNotificationEvent(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "eventId" ------------- + var eventId string + + err = runtime.BindStyledParameterWithOptions("simple", "eventId", chi.URLParam(r, "eventId"), &eventId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "eventId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ResendNotificationEvent(w, r, eventId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListNotificationRules operation middleware +func (siw *ServerInterfaceWrapper) ListNotificationRules(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListNotificationRulesParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "includeDisabled" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDisabled", r.URL.Query(), ¶ms.IncludeDisabled, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDisabled", Err: err}) + return + } + + // ------------- Optional query parameter "feature" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "feature", r.URL.Query(), ¶ms.Feature, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "feature", Err: err}) + return + } + + // ------------- Optional query parameter "channel" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "channel", r.URL.Query(), ¶ms.Channel, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "channel", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListNotificationRules(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateNotificationRule operation middleware +func (siw *ServerInterfaceWrapper) CreateNotificationRule(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateNotificationRule(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteNotificationRule operation middleware +func (siw *ServerInterfaceWrapper) DeleteNotificationRule(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "ruleId" ------------- + var ruleId string + + err = runtime.BindStyledParameterWithOptions("simple", "ruleId", chi.URLParam(r, "ruleId"), &ruleId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "ruleId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteNotificationRule(w, r, ruleId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetNotificationRule operation middleware +func (siw *ServerInterfaceWrapper) GetNotificationRule(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "ruleId" ------------- + var ruleId string + + err = runtime.BindStyledParameterWithOptions("simple", "ruleId", chi.URLParam(r, "ruleId"), &ruleId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "ruleId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetNotificationRule(w, r, ruleId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateNotificationRule operation middleware +func (siw *ServerInterfaceWrapper) UpdateNotificationRule(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "ruleId" ------------- + var ruleId string + + err = runtime.BindStyledParameterWithOptions("simple", "ruleId", chi.URLParam(r, "ruleId"), &ruleId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "ruleId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateNotificationRule(w, r, ruleId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// TestNotificationRule operation middleware +func (siw *ServerInterfaceWrapper) TestNotificationRule(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "ruleId" ------------- + var ruleId string + + err = runtime.BindStyledParameterWithOptions("simple", "ruleId", chi.URLParam(r, "ruleId"), &ruleId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "ruleId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.TestNotificationRule(w, r, ruleId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListPlans operation middleware +func (siw *ServerInterfaceWrapper) ListPlans(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListPlansParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "id" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "id", r.URL.Query(), ¶ms.Id, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // ------------- Optional query parameter "key" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "key", r.URL.Query(), ¶ms.Key, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "key", Err: err}) + return + } + + // ------------- Optional query parameter "keyVersion" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, false, "keyVersion", r.URL.Query(), ¶ms.KeyVersion, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "keyVersion", Err: err}) + return + } + + // ------------- Optional query parameter "status" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "status", r.URL.Query(), ¶ms.Status, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "status", Err: err}) + return + } + + // ------------- Optional query parameter "currency" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "currency", r.URL.Query(), ¶ms.Currency, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "currency", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListPlans(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreatePlan operation middleware +func (siw *ServerInterfaceWrapper) CreatePlan(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreatePlan(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// NextPlan operation middleware +func (siw *ServerInterfaceWrapper) NextPlan(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planIdOrKey" ------------- + var planIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "planIdOrKey", chi.URLParam(r, "planIdOrKey"), &planIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.NextPlan(w, r, planIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeletePlan operation middleware +func (siw *ServerInterfaceWrapper) DeletePlan(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeletePlan(w, r, planId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetPlan operation middleware +func (siw *ServerInterfaceWrapper) GetPlan(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetPlanParams + + // ------------- Optional query parameter "includeLatest" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeLatest", r.URL.Query(), ¶ms.IncludeLatest, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeLatest", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetPlan(w, r, planId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdatePlan operation middleware +func (siw *ServerInterfaceWrapper) UpdatePlan(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdatePlan(w, r, planId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListPlanAddons operation middleware +func (siw *ServerInterfaceWrapper) ListPlanAddons(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListPlanAddonsParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "id" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "id", r.URL.Query(), ¶ms.Id, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + // ------------- Optional query parameter "key" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "key", r.URL.Query(), ¶ms.Key, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "key", Err: err}) + return + } + + // ------------- Optional query parameter "keyVersion" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, false, "keyVersion", r.URL.Query(), ¶ms.KeyVersion, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "keyVersion", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListPlanAddons(w, r, planId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreatePlanAddon operation middleware +func (siw *ServerInterfaceWrapper) CreatePlanAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreatePlanAddon(w, r, planId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeletePlanAddon operation middleware +func (siw *ServerInterfaceWrapper) DeletePlanAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + // ------------- Path parameter "planAddonId" ------------- + var planAddonId string + + err = runtime.BindStyledParameterWithOptions("simple", "planAddonId", chi.URLParam(r, "planAddonId"), &planAddonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planAddonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeletePlanAddon(w, r, planId, planAddonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetPlanAddon operation middleware +func (siw *ServerInterfaceWrapper) GetPlanAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + // ------------- Path parameter "planAddonId" ------------- + var planAddonId string + + err = runtime.BindStyledParameterWithOptions("simple", "planAddonId", chi.URLParam(r, "planAddonId"), &planAddonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planAddonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetPlanAddon(w, r, planId, planAddonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdatePlanAddon operation middleware +func (siw *ServerInterfaceWrapper) UpdatePlanAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + // ------------- Path parameter "planAddonId" ------------- + var planAddonId string + + err = runtime.BindStyledParameterWithOptions("simple", "planAddonId", chi.URLParam(r, "planAddonId"), &planAddonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planAddonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdatePlanAddon(w, r, planId, planAddonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ArchivePlan operation middleware +func (siw *ServerInterfaceWrapper) ArchivePlan(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ArchivePlan(w, r, planId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// PublishPlan operation middleware +func (siw *ServerInterfaceWrapper) PublishPlan(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "planId" ------------- + var planId string + + err = runtime.BindStyledParameterWithOptions("simple", "planId", chi.URLParam(r, "planId"), &planId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "planId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.PublishPlan(w, r, planId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// QueryPortalMeter operation middleware +func (siw *ServerInterfaceWrapper) QueryPortalMeter(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "meterSlug" ------------- + var meterSlug string + + err = runtime.BindStyledParameterWithOptions("simple", "meterSlug", chi.URLParam(r, "meterSlug"), &meterSlug, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "meterSlug", Err: err}) + return + } + + ctx := r.Context() + + ctx = context.WithValue(ctx, PortalTokenAuthScopes, []string{}) + + r = r.WithContext(ctx) + + // Parameter object where we will unmarshal all parameters from the context + var params QueryPortalMeterParams + + // ------------- Optional query parameter "clientId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "clientId", r.URL.Query(), ¶ms.ClientId, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "clientId", Err: err}) + return + } + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + // ------------- Optional query parameter "windowSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "windowSize", r.URL.Query(), ¶ms.WindowSize, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowSize", Err: err}) + return + } + + // ------------- Optional query parameter "windowTimeZone" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "windowTimeZone", r.URL.Query(), ¶ms.WindowTimeZone, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowTimeZone", Err: err}) + return + } + + // ------------- Optional query parameter "filterCustomerId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "filterCustomerId", r.URL.Query(), ¶ms.FilterCustomerId, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "filterCustomerId", Err: err}) + return + } + + // ------------- Optional query parameter "filterGroupBy" ------------- + + err = runtime.BindQueryParameterWithOptions("deepObject", true, false, "filterGroupBy", r.URL.Query(), ¶ms.FilterGroupBy, runtime.BindQueryParameterOptions{Type: "object", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "filterGroupBy", Err: err}) + return + } + + // ------------- Optional query parameter "advancedMeterGroupByFilters" ------------- + + if paramValue := r.URL.Query().Get("advancedMeterGroupByFilters"); paramValue != "" { + + var value MeterQueryAdvancedMeterGroupByFilters + err = json.Unmarshal([]byte(paramValue), &value) + if err != nil { + siw.ErrorHandlerFunc(w, r, &UnmarshalingParamError{ParamName: "advancedMeterGroupByFilters", Err: err}) + return + } + + params.AdvancedMeterGroupByFilters = &value + + } + + // ------------- Optional query parameter "groupBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "groupBy", r.URL.Query(), ¶ms.GroupBy, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "groupBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.QueryPortalMeter(w, r, meterSlug, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListPortalTokens operation middleware +func (siw *ServerInterfaceWrapper) ListPortalTokens(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListPortalTokensParams + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListPortalTokens(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreatePortalToken operation middleware +func (siw *ServerInterfaceWrapper) CreatePortalToken(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreatePortalToken(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// InvalidatePortalTokens operation middleware +func (siw *ServerInterfaceWrapper) InvalidatePortalTokens(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.InvalidatePortalTokens(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateStripeCheckoutSession operation middleware +func (siw *ServerInterfaceWrapper) CreateStripeCheckoutSession(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateStripeCheckoutSession(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListSubjects operation middleware +func (siw *ServerInterfaceWrapper) ListSubjects(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListSubjects(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpsertSubject operation middleware +func (siw *ServerInterfaceWrapper) UpsertSubject(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpsertSubject(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteSubject operation middleware +func (siw *ServerInterfaceWrapper) DeleteSubject(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteSubject(w, r, subjectIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetSubject operation middleware +func (siw *ServerInterfaceWrapper) GetSubject(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetSubject(w, r, subjectIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListSubjectEntitlements operation middleware +func (siw *ServerInterfaceWrapper) ListSubjectEntitlements(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListSubjectEntitlementsParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListSubjectEntitlements(w, r, subjectIdOrKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateEntitlement operation middleware +func (siw *ServerInterfaceWrapper) CreateEntitlement(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateEntitlement(w, r, subjectIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListEntitlementGrants operation middleware +func (siw *ServerInterfaceWrapper) ListEntitlementGrants(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListEntitlementGrantsParams + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListEntitlementGrants(w, r, subjectIdOrKey, entitlementIdOrFeatureKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateGrant operation middleware +func (siw *ServerInterfaceWrapper) CreateGrant(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateGrant(w, r, subjectIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// OverrideEntitlement operation middleware +func (siw *ServerInterfaceWrapper) OverrideEntitlement(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.OverrideEntitlement(w, r, subjectIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetEntitlementValue operation middleware +func (siw *ServerInterfaceWrapper) GetEntitlementValue(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetEntitlementValueParams + + // ------------- Optional query parameter "time" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "time", r.URL.Query(), ¶ms.Time, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "time", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetEntitlementValue(w, r, subjectIdOrKey, entitlementIdOrFeatureKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteEntitlement operation middleware +func (siw *ServerInterfaceWrapper) DeleteEntitlement(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementId" ------------- + var entitlementId string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementId", chi.URLParam(r, "entitlementId"), &entitlementId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteEntitlement(w, r, subjectIdOrKey, entitlementId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetEntitlement operation middleware +func (siw *ServerInterfaceWrapper) GetEntitlement(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementId" ------------- + var entitlementId string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementId", chi.URLParam(r, "entitlementId"), &entitlementId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetEntitlement(w, r, subjectIdOrKey, entitlementId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetEntitlementHistory operation middleware +func (siw *ServerInterfaceWrapper) GetEntitlementHistory(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementId" ------------- + var entitlementId string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementId", chi.URLParam(r, "entitlementId"), &entitlementId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetEntitlementHistoryParams + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + // ------------- Required query parameter "windowSize" ------------- + + if paramValue := r.URL.Query().Get("windowSize"); paramValue != "" { + + } else { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "windowSize"}) + return + } + + err = runtime.BindQueryParameterWithOptions("form", false, true, "windowSize", r.URL.Query(), ¶ms.WindowSize, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowSize", Err: err}) + return + } + + // ------------- Optional query parameter "windowTimeZone" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "windowTimeZone", r.URL.Query(), ¶ms.WindowTimeZone, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowTimeZone", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetEntitlementHistory(w, r, subjectIdOrKey, entitlementId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ResetEntitlementUsage operation middleware +func (siw *ServerInterfaceWrapper) ResetEntitlementUsage(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subjectIdOrKey" ------------- + var subjectIdOrKey string + + err = runtime.BindStyledParameterWithOptions("simple", "subjectIdOrKey", chi.URLParam(r, "subjectIdOrKey"), &subjectIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subjectIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementId" ------------- + var entitlementId string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementId", chi.URLParam(r, "entitlementId"), &entitlementId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ResetEntitlementUsage(w, r, subjectIdOrKey, entitlementId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateSubscription operation middleware +func (siw *ServerInterfaceWrapper) CreateSubscription(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateSubscription(w, r) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteSubscription operation middleware +func (siw *ServerInterfaceWrapper) DeleteSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteSubscription(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetSubscription operation middleware +func (siw *ServerInterfaceWrapper) GetSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetSubscriptionParams + + // ------------- Optional query parameter "at" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "at", r.URL.Query(), ¶ms.At, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "at", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetSubscription(w, r, subscriptionId, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// EditSubscription operation middleware +func (siw *ServerInterfaceWrapper) EditSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.EditSubscription(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListSubscriptionAddons operation middleware +func (siw *ServerInterfaceWrapper) ListSubscriptionAddons(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListSubscriptionAddons(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateSubscriptionAddon operation middleware +func (siw *ServerInterfaceWrapper) CreateSubscriptionAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateSubscriptionAddon(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetSubscriptionAddon operation middleware +func (siw *ServerInterfaceWrapper) GetSubscriptionAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + // ------------- Path parameter "subscriptionAddonId" ------------- + var subscriptionAddonId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionAddonId", chi.URLParam(r, "subscriptionAddonId"), &subscriptionAddonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionAddonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetSubscriptionAddon(w, r, subscriptionId, subscriptionAddonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UpdateSubscriptionAddon operation middleware +func (siw *ServerInterfaceWrapper) UpdateSubscriptionAddon(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + // ------------- Path parameter "subscriptionAddonId" ------------- + var subscriptionAddonId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionAddonId", chi.URLParam(r, "subscriptionAddonId"), &subscriptionAddonId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionAddonId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UpdateSubscriptionAddon(w, r, subscriptionId, subscriptionAddonId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CancelSubscription operation middleware +func (siw *ServerInterfaceWrapper) CancelSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CancelSubscription(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ChangeSubscription operation middleware +func (siw *ServerInterfaceWrapper) ChangeSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ChangeSubscription(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// MigrateSubscription operation middleware +func (siw *ServerInterfaceWrapper) MigrateSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.MigrateSubscription(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// RestoreSubscription operation middleware +func (siw *ServerInterfaceWrapper) RestoreSubscription(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.RestoreSubscription(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// UnscheduleCancelation operation middleware +func (siw *ServerInterfaceWrapper) UnscheduleCancelation(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "subscriptionId" ------------- + var subscriptionId string + + err = runtime.BindStyledParameterWithOptions("simple", "subscriptionId", chi.URLParam(r, "subscriptionId"), &subscriptionId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "subscriptionId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.UnscheduleCancelation(w, r, subscriptionId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListCustomerEntitlementsV2 operation middleware +func (siw *ServerInterfaceWrapper) ListCustomerEntitlementsV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListCustomerEntitlementsV2Params + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListCustomerEntitlementsV2(w, r, customerIdOrKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateCustomerEntitlementV2 operation middleware +func (siw *ServerInterfaceWrapper) CreateCustomerEntitlementV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateCustomerEntitlementV2(w, r, customerIdOrKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// DeleteCustomerEntitlementV2 operation middleware +func (siw *ServerInterfaceWrapper) DeleteCustomerEntitlementV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.DeleteCustomerEntitlementV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomerEntitlementV2 operation middleware +func (siw *ServerInterfaceWrapper) GetCustomerEntitlementV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomerEntitlementV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListCustomerEntitlementGrantsV2 operation middleware +func (siw *ServerInterfaceWrapper) ListCustomerEntitlementGrantsV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params ListCustomerEntitlementGrantsV2Params + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "offset", r.URL.Query(), ¶ms.Offset, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListCustomerEntitlementGrantsV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateCustomerEntitlementGrantV2 operation middleware +func (siw *ServerInterfaceWrapper) CreateCustomerEntitlementGrantV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateCustomerEntitlementGrantV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomerEntitlementHistoryV2 operation middleware +func (siw *ServerInterfaceWrapper) GetCustomerEntitlementHistoryV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetCustomerEntitlementHistoryV2Params + + // ------------- Optional query parameter "from" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "from", r.URL.Query(), ¶ms.From, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "from", Err: err}) + return + } + + // ------------- Optional query parameter "to" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "to", r.URL.Query(), ¶ms.To, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "to", Err: err}) + return + } + + // ------------- Required query parameter "windowSize" ------------- + + if paramValue := r.URL.Query().Get("windowSize"); paramValue != "" { + + } else { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "windowSize"}) + return + } + + err = runtime.BindQueryParameterWithOptions("form", false, true, "windowSize", r.URL.Query(), ¶ms.WindowSize, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowSize", Err: err}) + return + } + + // ------------- Optional query parameter "windowTimeZone" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "windowTimeZone", r.URL.Query(), ¶ms.WindowTimeZone, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "windowTimeZone", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomerEntitlementHistoryV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// OverrideCustomerEntitlementV2 operation middleware +func (siw *ServerInterfaceWrapper) OverrideCustomerEntitlementV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.OverrideCustomerEntitlementV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ResetCustomerEntitlementUsageV2 operation middleware +func (siw *ServerInterfaceWrapper) ResetCustomerEntitlementUsageV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ResetCustomerEntitlementUsageV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetCustomerEntitlementValueV2 operation middleware +func (siw *ServerInterfaceWrapper) GetCustomerEntitlementValueV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "customerIdOrKey" ------------- + var customerIdOrKey ULIDOrExternalKey + + err = runtime.BindStyledParameterWithOptions("simple", "customerIdOrKey", chi.URLParam(r, "customerIdOrKey"), &customerIdOrKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIdOrKey", Err: err}) + return + } + + // ------------- Path parameter "entitlementIdOrFeatureKey" ------------- + var entitlementIdOrFeatureKey string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementIdOrFeatureKey", chi.URLParam(r, "entitlementIdOrFeatureKey"), &entitlementIdOrFeatureKey, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementIdOrFeatureKey", Err: err}) + return + } + + // Parameter object where we will unmarshal all parameters from the context + var params GetCustomerEntitlementValueV2Params + + // ------------- Optional query parameter "time" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "time", r.URL.Query(), ¶ms.Time, runtime.BindQueryParameterOptions{Type: "string", Format: "date-time"}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "time", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetCustomerEntitlementValueV2(w, r, customerIdOrKey, entitlementIdOrFeatureKey, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListEntitlementsV2 operation middleware +func (siw *ServerInterfaceWrapper) ListEntitlementsV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListEntitlementsV2Params + + // ------------- Optional query parameter "feature" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "feature", r.URL.Query(), ¶ms.Feature, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "feature", Err: err}) + return + } + + // ------------- Optional query parameter "customerKeys" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customerKeys", r.URL.Query(), ¶ms.CustomerKeys, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerKeys", Err: err}) + return + } + + // ------------- Optional query parameter "customerIds" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customerIds", r.URL.Query(), ¶ms.CustomerIds, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customerIds", Err: err}) + return + } + + // ------------- Optional query parameter "entitlementType" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "entitlementType", r.URL.Query(), ¶ms.EntitlementType, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementType", Err: err}) + return + } + + // ------------- Optional query parameter "excludeInactive" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "excludeInactive", r.URL.Query(), ¶ms.ExcludeInactive, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "excludeInactive", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "offset", r.URL.Query(), ¶ms.Offset, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListEntitlementsV2(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// GetEntitlementByIdV2 operation middleware +func (siw *ServerInterfaceWrapper) GetEntitlementByIdV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // ------------- Path parameter "entitlementId" ------------- + var entitlementId string + + err = runtime.BindStyledParameterWithOptions("simple", "entitlementId", chi.URLParam(r, "entitlementId"), &entitlementId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "entitlementId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetEntitlementByIdV2(w, r, entitlementId) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListEventsV2 operation middleware +func (siw *ServerInterfaceWrapper) ListEventsV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListEventsV2Params + + // ------------- Optional query parameter "cursor" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "cursor", r.URL.Query(), ¶ms.Cursor, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "cursor", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "clientId" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "clientId", r.URL.Query(), ¶ms.ClientId, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "clientId", Err: err}) + return + } + + // ------------- Optional query parameter "filter" ------------- + + if paramValue := r.URL.Query().Get("filter"); paramValue != "" { + + var value struct { + // CustomerId A filter for a ID (ULID) field allowing only equality or inclusion. + CustomerId *FilterIDExact `json:"customerId,omitempty"` + + // Id A filter for a string field. + Id *FilterString `json:"id,omitempty"` + + // IngestedAt A filter for a time field. + IngestedAt *FilterTime `json:"ingestedAt,omitempty"` + + // Source A filter for a string field. + Source *FilterString `json:"source,omitempty"` + + // Subject A filter for a string field. + Subject *FilterString `json:"subject,omitempty"` + + // Time A filter for a time field. + Time *FilterTime `json:"time,omitempty"` + + // Type A filter for a string field. + Type *FilterString `json:"type,omitempty"` + } + err = json.Unmarshal([]byte(paramValue), &value) + if err != nil { + siw.ErrorHandlerFunc(w, r, &UnmarshalingParamError{ParamName: "filter", Err: err}) + return + } + + params.Filter = &value + + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListEventsV2(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +// ListGrantsV2 operation middleware +func (siw *ServerInterfaceWrapper) ListGrantsV2(w http.ResponseWriter, r *http.Request) { + + var err error + + // Parameter object where we will unmarshal all parameters from the context + var params ListGrantsV2Params + + // ------------- Optional query parameter "feature" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "feature", r.URL.Query(), ¶ms.Feature, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "feature", Err: err}) + return + } + + // ------------- Optional query parameter "customer" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "customer", r.URL.Query(), ¶ms.Customer, runtime.BindQueryParameterOptions{Type: "array", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "customer", Err: err}) + return + } + + // ------------- Optional query parameter "includeDeleted" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "includeDeleted", r.URL.Query(), ¶ms.IncludeDeleted, runtime.BindQueryParameterOptions{Type: "boolean", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "includeDeleted", Err: err}) + return + } + + // ------------- Optional query parameter "page" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "page", r.URL.Query(), ¶ms.Page, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "page", Err: err}) + return + } + + // ------------- Optional query parameter "pageSize" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "pageSize", r.URL.Query(), ¶ms.PageSize, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "pageSize", Err: err}) + return + } + + // ------------- Optional query parameter "offset" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "offset", r.URL.Query(), ¶ms.Offset, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "offset", Err: err}) + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + return + } + + // ------------- Optional query parameter "order" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "order", r.URL.Query(), ¶ms.Order, runtime.BindQueryParameterOptions{Type: "", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "order", Err: err}) + return + } + + // ------------- Optional query parameter "orderBy" ------------- + + err = runtime.BindQueryParameterWithOptions("form", false, false, "orderBy", r.URL.Query(), ¶ms.OrderBy, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "orderBy", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListGrantsV2(w, r, params) + })) + + for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- { + handler = siw.HandlerMiddlewares[i](handler) + } + + handler.ServeHTTP(w, r) +} + +type UnescapedCookieParamError struct { + ParamName string + Err error +} + +func (e *UnescapedCookieParamError) Error() string { + return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) +} + +func (e *UnescapedCookieParamError) Unwrap() error { + return e.Err +} + +type UnmarshalingParamError struct { + ParamName string + Err error +} + +func (e *UnmarshalingParamError) Error() string { + return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) +} + +func (e *UnmarshalingParamError) Unwrap() error { + return e.Err +} + +type RequiredParamError struct { + ParamName string +} + +func (e *RequiredParamError) Error() string { + return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) +} + +type RequiredHeaderError struct { + ParamName string + Err error +} + +func (e *RequiredHeaderError) Error() string { + return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) +} + +func (e *RequiredHeaderError) Unwrap() error { + return e.Err +} + +type InvalidParamFormatError struct { + ParamName string + Err error +} + +func (e *InvalidParamFormatError) Error() string { + return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) +} + +func (e *InvalidParamFormatError) Unwrap() error { + return e.Err +} + +type TooManyValuesForParamError struct { + ParamName string + Count int +} + +func (e *TooManyValuesForParamError) Error() string { + return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) +} + +// Handler creates http.Handler with routing matching OpenAPI spec. +func Handler(si ServerInterface) http.Handler { + return HandlerWithOptions(si, ChiServerOptions{}) +} + +type ChiServerOptions struct { + BaseURL string + BaseRouter chi.Router + Middlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. +func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler { + return HandlerWithOptions(si, ChiServerOptions{ + BaseRouter: r, + }) +} + +func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler { + return HandlerWithOptions(si, ChiServerOptions{ + BaseURL: baseURL, + BaseRouter: r, + }) +} + +// HandlerWithOptions creates http.Handler with additional options +func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler { + r := options.BaseRouter + + if r == nil { + r = chi.NewRouter() + } + if options.ErrorHandlerFunc == nil { + options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } + wrapper := ServerInterfaceWrapper{ + Handler: si, + HandlerMiddlewares: options.Middlewares, + ErrorHandlerFunc: options.ErrorHandlerFunc, + } + + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/addons", wrapper.ListAddons) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/addons", wrapper.CreateAddon) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/addons/{addonId}", wrapper.DeleteAddon) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/addons/{addonId}", wrapper.GetAddon) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/addons/{addonId}", wrapper.UpdateAddon) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/addons/{addonId}/archive", wrapper.ArchiveAddon) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/addons/{addonId}/publish", wrapper.PublishAddon) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/apps", wrapper.ListApps) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized", wrapper.AppCustomInvoicingDraftSynchronized) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized", wrapper.AppCustomInvoicingIssuingSynchronized) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/apps/custom-invoicing/{invoiceId}/payment/status", wrapper.AppCustomInvoicingUpdatePaymentStatus) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/apps/{id}", wrapper.UninstallApp) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/apps/{id}", wrapper.GetApp) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/apps/{id}", wrapper.UpdateApp) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/apps/{id}/stripe/api-key", wrapper.UpdateStripeAPIKey) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/apps/{id}/stripe/webhook", wrapper.AppStripeWebhook) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/billing/customers", wrapper.ListBillingProfileCustomerOverrides) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/billing/customers/{customerId}", wrapper.DeleteBillingProfileCustomerOverride) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/billing/customers/{customerId}", wrapper.GetBillingProfileCustomerOverride) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/billing/customers/{customerId}", wrapper.UpsertBillingProfileCustomerOverride) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/customers/{customerId}/invoices/pending-lines", wrapper.CreatePendingInvoiceLine) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/customers/{customerId}/invoices/simulate", wrapper.SimulateInvoice) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/billing/invoices", wrapper.ListInvoices) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/invoice", wrapper.InvoicePendingLinesAction) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}", wrapper.DeleteInvoice) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}", wrapper.GetInvoice) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}", wrapper.UpdateInvoice) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}/advance", wrapper.AdvanceInvoiceAction) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}/approve", wrapper.ApproveInvoiceAction) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}/retry", wrapper.RetryInvoiceAction) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}/snapshot-quantities", wrapper.SnapshotQuantitiesInvoiceAction) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}/taxes/recalculate", wrapper.RecalculateInvoiceTaxAction) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/invoices/{invoiceId}/void", wrapper.VoidInvoiceAction) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/billing/profiles", wrapper.ListBillingProfiles) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/billing/profiles", wrapper.CreateBillingProfile) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/billing/profiles/{id}", wrapper.DeleteBillingProfile) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/billing/profiles/{id}", wrapper.GetBillingProfile) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/billing/profiles/{id}", wrapper.UpdateBillingProfile) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers", wrapper.ListCustomers) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/customers", wrapper.CreateCustomer) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/customers/{customerIdOrKey}", wrapper.DeleteCustomer) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers/{customerIdOrKey}", wrapper.GetCustomer) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/customers/{customerIdOrKey}", wrapper.UpdateCustomer) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/access", wrapper.GetCustomerAccess) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/apps", wrapper.ListCustomerAppData) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/apps", wrapper.UpsertCustomerAppData) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/apps/{appId}", wrapper.DeleteCustomerAppData) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value", wrapper.GetCustomerEntitlementValue) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/stripe", wrapper.GetCustomerStripeAppData) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/stripe", wrapper.UpsertCustomerStripeAppData) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/stripe/portal", wrapper.CreateCustomerStripePortalSession) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/customers/{customerIdOrKey}/subscriptions", wrapper.ListCustomerSubscriptions) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/debug/metrics", wrapper.GetDebugMetrics) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/entitlements", wrapper.ListEntitlements) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/entitlements/{entitlementId}", wrapper.GetEntitlementById) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/events", wrapper.ListEvents) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/events", wrapper.IngestEvents) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/features", wrapper.ListFeatures) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/features", wrapper.CreateFeature) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/features/{featureId}", wrapper.DeleteFeature) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/features/{featureId}", wrapper.GetFeature) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/grants", wrapper.ListGrants) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/grants/{grantId}", wrapper.VoidGrant) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/info/currencies", wrapper.ListCurrencies) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/info/progress/{id}", wrapper.GetProgress) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/marketplace/listings", wrapper.ListMarketplaceListings) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/marketplace/listings/{type}", wrapper.GetMarketplaceListing) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/marketplace/listings/{type}/install", wrapper.MarketplaceAppInstall) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/marketplace/listings/{type}/install/apikey", wrapper.MarketplaceAppAPIKeyInstall) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/marketplace/listings/{type}/install/oauth2", wrapper.MarketplaceOAuth2InstallGetURL) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/marketplace/listings/{type}/install/oauth2/authorize", wrapper.MarketplaceOAuth2InstallAuthorize) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/meters", wrapper.ListMeters) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/meters", wrapper.CreateMeter) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}", wrapper.DeleteMeter) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}", wrapper.GetMeter) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}", wrapper.UpdateMeter) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values", wrapper.ListMeterGroupByValues) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}/query", wrapper.QueryMeter) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}/query", wrapper.QueryMeterPost) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/meters/{meterIdOrSlug}/subjects", wrapper.ListMeterSubjects) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/notification/channels", wrapper.ListNotificationChannels) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/notification/channels", wrapper.CreateNotificationChannel) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/notification/channels/{channelId}", wrapper.DeleteNotificationChannel) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/notification/channels/{channelId}", wrapper.GetNotificationChannel) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/notification/channels/{channelId}", wrapper.UpdateNotificationChannel) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/notification/events", wrapper.ListNotificationEvents) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/notification/events/{eventId}", wrapper.GetNotificationEvent) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/notification/events/{eventId}/resend", wrapper.ResendNotificationEvent) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/notification/rules", wrapper.ListNotificationRules) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/notification/rules", wrapper.CreateNotificationRule) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/notification/rules/{ruleId}", wrapper.DeleteNotificationRule) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/notification/rules/{ruleId}", wrapper.GetNotificationRule) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/notification/rules/{ruleId}", wrapper.UpdateNotificationRule) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/notification/rules/{ruleId}/test", wrapper.TestNotificationRule) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/plans", wrapper.ListPlans) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/plans", wrapper.CreatePlan) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/plans/{planIdOrKey}/next", wrapper.NextPlan) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/plans/{planId}", wrapper.DeletePlan) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/plans/{planId}", wrapper.GetPlan) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/plans/{planId}", wrapper.UpdatePlan) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/plans/{planId}/addons", wrapper.ListPlanAddons) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/plans/{planId}/addons", wrapper.CreatePlanAddon) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/plans/{planId}/addons/{planAddonId}", wrapper.DeletePlanAddon) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/plans/{planId}/addons/{planAddonId}", wrapper.GetPlanAddon) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/plans/{planId}/addons/{planAddonId}", wrapper.UpdatePlanAddon) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/plans/{planId}/archive", wrapper.ArchivePlan) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/plans/{planId}/publish", wrapper.PublishPlan) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/portal/meters/{meterSlug}/query", wrapper.QueryPortalMeter) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/portal/tokens", wrapper.ListPortalTokens) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/portal/tokens", wrapper.CreatePortalToken) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/portal/tokens/invalidate", wrapper.InvalidatePortalTokens) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/stripe/checkout/sessions", wrapper.CreateStripeCheckoutSession) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects", wrapper.ListSubjects) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subjects", wrapper.UpsertSubject) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}", wrapper.DeleteSubject) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}", wrapper.GetSubject) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements", wrapper.ListSubjectEntitlements) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements", wrapper.CreateEntitlement) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants", wrapper.ListEntitlementGrants) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants", wrapper.CreateGrant) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override", wrapper.OverrideEntitlement) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value", wrapper.GetEntitlementValue) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}", wrapper.DeleteEntitlement) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}", wrapper.GetEntitlement) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history", wrapper.GetEntitlementHistory) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset", wrapper.ResetEntitlementUsage) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions", wrapper.CreateSubscription) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}", wrapper.DeleteSubscription) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}", wrapper.GetSubscription) + }) + r.Group(func(r chi.Router) { + r.Patch(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}", wrapper.EditSubscription) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/addons", wrapper.ListSubscriptionAddons) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/addons", wrapper.CreateSubscriptionAddon) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}", wrapper.GetSubscriptionAddon) + }) + r.Group(func(r chi.Router) { + r.Patch(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}", wrapper.UpdateSubscriptionAddon) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/cancel", wrapper.CancelSubscription) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/change", wrapper.ChangeSubscription) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/migrate", wrapper.MigrateSubscription) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/restore", wrapper.RestoreSubscription) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v1/subscriptions/{subscriptionId}/unschedule-cancelation", wrapper.UnscheduleCancelation) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements", wrapper.ListCustomerEntitlementsV2) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements", wrapper.CreateCustomerEntitlementV2) + }) + r.Group(func(r chi.Router) { + r.Delete(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}", wrapper.DeleteCustomerEntitlementV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}", wrapper.GetCustomerEntitlementV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants", wrapper.ListCustomerEntitlementGrantsV2) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants", wrapper.CreateCustomerEntitlementGrantV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history", wrapper.GetCustomerEntitlementHistoryV2) + }) + r.Group(func(r chi.Router) { + r.Put(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override", wrapper.OverrideCustomerEntitlementV2) + }) + r.Group(func(r chi.Router) { + r.Post(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset", wrapper.ResetCustomerEntitlementUsageV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value", wrapper.GetCustomerEntitlementValueV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/entitlements", wrapper.ListEntitlementsV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/entitlements/{entitlementId}", wrapper.GetEntitlementByIdV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/events", wrapper.ListEventsV2) + }) + r.Group(func(r chi.Router) { + r.Get(options.BaseURL+"/api/v2/grants", wrapper.ListGrantsV2) + }) + + return r +} + +// Base64 encoded, gzipped, json marshaled Swagger object +var swaggerSpec = []string{ + + "H4sIAAAAAAAC/+z963IcN7IgAL8KovdsWDrbbFGS7TnWF44TFCmPuaMLD0nZ38y0PxqsArsxqgZqABTJ", + "tkMR+wb7e/fXPsY+z3mBfYUvkAmgUFWo7mpedHNHTIzFriogkUgk8p6/jzK5KKVgwujRs99HJVV0wQxT", + "8NdenkvxRuVMPV/Cf7iYTaT9h32aM50pXhouxejZ6HTOCDwiOVcss79ORuMRuy4LmbPRswtaaDYecfvu", + "PyumlqPxSNAFGz0b4Yjjkc7mbEHt0LQo3lyMnv3999G/KHYxejb6L49qOB/he/rRiVQGwBq9/2U8ytkF", + "rQozejbaO9kfvR+PtFkWdvgLqRb27/7VPF+uWs/5klxwVuQbLef5srGgVcuI4UrB/ZwXBRezIyUveMH2", + "K23kgqk3l0wpnrMvZntusMyPu2+DAF6/0pdcm/bH+sieQz05b7zZXewPvDC4UvcmKfFVu+bUGlsDxkvl", + "hi10d4q3Lw8PyIO3gl8ypWlRLMlbwf9ZMfKSXfNMzhQt5zyDB3bD6XnByGHOhOEXnKmHiHy6KAEDu4//", + "/O03f/vTN9/s/fDz3l9+fPH4yeu/7u7/x3c//Dgaj0pqDFN2zv/f33d3/vTL33d3vtvb+fG//+XV66Od", + "0592/kZ35v94txDljrnc+e2X35988/5fRuORWZZ2aG0sXVj0uh+oUvSW6M/c74f5KtT7twjP+9AeDbRF", + "+SCU/4UtB+H8HVsOPN7xyPEmdBZze+Bfw4wDoLegTTaEHwa/5wUcKb6gavliQXkxaCElfkAYfLHZghqT", + "3fPC9M/czGVljrgQLO/lq29EsSSKmUqJsEZNrvBbUsLHbZarJ+R0zjXhi7LgGTfFkmhmNOEiK6qc7RXF", + "fhjJSGJUxdaxizS0CRSdS1kwKm6HI3ZdUpHgdC/gd2LmjCimSyk0A1QQmufcvkMLkjNDeaH7FuSGTvK+", + "m1+xCNjd8p/EbnUxcogvJUgjHAjpx51MxVQcXlhasNsO54FIS18WofUIumQZv3BsnWotM04Nyx2m28RG", + "rnhRkHPmiJTlrWksdY0JFySjdroLmMyJYO2xxoQWRWMtraF7NjWFqniHg8QHwGxMql+oYPvJC7IrBNf9", + "SmmpjuiMCwqIzuCHNOz4jNALe1dczXk2t4SpDVUGqLGshxl8YcBsG10RHZALvuAmDTE88odlc/Bw5OQJ", + "eLy7Ox4t6DVfVAv/Fxfur3A0uDBsZqkqtQzHrr6UQ7FyQR/3OLRAWwX9SXUeYPzitmbt4j6NbUqAmVrV", + "C2G4KdiCCfPF7NS6NX3cDepCl1rDD4yaSn05t/2q9Xzc/WhCloL9z4p+QaejfzUfdx9iuFJwH4pLyTPQ", + "Urz2qpjVBfasKLVKHef4JXHvE8MXbDIVoK5oftmvb8bjx8uozUhPdp883dl9vLP7+HT38TP432R39/Hf", + "RmOAm9p9yKlhO3bOlIlo8Cqfswup2D0u003w8dbZr1gmLCuHB+uMBH9Mk2IXr332i5/n1JCSKqO9bF9w", + "bYisTFmBsowfWm3ZPuBipu/YjOFgHW6vSC3OMJGz/MRQU2mmh5wP/41VuvCjvmW1xk4u8A52yFkMDljB", + "DMv77So5vuAXogcy4tbwm9nJEtBqXW3AdPH1wcwoHv2jsSIEYjjHvdEaPza/LZni0hK3Mms3E9/1VoqB", + "y+xM8Cksdf2m3natH3tf9QBWaLm9J158v29heiXzG8DdkXtuwBi/GEF71Xo+rqjdhCwF+0u+4ObNxYVm", + "ps80+LpanDNlZQcgBysxoGkcbO4HzqjONXm8u3sftsKNjYXxmiT8Z9Ci9Dtetpc0eEFunuSK4gXsDlnA", + "K6reMVMWNGN7Jf8LWx4KbWhRHLN/VkybCY6QIiv7xEt5tCztsjh+G859Sc28hhuGGo8U+2fFlZVJ0Fkx", + "MHKnLE/t9++bMH9e0L7Zq8z8iYPZ/lsq/hv7pIFn5guyhPev5uPyzhiuXrj/w84xofklFRnL4ac/K1mV", + "z5d4B8PlmUlhmAAmRMuy4Bm4VR79Q9sV/R7jNziUj5QsmTKcrb19cZ6TIDcE6aIz1XgE9ki7Ew5eAqGO", + "ZGYhRnwizO8tlbUiAkrn6aarv51MxV9lRTIqSKUZMXMOvBWfkgupyCUtKhZU0WiU525De0WUVWhubkhW", + "cCZMKmxpH56Qw4OpeKvZRVWgt5hm70ip5EwxDaBRAnMP9sz5+WLiWtDrl0zMzHz07Om3cAX4Px8PkPei", + "1SDy9tcGY3ExszuxqArDyyJyrsOt9oNUxMmnz8i/t8f83r+883ha7e4++bb/hSc929MBc5gavaDXh/gQ", + "bv51wmMHL44QECmlYhk1NXNtoumE29XHxOjJFyMYLH4yQxbUZPNenLn5/n7JRC7VL9/LkgnKY6T5NxYy", + "Z8Uv389Ks/P1jqnUubRj/uf//j//7//+T3J2dhCgPTt7Rt5qRn5dQeG/wu3CaL4S+x4Z4wFcpc+gIc//", + "wTIT4z5nrHwTfo13QMlFlxpBOyJBuyFckOMf9snTp0+/I8ieMFoj6FoJVCu5+P7J7pNvvA61+1+f7rn/", + "m+zu7v6tDwsWoA+kkUV4mMU02LDoXBAhjQ9uYTmhRHMxKxihs5liM2q6oSxAmIxmc6IrQDqB8COLySsu", + "cnk1mYpf3aNfrZBKiWKaqUuW1+wYuGwCsQ7S7933SLb+RyDYHszOEpR1c9tYhDsHyVCm5l5P8TT3yK/N", + "c7L2z338ywNy5ys0MhFUJvLbnRAj3fl4ssn5MPIjnA6k2hP+G1t/QMb1Cak0na09J1aGYMJwxczSyxT1", + "aXMmnuSBAoJOILaG9vuDvb8OFACiJQ6VL3+uPxmCvlO+YH+TokcZgeNueYFdv4XJ4wLI6zcpGKGa5OyC", + "C7Arw7PDvdd7xI5L7MDkgBp6TjUjD+bGlM8ePbq6uppwKuhEqtkjO9COHUg/nECkXWvb7IBvT/dhQpjP", + "b1elXXReCs1+Vd+/Pd3fCNUBHUmNe4TDrSXS19JAzKHF5P6cCsGKL0avGrq2j6tl9UO5bk0vLr+kUJZh", + "K/t09iqGcd16jqsvKJp10MI+nX2KQEytBo1f3uqFp1DmDEI0XigllXe/2n8npBj7M8lkbiWUY2fYQlUK", + "LmZ47IPmhy4X5xq62LUrQLPZLZd+1lj3733GkXm1oGJHMZpDBIFh14aUSl7y3IqxUb4AFyhVcSnGU2Gv", + "SGIkoVpzjdHBaFEgObtkhVXa7J1diZwpbaiA0WoEmzk1RGZZpRTLN8JyY1kbxRVvhr1K8RVYqxQnHIMt", + "loCnNh6v2DkprTBoKWsqIuQRei4rU+NiTDwuEe0sQuZU1Nhs52+sGHIjfNqF3hkeT6osYzqk8AAEbSQ2", + "voST6GPNayICSayghln5K5tTMWMgElNBKMxAjHzHRPIIa4Rh40MM0N4TJrShJoGKADxH0XcKPk02HZGQ", + "1U2uqCal1ZaF8VKwQxJtIFI58/9UWLaNZiGUsRXLGLeq9oWSi2iAZ1bExaCiMVFU5HJRLMmMCaaosQKy", + "LCk8s7qHkGJnVjGtgbwRJ3iMuSYaaPVqzgT6puFICADQnpGsASEMd0kLnmO2jP2qVNJiyzOJTbcO0bvR", + "3kX5BfacdvfmyJ5eLnJ23XEaDgULBk57DDd1ELbATWumduOdG5KIlrfQshD75S08oGHie3KCHhVUfFn1", + "C1av6OOKXG3Y+uD/ojbjE92HFVtQRJmPe2V5QA11d0raz+sCaUIwak4NtWsAf++yHMxSnet3Q1dvF34Y", + "1i/gz6m4hm6wZ52S2Qr4vOMgTw/W8CjPxmpecm0+4RDWu1jdpuGftf/u9gGg4UC7z9cHhHbhf7eiJkGd", + "Pnu+JO/YcjIV+1SzHS40E5obfslgAzktnH9t4JrebVquoAu3WFWOoAE41CO4K8jFxoUKuqCXBRV/GYp2", + "SNssqLD4d+eEK6Irfe4/HCycuGlvC/2QMgqNJTTqKNzZTpQ3rrDQXdMad1VzOc6FYYzi5xWI7e7zO1ta", + "ymk1bFXgYbgRX8ICWR+BKb33H9fVuRIacZ7vWC2+KOSVdjkAVhXSUZ6kc/dbPk8NtzqYpXjdMQtY1S2j", + "CkNSyob3nAohDegQeriQtRd9hGJWw2/OIPv6HVvuoK5ZUq40WVBBZyz3J1wvtWGLCdkHCMg5IwuZo7sL", + "KI6pCUSZ0fyNKJah+oAP/YkhGIfMp1RGOF8wbeiitDCBXumUSVmpjIEm7b5uZsc82X3y9SaexD5I9+3g", + "9sic9ngcwd4lsuVw9O+7L/YtzTbF3LcnB6NxOosfPkHTig/3AxKbRBFVfuQRBE4Bpd8QpyVTC2rBLpb+", + "wN0PfuFArsLvMJNn9LNHj1/PhLxy+vPj3Sdfk2xOFc0864iio+zTGK7YJNmBil1cWIXokv2QjD2xe2ZX", + "H8VMeDTjrpFzlskF0yQMNCE/21cS/kz3BYRY5IpemM5OPL2LnXjhIXG5CDnaX/qXfipvsnCuiZCkkGLG", + "1GarDy+DCeeCC25YsbxvZDAXIpFCBU9cU3ukwpw+HhL3QohAIMl7T+TrWxfkMXbXIbShImOnTv0ceI3Y", + "m+8w/rR7mZxC5kf9SpN3abg/7OUxHWG4xXREpCLTkQ+0mY5i/tacbDxKqgJ7RLMF3xm2C9H5//brdnRk", + "jHu689vuzne//LcH//7sLPzx8F//JYIORdVuZCEz1GrswxH7yn/RxedeLRX4cZPrElVR0HMLVnP/w9CJ", + "OLu0gvJj0wkCUR2dGclzZq4YE+QxHPwn33zbz2effNMNQ/VMl+uyoKgApVBpBaF9KwilGY99TEBQ6l6R", + "g9TrYzc+KNYOpuMw6CilbUO20WZHxqcoJQ8LjtiCfyr25aKsrNR7TjXLiUSWylos2+Le8yv9bCp28L4g", + "31uW27iy7DOKn37ffEKm1e7u08x+cuX+TSKWDx+qbA7Oh/jbUxl/uYIF1RlaVZnfQuwrqDbEDXE/sslL", + "O8NbmKFXPHFODy4F+BsTlPkSbEQXpH4TPXp6MFn+1JwDzmrrfPct4af2pAkivmRKB+mqdmY0V/ETvtQi", + "THIoMgW1RbzXp3llR9sT+w16oXWQdD0L7+OMlb/bi3fsLRu18hBT1NiZbC7DkI1LLpLbwymO+UtiY39J", + "sEw4z6AiJD2BjloRQmL1NtwKiHDtKnOfrirxKYrgW6FlK7RshZaNhZYWJ3VQI7PsZ5H1InrZ4GHrPG5y", + "piZTcYLh1v4df9ggh+sc/sSImtiAhhU8pX39as6L+iOwoIVgfciRbIyzkApicgR8DNKDsHfT392Jtpvv", + "vo4WXO9pw8naZYneySidmQ/CXBzziOaCW6x9Tbnr7IxG95n9oxcMF0bA8mMXYZGMe8BXQhRG5+7pqVgD", + "2wbBBj5OBWjCYNzBUBJFG2nCW5UO0zjFwo8+VCOW7ZJBB7eMnmiMv5tMjTbS0GJfVqKnZiU8b8/QGPib", + "1MCtsxjNMvaBJlGABqK69/wdM0gkRnl1hTSCNLVeGtne+nd5628v1D/Whdq6SgfcnyfBljDMKhDyaJxH", + "pqnFgykg0s3rsx3fQGAeGI1HaAqw/3Cqfd91o5jWSWcXPOgoNNwkrsd9bsBq23WlWNanNlF/8INI+2nM", + "g09R0eGC/P3w5A15+vjbb3ce/wLJRdpnF2kJyUVcyx147gDZsV/qydwsioeEFuWc7jzxiXEYxyPY45QL", + "VmlD7MNowyx+kou27z1JZK+yTIp88CjlXAqG1UQS17996G6n9NdSw82TCu09gmcYXZ9OZkpeN5aamWWQ", + "EAHthKzWx6lk372Cz8SC+Yt2dSZ1eJlkUlzwWeVuNJC3MAhBqobE2L3mzjnySP2q0gYGHDLzz3Nm5kxB", + "zfbnbgQnV9iT51mIJotKG0LtsJOpqOFdMCowTe5I8Yx9pYkr/71Pc2bl2fo7WM25NHOS+/XZKajI5pYB", + "80WM2uC0TuK25SxOZ2S/v0+HcJCHfod6d0rQ4jAHH8h3j79+kmU7dPfxtzt/+u5buvNvjx8/3XlMv/v6", + "yQXL8iff5snk8L2yTPCjspxMxRs4Os8gsBmYcM7tSwsrCmMayYKWpaVEsL1oIxdnWKUKflsVgXXoX7PT", + "j0eaivxcXvcGNeJj9y5C0/cqPLVvvg+Eunwdhe+9H4+kYEMiKaOR1rxZg7fu1cTq3/+S3pXnNKWJ7J1r", + "YwUCsGOj5An07WrWsJzQssSs6mPmQ+SpgFDH+h0jgeSkmlHhYuUhRp5r8JIKQjNTQT4FXsJjVAi50URe", + "iRazsIcpUwxMLrRIxFh8ztEJ2yiAe1VGvhD/r4tW3UA3qQtXvXTfphWqRf2ij4nFDBMoydM49fboeu9W", + "N3Zoq0LdpQq1sd+yLHu9lidN3aQsLX8VdbpAZx8/f7ffDbxR/ogF3Pdcm/u0pOe8SCpOexa34TlckuF1", + "zjRaQ9k115BVhrcc0XBXLkkuxVfGBSICVoNBKNh/IuGsvcVWliAlXVrhVZNMFgXL7G1amZAJqtglE5Vr", + "SuW+8GGoX+nQ9sgNYk/dXMIOgkPEyUVnbugz91odwLmPD8iRA6LeFfdJePB+I0sW+MQCUuMrJKnuJL03", + "6ES5E7dMe740L2kB7RvY9ZSH2eCU1+S3wkoWzYzpJx1DJho90LTtDkY8zFraT/sQmvRfp744Y4ZipVTm", + "rUbDKf4FBQIsrWS0yKqCGnZKr8E8AyVJ45ZZbTJKWkDK8nMwt6P6sDW234+xvSyP7c2h0O//RuFV8UZh", + "bPkbrJfzRSqlQ9Z9Z3rrsMk+hmp7zC6YYiLrYVHKP8YLWvjyQ4RqQomeS2Xqd6DggtNvUYK6qIoC/sY5", + "MWDWEMFYjhJPi5Pk6VNyeBCJZB+8c0RXQurF5UqvlcVn4xXyylWHu59z0wRng0PU+XDoiYo/u8Oz0xx2", + "6CnZ7Lt16Os7P32ejr2GkacuFF9f8DS3EkUlfJmEPkeFy13tHoxmteSG498zZL/l4y4ZpeZ6TnNXpflI", + "yfOCLWK5YJjc9Vaw65JlBprLNoboiRFl6pIpkqGlVSosrWH/7WouOK0JSzPkFTAZLa3EHVd4KJlyRSSM", + "hNAIX4QC67k8YJPZZEwWtLDaEwgzOKBeCkOvx4QLiJELvy+YhkSzC0UXXMzGFrKcZayEMFP/lpKVVYQe", + "TlKa83NaUJGxH7k2Ui2xNl2avZ3jm2SOr/qalF3zPr63Z6AcaHosVrdIC+NSrL2CcbW+GSXU8euKMLV2", + "KavzIqla4kJRZoFjDkOtzSPHt6zOrHuFNxSHMMfPAXqBPca8EHlncLe4uluEh27cRnbq+Hs3BwrbXIqW", + "wydeXf+7IUlE11aC0mXYgcsMpU49l1WRW9p2wj1UHTRyKqjwDSkaPCDyFI3GI3SxOB7jLa4BGPTOOCW1", + "yxYc7KG7dk+Pa/9C6DxMFkzNWO7bAoOWD5Zt33OYaxKUmbj+S7vnMfHtottNi3kkfmjiLFBOPXfTVRoN", + "dLlkKH3M6aUdcEnecZFbMgs2GSyWPY6aKdfAYZHtRNZiWW5gfGo2xt0rS/1G1SJYmkVGZcc1Cl/gpuK6", + "jQ1YsOutrZmBpH0yszgUKJDx0Dsc2erVXBYsls+kIv+oXL2sw4MItUnjl64sZOil3Wz5VJllz2rBlgh+", + "DCkMtTJjVEjK2xj9zEk0EOW9LToF9ZVU7y4K5MUbQf2z/zANuIfCj19vAUJdk30XqhYzCoiNoB0jpa3g", + "Qwdcg7P/VWRbTjKh+nwiwQOApZJ5lRmSUUMLOSO5Gy3lRJJKsQJ2JFkQvn5sicjvmR+w5gJch9piBRfv", + "6ikJzZTUmuT8AgjQhL5d5IGvKW/vYY/ySjNoS/7Q9yx38sMlz33qXRB8CBMz7oup0srIHV9Rikjhc/dY", + "zn2RKN/rx7Li8VSUBQNvH31nqVCBOPKOsRLJ0tJu1ly+75Tu1kbAQUgSq5gKzUxV6ubrdIEYWfDZHDzR", + "XMAEmfkYetA60juyYpgwyft9D4U0eFoTw5a4tsTlAncatDOMM0f0lmbKEcm1cOUcUKn+6bu1iBRP0JUY", + "/aMBTPmYUd1nslfwrEvLaywDDvozbaXFPgw153d+4xP4AiP5Mqrysxj3Q8Y5dh9G6IlGcwL+JgOhpfu2", + "NoMVi12n/69d380GcOsaQCBvdQ/XRG1oyzC3DLPFMP9ZUavsbxBj+rpaMMWzHl7px/NIahGe3cxXVjk4", + "Z6SUWGEnjhJ3pN7ikgHIAUcgZUarcX9ee8maB+AmF0e/3LL2HqlPYmzLuNG0NXfoztg+9qvEr8OmB/CF", + "6757wAzlhe7VA1Z/hkU6stpGIC+8vgBWN6pYYBiRKz4oY1bHI7kbC+PikGs4lsO0V7hR1XMGnjclE1BI", + "qdZS4kFi88C4BgSKbRjFM1Msiae/8EFoNms0Ky4SOjxGI6cafx6zWVVQZSnekPAejHw1Z2CXqtXT2kaD", + "5XAvIk/H0OQiCD5vNnHquj9TjpK3vaFauBUP+AWhl5RDCNDDfgPZmviAPeFSwWjho8Pq4mh9Uw2L9OnJ", + "30yHDbxkM1q4xhyqVvlpHDDXCKpMxhTQa7wzNzdfnNpPGfK29AnGh19pUgCohwcYvQ9nBraGXpOyUqXU", + "TE/I6ZwtyYIuwTw1FRJCstFYqcfkvDLkin2lGNqmuDBMMW185xGpGebkdwcOXGqvrpm2SVI2HrW37RG6", + "S36Fkik4Ad2Lrhkdyx03c7Gu/vy2Lw/SmKB1kXTWsOJCQftSIpbBEmdtHSLU8nUrektFzivNBdPabduW", + "SWyZxB+JSbxfc5ruOiPzsztNWzr/Q9B5vJJu2U73hGgjlfOheOE0CJ1GhtYbVmN1X7RBsaDSWsR1WXop", + "7T7fXL8Iiwh9oNJZha/tMSr4bxZqeo07oufySviiTFLxGYduHn7lucyqBVunkPS6CJvPm3dxy42z9bTV", + "PqvPO23HlfHpnCbnmI1cth6//z5Kla7dJgBtE4DWJwBtU2vuLrXm03fwfyGl9z6DoIQhmUErAhfqi+CX", + "tXJDHJes1wkRjZdjiQK3Ojx5wPMxWJAfejuEhStc8+vljygEd4MslHUyR+0KsdJBLQ/brYlw2BEJfFLR", + "XcLi85k2g8TQ6zuFwoqim0DQToaIkmIwS82jahDhDaG3DpklBcf7oqhPgJA+Kv18mmTTVzmz7802CXFR", + "VgbgBuaKXRtbBPSVJo6XrqCjG1PGh3RfjkfXOzO50w0CqYnxhuT1KazCUfQNaPTjQ3/HxyJWuqHHx/JG", + "uvva8ItVAkSXX6QBbB/JSjjdK+b8VnJNzTIVWKmnbSnoomUYp7g5l7hzw4kDuNdmssZWctdGgE9Red4q", + "nX8wpfPWCtvKQzVcbZv0Fe2LVDF/+DaKJvdsyPlq37hMjBVZHyFZoy9V4rwx8mFPsmcb77DaMDbXhGot", + "M47NebmZ+ygztijNMsVH7DeFlO9YTqqS5EtBFzyjRbvdygeJ2fq8u0PhRvdtXMja4fn6TfvwqP/iSrX0", + "GWGifdr8fPcJJ0d0WUiat0UPwa6IVIgYF6IJRVvsvztZXB+aI3TjTj1n6KSRaZLNpWbgvQnO2k8pw6Jn", + "u170tHdNvxelGnr/dCh2FJDrW7/GyYRO6wyBO7/0Zwn2ALpZgfFmn1YHRETXNSivnUHS/Yle8yxkKja6", + "VPqf98PB2XwdP3Mz742r7CZAhgvck2vqWqSaPb/hQai57lFNyq3j4PN/oYWZvCDQTRLOSNZanA/ERPJg", + "12XBM26IyzmwQkhdy6V96SPFTsjhhU/Kngq4ksdYnB5iQxMrJWnh/2PczZ66N46O66st5JHUZFjnrJBW", + "lDNyEk8bS1g30dQ6ktoaoNriWkeMcsm7+BiibKN02Ebvps7evY/PYAgF2GhV7WzjRMAhwtc+FEDyDRoN", + "pzE6hO3LNHkIN78+I/bwGRRXGs7qtiWY7qsEU3oPvJY4QO3a6K6pw/lvrriGIU6cUtrHaerUga76GjTR", + "9+ObuEFaMIW6LWtAqi3hAyFyJZk38G0NKPT0cd03LdS5GnFrEOdN76vR5t76cEj7AA6nFrpO6fUaVBl6", + "vQZNhl5/OBTd3i2GZdV4syJbtNXruVqflpJ6KwRUXlkp0l/qPvHIKydt3WS9IN+rgCRfa2lK0v5qz2as", + "pDjYdKyi9KjktQUOrHProf3shIethPCBJIRGIL4V0X6OLNGrKLtZeq7Xr1SbctqStUvbQ48PHEhftuvc", + "x/3nJOeKZaZYjsGSgsUAszkVM9BMc6YhRhoMR1PhT3dU26i2cLbr3m4dSFsH0taBdIcRfzd0Ha1gUVYy", + "wtpzr5L9d7Dgn38HUoPs4cL2NpOpODT29mdqwQXTZC6vGhnF2JWF+AIBui5D4NtecKOjvajrn2lSaawW", + "aFePc+24L87MnAlXF5E9q4fxtchKxS65rKLthEpxYA+BsC8rVnGlTWTnUmxBubAv+xJ8PECbT4gvtxCz", + "LLuEhdSGZHKxcBpThKYYYCmK5TNMfdkIWo+4HHvuIOwT8lpGiGy8lkLlpCnttBGIsaEeylWCTjpHpUsy", + "qdcwNV3cJnulwWyePunwmh6o1162/oX2Bds4hbRzSrea+g019U9J/f24euUK55GfJA5Y6i9LH9VzXpas", + "pQkZV3W2fokLjRUaQdYLvzc1tDOIHrf/ABh/WX/CBlXVBHE0FNIEz5H7DLh9spAmF1im2tfMtGLtAXJh", + "3W7KOyZXc57NQ4szasgVAy5ppG+Fjk5QX2KCXTK1RFeLmbOpoM0mv44dQylWTR5gWQxC80u8JSyAD4lU", + "hIk8eqwUo0q7x+vKQoVKn5syiYDnPT/CuFlF9MYDnsSj3LbI08bT3Xa4gI5VZZyGfL/uzljxbesUbkjz", + "U9Em+s51o1hWKXsUj0I132F87Lj54U9PethXmMCfAS9dhLVM4i4fCf7nOE/0fsRi4vK2qwNaXRPT1npv", + "trUNSrvB9sbf3/sW3xC1DRYwDL0bITNcex3QgiwVyycBSaAeSP+sj9uDuBWQ0g2Nje+WWwpZ9T2FJyAY", + "LDzGWlzw7q8yFNEMU5e0aBhNRkenj38cdafkmswUzXxZbd9Y3pd1ypnVs01TQgwFxLslqt3e5ISLqaiJ", + "qVVi7qIqxtDUiWqgutDbvqmyzekliH8Fn80hZzeUn2vqNk1L3Ojo8UEceXV48ubfvt19vFGsTStEs7/Y", + "hZMA1ha72MryW1n+rmX5LvLX3T+dL7pGYJRh1+iqXSZaGbmHImyD66xqNmwZV2XkghqMxSVc64o1wKAX", + "hrlilYpeGLyoyZxqUlKt0UicMu/C7Kf0eh+axg3fxfqT7qY5BcEZGuKWq3YhZVksfVJpo8qdwzShtYXi", + "wa/YnWNi//qVPCK/Gjtvzg7zXx8SKQiNsr3yzrQQV1V3dEbTFxVESFJIMWMKul/kOcutGoGW9/xZpwBM", + "a2QwqUwF8H0utGE0n5AXPpDT0GtoH+5DgRZ0SbThRWHnUmwhL1k+Bkh+PWeWbUv1q7OB6am4qOz26qos", + "pQLTvt2kekNb99Tuwain/mIsM3oSwWYf71gJgWkwqu8vb19dUFHRgih2ydnVDe+J8Siv2J4lxRakT1eD", + "itSL6mOjBqEmeWW1zp+5mUMnk5ojyaLCu4+br1wLRJdZel6weEURk697D0ZrQ9iGLC4qferYxdojfILe", + "mlTpV0t7RSGvUq7mtDcmvvNfiPxISTxXr25S96bL6VaN3pDSIBT5DHstn4VmIO1SusIoWaDoGQO+42Qh", + "6IfFhFXXmLrkQa5Cw6qdAej/fe3LCCJum/eONrkB1uAw3QSgdhDESggTsLORPBPrAoAke6BrFCXwNsC6", + "85ILZsWoohqkOjVfbysBc5ZulKLsF5e+LBSLlAC/npwuR6GBTdQZ5dCwBX5e9Tns1sge61bUer99FSeF", + "lAFXcc0YXgFf2CCWtf1l83hkc6pm7KxxZ49WiVfIl9ocu4f628sdQP2xkLUO2dG7bUR3JLEBSGbC8uN8", + "LaN8Ae/Vcg5eti6G1tIxpprQa3sphAsS8yixp9dU/CAVcYx93GhHG04/juJgGvvh4s41nPqPTul1Wmpi", + "4kKqrLWmC1roxKLgzZus5ecGoHWh39DyC+6O2LRaF/y2S5eVaU87mQoHENAPj6uUl0xBrMIY9jUg0aEC", + "jdVguNAhVHhqFWrsDwQzFTKLVgdWWxTnSsrzjl+sjdYUpcf0lqLy/TnL3snKnNibVQqM8jxl1wZEkJPq", + "fMHNEVU0FdfjVtYaYuJavxl2bbqiez1qX4gpsR+i7btmrTn64FkeSen+EIOg6l3j55UxiJ3mxK7Bmutj", + "EDxvT6JAmlWaup5zMHj76o03hB0C8Tn4DXE8X28ykrDuHvZboTuA/KFRbpha6DcXJyjZ7GUZKw1NNg4d", + "tBAuCLbS9yX5vUJip7E/ehGKzhTD020HvONlvV9/BN8epuWontNW8TMrNUVCBlucM6uQjcajudSmp8/j", + "PvQrxI6SyvSH/fknUbc07HRoGdqDmqme0+wdEzkUO8LOf1Bdfa8y8yck7XKuVJG2D789fpkcxreuRLoD", + "FXGmqDBh/NW2YjtfylS8nxBi2pJ4842ERBgE6kTfvAf1lXypnU71MA5sSAs7mok8BDqk++ih1JOSF/el", + "uCh49uE6a/omlRms34Xp2XGh9KFvpUmBd1jA4sQZDAe1mnQ4n8aixDTCxxIbB1VM05Ecfz88eUOePv72", + "253HvzyYG1PqZ48eXV1dTbiWE6lmj7iWO/DcFUMFm4OezM2ieEhoUc7pzhNfKBWIbTIVntVcyZ2CGUv3", + "8Quod9FCy0gkQdO6uGSCM9EuX/j2pBWG1ggMedJMNtvb+dsvvz9JJ5Oh7bjFHCCYZb9hDG7RNco9jrVk", + "7mui8XMQHqBybv/d1JBNE8JoZwiSV+CV85NNSOwMBxEwLTLWJ3mwijEAJ8d+1JQNzv51jn0ywYhI/XJ4", + "VH935XoEu2SqG/jmsZbkRptAfesdDeuI1W5+cRbodzQewSLSlwjMhpO1IHYqkROYVhHhCfDSZcDyfgAa", + "WWnscfOC83/+j/9Vx5w5Garhn62MHEU43xD4fcvnhFl5dJxVlsVNDS2IAfwTj3NJZhTpJ4N2vhmOjjdq", + "I/W41WgGpS28co5Zpdmel002PQTDVnm0YsLU+QihkyAbQo8eKcAwe8k1P+dF1N2npacrO3okazmTydtD", + "r7dpZrzR3utQsOm5P11XziBcaZa7xk3umznPcybGQ6YFmRGbQRVXdKntgPh5BJGzWy4kGEvvCfX1+F1M", + "H1400YHsQyc8pSEHNdAYJo7g2GDJXSwq4WsHTjDCvkOygJEQGhtOppFeoLaqMuam2B8l2MONjGeaisZU", + "tfi4YCqbW6EtZ96nK0X3cFtVuGAT8gas0r5Egp3t7UkYA9uNNDWF+9mf0+Ycq/bIM50xdgtuqfxwLQBf", + "ttdJW/mAB+fympyzC6kYOWfA4NzKS7rEHVOMLFxrLOpqz3eGskK0y6Bfykr5K+GA6vm5pKouJD6ZCi8e", + "5f7hJDiNFo/8e4/K6rzgWY8Sc0dsZtMLbfX5TvBUx6XWZRvd0XqO/HT3ibSjaE0bIc8ziYiH1KzRYypx", + "rSKHvPWletTgqbeFvObQCYiFFOzW8J52+MxtYW4f2hhyAPkWIozvpNTTQSU4lyDv0ckwUpCQ5+1jc1yi", + "lbOstq+K3k4rd8OGG4t47py9g2T1Woqkl+6qbMmLRNory/PliZcip+JUemnAi56UXFRW2mgOMIbWk+7H", + "M/fjWaQtNQN9vS5Q5zR9YvjBfi4NpNifepfhjZif2FKCbTVOmWouy7+Cm+13OfUh7rF/MnyTN2X36dVv", + "zGL84XVtkXx4RIoj3kSpO2aYb/lG7KNh5ya3jnKDEOCJfpgGiHD6RmOriAb+d2OQwSx1Ayjhu4a55vdG", + "zR40W2VLMOMc+FzrZ6O9/VcvxuRQZPbbVCs8XQFJ/IUttV3tYrlTt7sY/WJJx6V9RyXLEnr0KEJNB5as", + "w/4DXw4UgODCX+AmyDKm9dvjl6NnIysQPnv0yK3cioEj17CpqRMH8w/6I2sbR9OG8P79+0SR2FTZqZVl", + "1CJXmu8eDFm/y49dvWlQleH9up7YuiSB/ai82NB3ewt8HiEuCa3Zw+EBkQpahxkJDC6uo1fb9AO/nApU", + "I9vjuOZC7eSU8N2oScu3viTcYX5T9mnK7omL2LOAOZoBh2ooJAjaZuvE45WGs66oPOn5RY3KSaf4X4xC", + "WIx2iGl/LBUEwelWJ1r/PIrIS0y7vmBj3ffSb8Ivm11LLXxvykPdrFNxwhgJOqbMdKxe0pI/8l8+cl/q", + "R4i3vgKOSaviramr12TZpbM7s1k2rMWWFWMxMyoyVgAr/j1pZxjXMzqLDHQ0o9k7547FQM1gc/DGMrx5", + "8WRAtNzb45fYQYwtSc4ycPRKgvPX5W6E1axNpcDaA9aEK3auuWETF2lfUkWh96plzCG0Avmz81DaJ941", + "mewHiH7FkDB4eLCiPxR+hdaWkD2YUk8w+dnpMg0OOLZ/UmXgn1IRzRe8oGocQlyjxATFMikyXwJRByuZ", + "mSM2IAlC0MLljOv0+lJG5bu3VCWo9R5s1e9jmWN4/UL8oqc94OlcMeb9aocnb4ifAZxrkMNhiUplVMc1", + "/07Z9Sb28OEBLwndw1s/64IXYEG2+ARCqE8cVgDI6tCERpXCSCy7W8Upvft3o+m/t0JWyRXTez25sS9K", + "mc0xG5ULou2pyTWhJopLTtuacVwsyeAPq1hi+1Ugvae7ZMFFZa9SI8mTr8lcVkq7aKDOmJmrLT0hz5f+", + "Ch0jw4OYcsuLwhhI2v6LOI6ZC/Pt16NUCR+0TsfJVunKKoFOjhKpcX0t+kYnzBB5YeWzHQS3pFy5fOCl", + "rABD1BhqUQoJWa4YqmPGNfO6qAqgTW2kcreOp9tYOabnEOo291VVXbNQo6rMVK6x/YLa8Q9Fzi95XtHC", + "QldPJTQzlnBKqUNdZijsifBjrsJiMhV7xcZfeoQmQwAaPrLTZZnq37VHCq5NCCywL9k/mqZjTR6wyWwy", + "tndC/hBppUtXFvEQidQoW9VtyNKqTKV69OY7EIgTA6c4a+OOxloccJLc5fysvpqbEglo4pOpeMmoEmQh", + "FYuoJWjy3s5g0eoH8tekPf+Rh6El/blN0LUIiCxyx6mjOyWdsX93b+1U/Hs//I6lScStFUySslIUSxRA", + "bbBplJjsOn1U4RKCjKw2nkEwivKykJkzrgLNOI9Vk4RAwIOeq1aa6BGOQtxAWjJyshYCu4NVb9uEShXz", + "Ya0eEF1bYxP1iWrFfgWGkEU7Ud6JsZo1pUirRAUUKCuIVqCK+zCfm4qDoEEtZfWf/+N/5aTg75jXSxtV", + "j7wH0S3IMrfOCZXO22XJZkwUozl8MqugZrS3kPHfLKuBF91g8MGzW9Jpb5frm8t8ayJ6Vtz26yNvoEsB", + "3yzzJR2smI4Ie3sYSi7ZPQgiecxgMEJxc4PpMdPJ8mxNjbRDHr50YSJntl/l2kcO8Pb45SC9Jb8LvaV5", + "lX9kxQUWeMIyxXrkPhcSquEVv98dA0tHPMHm5YIbDnWV3K5N/qEjgRpG3oEIZG6ZzML3mZ/cuN9JQx7t", + "GC1WNT55uknjjYTJ8NNQmJjCDgW9NZ6/sqyZ8iJ4yoJhKxjUJjfp2NK1cDk71ge23a7SYoZSSaS13C2V", + "3J/+gCqDN/6kLKAJHrzY6HpI8uqeK8L+bBUC8LT+CrLEr3DwhbyarJHsjtEa1ceS3YJ6Owe1dzNpTbXD", + "mKo8FIYJM3goJxPBR73jQspwT71CTCfu46Hp4dYZre3AgyzIq6XFEycr9aE9GdDvg/l9oPyAJfXYsaER", + "S2ex8W63t6zZORpIea0F3PeBkMrQwlHwmgyogNMSPgqh8CAGJ6viRxn9fft1eAAlcuIGR+1CAFZCDnnP", + "DgvjqcCxzsGTbTS5qESGTISbJQgJF4xavV7XnotQSmXcEBSCb8K7IRoguJIDa0z7DjdniJu2hf+/4H/c", + "0zP3dKcxzyhOfWj93ibB2jCTwOiL0x9IQcWsojNGDJ35U4YfdbYRsvvq/CHE1nlBxTsrdmEoZsfAX4Jg", + "p1h+hqNq++65kle6EdjoHZgeh8/uAYkOF1HLr/BDG22O1a5JyAlKdKPdSVN9hmzGkPYxFag3uxNh9dvM", + "R57e27pxMWeWG9VrPw4rHJR9tg9VRV9Lw964qp6YAMuO7eU39Dp03/yZCaZ4duCqgdohEorbihmDu7uj", + "ONQ1R32Jijk1VkGA0ezZBlLz7XO6vAjqoCQF5kP7ZM/YCa0GqeumTsAR3GJAXsZBbicIdfrUtWkUC6Jv", + "jPzX+FkX4Q9OmOK0eEheh0rrjRb+eaN8a7erQ7q8mStt1shB75Swtdty5reukeI16Ep9ycU7L8S50lAx", + "qAG9leLrEZuuV9ebKxfpMG3lwekeeQjQorVC0kjRDnpA6mrcyBqxTj9iNQSgH0F9id6q4o33IfQtLSGd", + "V4KblDiAT4Lw5oZq7gkX5umTpFNBLxfnslgDFr40QGjCpFBfYhuHjoBftbk9pZFjbfPvhydvvn7y+E/9", + "qXX26Y4Hu5Fb19BSo6S6ePzGOzfJqztolVxuJNY9TSTWPe1JrAPgDlsNepIJyIeNljqxmQMLqxqmLqir", + "LUCoWEaFymRtWkZLTF3Ezo7l9G9NQFcykiyo4CXUW2hWJfdmyjGZyyt2yXwxDMNmKDNNBSQOKFYsiRTk", + "tawrXWuyd3QIHmAGFweW1kNrv79dsMBTSqT9jBvN5tDW5qawl0wtqGVLhWV9MNL9rAO676xex6fYaQI9", + "FQeKXpiTpch+lPJdb7YoVNSa6KXIyFzKd75HoIXR/u29CXXxkSjx2oe4+DpRtZ1DsGufXNxIse4rTWIH", + "t8IPF7O1EHN87yPDzFfZnOvg0mRTjvu1vfUR8+FBUntDTXeDpiRUvWMGCju8dN+mxYBF/SIpfJ25OXQq", + "hV4J2tCiYLmPLY3l5Y7kt+2dcne9U4IlbHBrshP8JBGT17CcwRUshagT14dK8PjxVxrLFHNNWiJAt0fw", + "WV3b9Jc/QidwKK7vtrSvBZk/ymGPx161SF0IfWw3LaW2JbJGq6kV9XNdVsTa+rnbi/SPepFuWfudsfYP", + "w13THaXuh9N418BeWR44GlmjB4YQy72yJAcuhq2TB7NpA/CGMtpXAtsLNC4CtdnuFYQeoMe4OXjiiuR5", + "7xYmMx8g5x0OY6XRTjgr5DkwS3QghC4MFopl+SH6rjt63QOQ770Xnn/kagWD+u8iajtb4bCmJmvPS7BG", + "rTwa0UpP8QTcsHlCi87CCZorKfhvLO9NqjuM4rWMJBdcYGRHqKod2q2ib6u3ecQNqsW3gLbwuiihvoJV", + "9qG/unVYnosuSbsFmnP84NaXh19uhJmaIjbCjjdt35lF3NewqC/Wr7TvQ+pvWFfkoo6lxrwpJsypDAzS", + "9OWttMaG1IIoMReCLvonusM4i00215VeuNHWeqvewI1l1xiP1ZMa2cWgH99/SA4PVmPwFni4BW0zL80F", + "Up80aNgLd5DaBH0Nm22uWkRY9wx8cPj6px1wuvLrh/fBRvqP+M24yg3aTgykyyHw1EbmG3C7l1ywA66h", + "4t2LQKiv6lZgrZsQH5BzJ25CzezcfY/m6ohq9WaHwS4tpnkI3u/esGhM/0qTw4OHk7TFqV5T3zwNwD9G", + "xFrr2m7BPI4R9cuwbbzh9n1Ku7Zytz6NTbrB5rgzfar4bMZUqgs7HmCDL2CHepZVhmEvD89785T3uaRg", + "uXFM4OyC8oLFP1TCR4ufFyz6XV4ylVf2F4zeiIsyXEreU5umVxxbd3/UzKl7hew3g4e1kSoiKdQsDw+0", + "z4vw94dUSL93cOPWZHrTO3f86clvRZK164EoaTLImD2smDY4ODsh63F8Sxgs8ARorcuhHTO2vIwIPWRk", + "bXCdrr7VEslcRYN/boSjzxA1A1AyQHRotEdKGk3qY1U3H+oPD+k0bfaxBFjQMO7P7Koxg/u9VMwM0sdr", + "ZdqPPSzgYgCHRyu178cBtvFewdoZ5YPUhh4OX5omwQ+7cQGRjuA+f4C1MDARqmEW4toVHLTDJaRpU99K", + "N5JcW5dbT6+y+mY7Z/5yy1sMvVtS18PWvwNHBRWHoqxakncCArYoAYUXUhG54NhTq0bF5C7aOra7NzYM", + "x6EvYzPk1xvPoKW8XZirJrFPc5asjH8ahe76yhMZvox5wWua1h+wi9AaX14YJqJkwLrFkPvQdX0ieQQu", + "Zg2/QDlMPyPT0dHjV9MRebCQwsyL5cOx/ekp/PTPiirDlP/x8V/tj1SIihbF8mG7m9arhqLfjRR+3lzu", + "veXj+IY1GHG0InAri1LhcAOjEBUPyScbxbF1jNyZY6ScU816sj8sYRB4AULCFPJmBflIRSGvNEZguaYw", + "BRVfaaIsq8qoyjWREPHFF4xQTdqtwL1rTE+mYs9Noq+4yeZEZlmlfAc4lFyYyMFY1ep+OiZMaMwjdZHG", + "9uy3mqk23XJCGsJFVlQ5xI+pGXM1F6LWOQCMXS5y10HCiuXnR/ZDoE8uDvGjaCeOAjaj3jdBjiuVPIZy", + "UJs2bjxqfdhqv9uqiYYJVCNscsbOcJHdnC3f8bFUckfRRL7Hen4dMZSjnlFcVpPBPMobNb07aX7eatuF", + "8c1mzsRZ3f4skeUUBmmkCLtr59DUxafrDhueEFHcDTZA3YyARAjqEjfrrrgdkoD5WT2MTzovFbvkstKt", + "84CRqVBPIScXXGlvv0TOsqBcgBGFFthxP0Cbx3Pbg/cMj99GE9d2ULt0B8aEvJYRThqvpbAyqbslx6k+", + "dsSFhIYei4Xr7httWUxtJ81HfV7ZcN92BJfAFLvSW7ecXQEG9LJyXatRiG+wH1/MhTzwbbzeMcx8umRK", + "cykeptuJwFBxd8N9CHdN6Czwe0jL7nTmShctg57xab4fyoLBO8F6HA9L4H7wibigF3gNUlg5CK0+NMuk", + "yl2OeXxqvNgXwiKoYhAI7HaF+ZLjrusOX7AJSVZjDATZwHlrBY3q/HedRu2l+U0VkVoD6MsVgN2ESzgW", + "sDAPOHfCMNQyaGw4NF5bbORliAc4xW8TMMGDHiUAQ7HHddQY/uBVXkPfMcIuLrAu0A++OS9KDvHO4aZi", + "VRuW+567WJw/lBdpnK5GDmBXEcPVNPbpl2Gnraf/+b6vLflHPG0N1Ndv/+EO2LraApguGycmToivfMo4", + "tq+YM7gIJCQ/kx8pZGtqhlslL+tXPmI92b+wZXqBAPlGK1yvsXRitu6Ki3l5kC8WLOdYyfO+eFts5LBi", + "jJ9y0pNIHjhSnB/ikdovF6S8MXvtUrjtctF1VsyqaF2er6OyqLR0qCxdRxWvGntQAeoz98vZO7bECtQt", + "+5YQEquubBKrHX2UiNZO16hYUEFntYnWJUORfYDA8ruFzDEx6XxpeZ+arAhsbkAwbhWP3WAh7oM0T+t0", + "FWid0al461PADL0GKZTHwY5tg1WYbfxZJ1XdebGbkF+6AsFuL8arMR1b21zvwZiRrb9hThq2jiY4ZE41", + "keIjptbsu3aKDSjTkY/bzLf7tJl+KVlZ71IiyZ4v700Lv6SUhDIVL1A0cWJJ+zqaRHdR6GnlJWA82hdV", + "0XV+huPGRdsRqtttzKGQWE4NPaeaDROMHD6sMLY1ht+rMVzxBVXLnoJkqITBG62KZG06a9g+8QMcM53A", + "X5sEe6owNayGXaKGrnShge2vjdd/Jey6tDiTQUMdZM+O+TXWZEkf0pMG+F279uefbpaWWjdRRJl62x4h", + "EarvItyMJNS9yAiULQWfJhQJko2dvx03i2gUoCMN8DbOsftlhaqyB4W6+iv84fOoVAfWBnd1oboCDcX3", + "MUuk3QEYFgVlB1bVrFu1aS/qMX6yykDXPfKKAs3Gk62CErVCu0vOqu2WZn9Cu0qoA47OrjCse/DfOr/j", + "vdFTTCXq797s8xvhZuV+rU4pCi9MxYmRfodoWfrCXRlp3BsNTsWIvHhGsLLSmGgq8nN5PSadDJLxKOd2", + "6gUX1KDpbFEHh3ZeHxby0V7geOQA6OWC+DjxHSxgTeHB1le1Irt8jRo07MD78UgKNrycYWfUNV+llzCs", + "kU8v5t4PoB80ZbxxvQAODVtsKepOKSqB4HuhseQ8nyrVHdGZ3WCWH7vqyqmwZfdKqMDcTdXwMlIim9E+", + "8g2ZncYOBbs3DGxsMIZOOACd9URQ2SeEi5xdNwSix6kaTvbdE/5bz0gLp2SKUHEMl1YyFdZTj7+7m5rB", + "SEOLfVmJnlrM8Lw9Q2Pgb1IDt7049SwONdHaPNJX0UafMyck47uOYWuT8T8/q93nYfn6NG0mW1vD1tbw", + "Jdkatoos7Maqm+IFWEv6BVV8HkoUa5fIqExnZzAbqkT2h5V9ofFPZcrKxIlQTQtQf/ZS2t28pushmIVa", + "ZbZbok5i0LcvDw/Ig7eCXzKlaVEsyVvkdC/ZNc/kTNFyjpVLyIlUBk7TYbAhP/zY6W48X7nHSa/2Rnh0", + "XvkmIt1tsRo08GmugO2Nypl6noAPHpDzpe9jGcWbOb7k6SltrFlFV5+RzLwVlu9dWL7rAlZbmXkrM29l", + "5q3MvJWZv1CZOfYB3kx+abo4Y2EGO//+oCAYDv84lSuFmbeJDbsttp2hOYub1EJvid+Ykhb90IvSoVyP", + "p+K8MkSK8BN8ABkVWOLMji9FkyKbl2YjKq7HKfwP1wiBGkz88GvJE+C71FzsZgrOViHrMeBzrWXGQcQL", + "vuQYvh7x7iQASrgmFPv4W5CiLhEuvGSJwd4+NHFt+GfwMAdMJJK9Y0qNkZYiWJ9Zf8RUxoRJio31s1BE", + "oLs7ZWOAgYla9TdpiaYe1DOsGAAngDrhcsEF/rUbsbJoghZiInhX4eWYUS2FEwpOSiZ6gs8UvBeugVBs", + "AQjAS8rafp9I23aV5fwBd6+fwevrayr2VolrruGYGpZRla/a6bUrUW6QaGdSRQCUYkVv86T9+jE5POhM", + "VFdXiI5LwcW7uDZRpqTWUYJiSKd64NMo+WUtEFeakYxq9tBXueqG8UdVQ8SMCxe/Tysjd3x2FkQNkp8t", + "o2BW5MBmyD6VsuCCjaeiLJgVkhb0neVHCtjmO8ZKjJa1kkLWXH6Lrgl0IiCJVUwF9M7SzdfpAjGy4LO5", + "wToKMEEr1PnDxMh/8jxg3DlrnqDPkvxgdQ+WjViIP35wF9/m5MFtvD1020PnDt0/KyoMNxuo5q+rBVM8", + "6zlvfjyPJJT+GoTyygvPUnMrfnaE55UnDQYcfMjC8tYfsdPeCq0m6voUdhGPWyxZNy/ecZI5jNcvpIar", + "57C/7aK0+RNZMCq0b4DAMHGZvHYGNiuaXijGJsQqAXHesS4Z6ANTASnU0ShULN1OQhmyEETi466gSbjQ", + "PAeJf5dUwvDC1SF2QE0F14Rdz2mlXexhkwN9moTYoqpB5JSQ6f0jSHwBarJohGIBdyIKJ+TwtddhfQ96", + "pXzz+RyWklO1EJ4uJHWwFHTBsyPARBdt+BQRFco/VSJnqlhaogUd8ytdh/tFVAgJm6HwRCialdVdkEMH", + "Lz8yXBlNT9SCqndVWacPIiidTVtUheFlwTcpn9SkX59T9zhZUaEeH5TssiyWISm1XqPr7gR8qoO6UKZn", + "KnbI7mT3Wb0eizmreOOTb1pPvtn9r/4Q1XPZVx93Bgk3JtXJ99tDP06OHdfnuvXaVxffjll72FrP0N04", + "t9GhIvL+mZv5vlwsuAnBtCuoHU0GcJVAiQb3VYLy8NbZW3g3yF0wz9q+q0nBF9yZQBAcarByBIQULrwo", + "HQyiTlvFJ654y/1CiPhpw2ilul4gEaQYyO0B3h7g7gF+kXPzpky1NakWUacpFuk1tfvOjta0veb5mRXC", + "INJ8IS+Z/6sSlqbyqmBnVk8ZjeFVqJpSv+v/1EYxk83d3ykB0kId25D38jwdLbyX574Ut2EL2B2sqNTl", + "M7KMxfGwkl/6SmD9Jem8R/l3n6p8nX/62L/X3itZjqIpogH79q+FCSwqtQIVHs/r1t+P/9JPMTQhCGBy", + "MZX96x20wmMglvR24zNQge12QxGi3g23r/RtYhMZMS1vSA9r9tbDMHzhPbvrVz5ocxvnbWMC13N+YdZS", + "dw3siX1/CDJw4CGoOEEO0YML97QXGezaMJGjyylZg3E1NaxnTzenhwDaECy8DUzVPkno0eG5BgW3VZkr", + "RNUM4YdtBr72xpFleg11ShECXCqWUVPXm2tfQ3UGk69rihq+t8Jh1ZV2uhN2qvBF0n7wiWH2Q+lEqYAH", + "lphj7OSDJXyCc4SovFCxcLImRcR35lqfNvbcvQnOfwYoXPvNK/cmtqjj2YBPTvDF2+Z8JIBYl6eRAmLw", + "Fx4779dQ1HOq2anbwQRbmFMFVe5YkQcPf2rzUxVya6dyur+1K5iEFY7aUTN3W98o+LRXQuIKYN4nHHdf", + "VQXaRdVvJDapVaGmUfQK6tDo6vzs8ZOn3QzkL6IgCRqkjqCE4kZOJPv+qg7zxpmzsDrj5EuqruFsuH11", + "UbyJ19QhElbxczQHd0ylO0Ut9o7/9vT1wYu/nJ789PXx8Q8//Me33/35mx/2frpDz4UDrLei1k0Ad//a", + "cd/uvAOpI4q1+vbrdphFvBy689vuzne//LcH//7sLPzx8F//ZWj5kGNGcwhqcSF9EDVelxK5fyT35D9/", + "hNg7twMTV9HBRaH0BEPXxVbesYA8Z2Hw8TFT8frN6Ytn5CQO0cF6+LWUNSbOGej7G1p9MJia9o4Om9HD", + "oazbzuP7IhNv+RiG7OiyB3dWTw3+yGbSujuC2cYJPF9MtYlN74RjqOXIxWzl5eAl3/hySGC2W6qup61y", + "IzgP0g6cHzM6Ag3OF7PvddKfl7Zvpla4cuE4SJtsttLgVhrcSoNbaXArDW6lwa00eP/SoDc7egtaysq6", + "Fd3uRXRzAtlwCe7uRDd0EEEFbj1EjHMZuNBNAdNDEuJbR3q7mxsgpNPUKyYy/HWY2288Wj/f6+Lmq/yA", + "d8tH4dIbcao7OOXR2VgZj+bbqyRycxqC8/AIgc4x/elJKl5gq1FtNaqtRrWBRrWuJUQk5zVlPP/hh79V", + "1nZ5WCmbJuFuyJRfbIXvrda51To/ba1zq3l9fppXj7LVuFrWiHRdlWu1gtVUrO40+KUByg0CYVrfbxgU", + "0/j67gNkWsNvGCxz069TmH0/iCIwWOYHiJVZF0rToovQv3CreW8173u4qT5VbXrloXIMue9A+ec9R0p3", + "85m3ysMa5SHZPG3IlfhnRYcFp1qYZ/blhD1j0V+0DZ9BOgh8TE6wLdw5hG+7VE1X1K1bJK4WhGR1XrBR", + "K6sf14Uf35MRAfATmxGaJgOudcX2LgxTx0wz44wDn7l14EvRQ7HrIL9kqZW88A+xYajlQUCh2JnadRu1", + "vyrPTN3z0MjR9V8N3T0zxt2VBtKc/eKKi1xenfDfGHmw4KIy7OEd280ivtnHHR1riYUWUANDRjmsCypL", + "NDn/BvLEWjWPXZfc5RwMj38K36zUQBD8egJUSbhvzQMPmN7rqyrJFyzCgnv7dru0FhufqapOr49lUchL", + "pvYilu9SJXeTrBN9sUoW9mhA3jU1ll8wMybU8k3XTxbSD0LdMBpl4Pl27JZAQBA3EjvgwCdzmvv2vI4T", + "MTOZiufuI5wiPIH8UlpkVYGN2PUz4t48AyZ+BlycfE9eHb5+8Kq93DF5tff/feA/eA6z4hdj8oqL5ssP", + "Hw64zTo32J3KmPXh8MO2Dd5QzfeILj37GJX87Os3au/d/OXlks+5/K785vH8O85/EM9ByFi0l7klgbsm", + "AcGuzXHoPZ1mWvadNueCawgvqzu+Y0rFpXLFPJI1JeGpN/o4Oc9tPWgQcz6zyl14E+rplWXBQa1W2m7X", + "kX8IFY6CZJizjC9C2V89IT/bAQt5xZT/jXCR84xC8q6biS9KqYzdo3b9UtqA97GdDYoTVmoG3rw5Fa13", + "nkym4mcn6Vi4FSOaXTJFiyAwXFIO5USDBgdJ107fHUfNcYlmhatKWG+bU7EAdG3C3JOpOBRQNUlbSUsx", + "P52eU69R22kCrAW7ZMU4GjorpLYjGkm40fENGTckDztw6OpPU43xxFfSzwgHEq+ijBZ+Rs5QVopvXmqY", + "biwYZvIRNwgWyB2RlOsAaFWgDqRZcWH+La7u9eSbbyI9IFmsWjXOz12aO6Ou8E1bp9ONvhCD8aW0Au5A", + "mcmCjR/cKeMZGmW9cMW8Y3G/IXA6A3JTVB6iF8eGk01U5GAURGPyJ6wx/yFUpI+memwF5q3AvBWY75sE", + "tuLpVjz9w4mn63063t3Wkk9bUtV66WlDQSkVL/kZCkYfwZUgsPPGWWjO4Yim9eP7rdh2j2LbhEB14vgh", + "161SxY6UsWUABqpAFyUYgxXLyQrZ79O47ImL3LFSiNtr9s+KFtqtzdXY24qFW7FwKxZuxcKtWLgVC/fM", + "IElwpfi3lfduKO9to0m20STbaJIvRjfYhqTcc0jKVsvaallbLWsbrbLV+7Z63zZaZRut8slHq2weoOJr", + "UQ+IS3GvNkuGu7LiF1UBfGBBxTK6w3zDPj3G0uGaGeBYVelyhc6pPYw0y5jWcGQtFu3I9i1LrwW7tkcm", + "5yZqJb6H73NNcgvTAjJHcSgpQrIYzlBpaPBXX6fuGrQn94HdzikmRxFaFPLKvjIdBWEcWnPNGYH8jNxz", + "Bq7JdHReKWFILq/EdORfg4Eebit1bCt1/MErdSSwt61Ksa1K8YerSsH1ibwwL/mCN3XGC1rozv16eEG0", + "f/t7O2BjL6yO6EVKv1fskgnCu00Z4qaaYzKn2l2Y2Au3uKJLbQVhO0dc39nCip3d6h3wFQlgMW+F6/uW", + "Xsxq8eEgKqHIZ0Kq+no9p9k7JvIJOapLK0aoI1xow2j+/8HmoZDuG6R57MsT+oxcVJjznF5AK8uyTVB/", + "lRXgGSU8JxZURi4o6ADFktBCipnmead5Csr/jtyIzpigikty5V0NGLECkgjc8vafTiSZQCtjq4ItfG9m", + "324yJ1YHsgpcpO760azg1AdOrWHVQwU70anVRaIBUdMxX2mwV4Cxwglq0Dvzgs8qhRim5IouXfdXsDAw", + "ms2diSG0OBu7PUV5y2noplK4QVLxGRe08KttLnUyFa+oqADXAWW6gsZEDmLA6IKhycR3Wps6iXg6GpNp", + "12Bjf7Za27Rr6ZuOfP44Rdx6HXMyWuv9cefmUHDDvWZMgmjeMXK06O+oYWFwh+lx99hccMFi5TnovqHj", + "trMNBufYJmqkX4OFza8AthZ3NZhBUhqnVdt6jlJDYwL1Dseb07Jk4rZK04ByQFRXioG80y93A4CgmKAx", + "Dk88djm2n+fOVB9TqRQh+mzsMQ+qS6qaB8xw70v9CPUkSrub6pK9uWSKztheTAZr7jhYBrIC/Bi9Hzhe", + "HsykgHocI2rVDAU8LB0ZSXbju+vIDRAG9eMkb4JtueC6aJWvGbQtWrWZXexHtq5YVUIP+hB1g2O+nNT8", + "EuyxiaZhNqP94FDordBSuxyiGi2LhB1pkijW8rE11u3t9gncbp/y6f1Ax+zmBb5V74Hblhn70suMbU0P", + "W9PD1vSwNT18oaaHlAg0VPttfdmVDuKFfygpaqvJ30iT30ib/VxaStxETExFzG899luP/dZjv/XY38z+", + "sS2Xu+21sY1q2EY1fOmmBV1tEDB72FLkuzwW1ZlIkRm1VZ34WZ9tYLVBY2st2FoLPgVrwTqz2zZ0Yevc", + "2YYufDyDx9Z9/2m57+/NY79J+6pgMNq0j9XWj/gH9COiBa0vH9oStmELeD6wv1ai0tv7miWEYR0gVCm6", + "3CodW6Vjq3RslY7PXenYOi23MvzWaWnHeKNypp4nxCd4QM6XRJboEmp39QNByOEtLXinsBhNfUQthzUs", + "P2a6lEInqk2EV+we4jttOTdIPQkfg33kg4K8t6WkM+CZm0pLNbnUopAdq6csBRCpyNl1u7JAlxnZd0/4", + "bz0jOQ7oyk1Y7QiXVTIV1tKs8tGdwUhDi/3+ymzwvD1DY+BvUgO3ia+exaEmWptH+BpyPHF9b9cLQXsE", + "e+S2FcWt+/gLdB+DdJfG238/efOalFRpKIGCb6bmJ6dzrl3VJm6lKC2dvGe565wJks1Z9s5KavE96+Ir", + "rFTGQeaNIja80Gm/sVf+zkxRiKdwHwXp1Lk13cU5rkM1UFxdykoReSVcmMaE/Ejhm3OLVILnpEkDv5Mp", + "HkMUZfV09Iz8fTqacTOvzqejX8j7mBr+oaFpStdJu/XKD/XKbz3MWw/zH9HD/FGUim1SYK2RoJCzdSps", + "XisLanSyfJ1zoU+HcjLHXecEDpJ/b5Fp5DwEXdm4m9e3FaruQ6ja+l2+ML/LR7kCN7kGPh+7lGM5g3hg", + "Kox+q/Nvdf7t9bTV+T+Yzr+NvN9G3m/tIlu7yOcnFG5tA5+WbaA34HB4uOCp2/61bcuXJeuTxlp+7nFw", + "ho97qWk8ut6ZyZ1VntyUrB49JoYtyoIaFnJegevgJrTBBEGSkrKgYjIVPyCm8EO54AZKGCm56EQS+TnG", + "hGrszGA/8RvtnMDK0ltGFVB1zi28Cy6okcouYEHL0i7u2e8BLev9ws/xzZ+eQGyoq+G99qs6Vzggfv1H", + "QTF6H1Se5Wu6sNsCu/N+PJKCDWmdkwLk/XjwRxEgg7+p8fR+DZ1vHg/bNHPd6b42QLnRDrdG2HC3G1/f", + "x763JtiQBm76dQq76+ni84oYcfG025iRe44Z+cnq9ysvILw+YE+lgrvxTckEHAGvty+ooLNgNWBLfzvV", + "9RUu/FUE9nXnVZqQxjSuT5jjEmPi2M2YBJN811zlIlATEVhWAm52d0lW7CO91SXOK14YQpWsRN5TxwF7", + "uzTrPkBxiLzKGndto47DxHctIopByJ5wXWUUW1AuoqjhhCAyxiBeNMsIdskUMZUSmgg2o1ZuGtL8sUdC", + "r6NY++xHCax2jYoae30NtTO17DTv2PIZmY5ggdMR2GXWKhQhoL0L8c9zBkbyWIGbUx2RZqwokJM5NKmi", + "WaakxnDhhpy0LFu95xCiHgijYEkXUXkLQnVRom2iQarzjXnEV4Zkdi6sIYIENyZsMpv4vIAaC5askRM1", + "SVhekMe7u56TOwH/vHI9u64szYOCCaOznPzb7th1WAqh8E92fQxpA1s3o0aAcc+jCHIr+vrbDcYmdn9d", + "LELMPEjORQjwxmaF1JB/VkwtMRT56OXbE4fzxmea27PKhfvInfK7OIewH7dY5TFD5mDCndNiVq3LOpTR", + "iO6hGwDeuqfq4znkMlqjD7l3nClap2zPliUxsEAjm4yqtgZrnM5kyXLy05MQqLC9WLYXSzJtzCEVfT/B", + "2nTUTBhc3xzwFowqK6Ru7R4k5cQMp8mrIAOIgY2ax1kkhwdwLuwPwbOTpJBJP3rqo7u9d7f37vbe/Vzv", + "XaWkenFtmNC+dXSauXV415+ZYIpnpDkCodpyZdiZH09Pj46UPC/YYhJe0JO/nxhqKr0vc/ZLIqQq79XI", + "s7lVJ+3qAfHRK4HxW1iaLJ+LS1rw/Myh/gz9MGt5PkgLfUYGMw+sy77WnJDmuRT6UankI0UNy6jK9SMj", + "3zHxqGHBHuAg0brX0jGvFlRsigshDbkAgcMT4vmSDEJIi6YQO2PcrRrSJIFdshSr2C9klcMzTU4wby9D", + "qQcu9hOwBU3FVLwpnV+nphOQn0RV4PmjWSZVDumhuCfx0Doe+tlUvDk6PXzzeu8l5At6Yzg1RvHzyjBN", + "Xu39FashOy4PDYYJhdkQMrgwW2EZEInxTfZ494LmbOdx9h3b+Tr/Ntv5tyd/+mYn++ZJ9vTbPz19nD/N", + "RuMR+ogsapm65BnbERR8NxbSS6bwFI4eT3braMjYfwyeEPAMrQxpcdtQKrkoTWT0dKcs+N0GnnVLcewS", + "LXnLQtJ8Um/M2F5tDl2EG7KotIEYDMRXHYfhd6xXkLBQZVIYJowJjpoG0eBDEAQ8mce7DW4/3CACXLqW", + "cKYj6FeMhPDoH1qK6QgDWgp55dtaW4YV+3jan1gCjw56+2nvEiNPPzUU7Zzd1R167yzeGPgayhawMJrb", + "W95KTc08X8VHbU/yWjhSLuPW/LDfTf4xkMSbsHTm9idgzfxACdfG3pKY+EuFo8F08aLWeYrxs6MYlITN", + "2ADo4nMY5eC6I9k9F+7lFD02uE/dJN0to9ItadZNsQ5AzxR+7yRN27/OPfk4QdPfBjCllzgcahvPSiXz", + "KmOKPAhhAiDF4nY97IniB360BmJkV8Oc6DIL7ZnDNpNXlqUg+Vsmf/zDPnn69Ol3twvwW3tG+nkQ5cJe", + "CshZ8PG5r0/geRMiVTFsGeOuJlcSAWod1CttoVYuJu6viZYLBgOtQ3LrfsZYejxnTZIeewe8J6POnd10", + "ViMXeOFgCE92sEG7RY8Vh0bPXBDdJJOLR5k9AvChfqTzdzsz+ejyySNcx3svEhywgl8ytdwzhi1K0++O", + "wqbd+LRJsbkbwl7gdoyE/UbmPSE99kkUMAqjT1ZEW3j4yHM7ZIqzVxhU+KrHL+aftye1Z3LBi4JrlkmR", + "60FAHLjBkpUZdBCvu5Cg6E2s3NYF5KLWalZB4cbYR9mvO3+liu7Eb49fOntWvX9XVBPt2JJvWi+kqTlm", + "NqdCsAIjpK/Y+VzKd3DAVoH39vjl2lbk57iJ0Z4lRdfQFz/gO7m1cf98v8sgQtSSxI9v3h6PxqODvb+O", + "xqOfX7z4y2g8evXm9emPo/Hory/2jtOJ/mHcOoSnOzuqzDEM7IIL7sijrV31OiNrNyRo25XgJrhxo8ET", + "SurjJ62qI0+fxGVHHu9a9Xt1u/88wu+wIKXE3vRE3Qtuwqp8SFhiQW0SyesjhlhLUYiLrUmF3wUzEY3C", + "B6nx/k0m7DHLiVQk5xr/baELYTtvtb1+pZnDz3g5268NLeQMzHere47R/JKKjOVggP6zklX5fPkDLwxT", + "K02Yq3COn59EYasNs4hX1PzMaBUhMzu3FSQucPbJVPjqS5gyyNE3DE9hsXCvhmj4aJTnS2fFb+lfC5kz", + "4Dn/woXdu1lpdr4ejfG/cvRLdJn/C/snkB6kaUS1uvZWAz1KbD5V2Zxf3jhC0H9+x3Up/XpgdFr0R4J/", + "xlHsX0q89OcZuPsuFSa9570M1AOOHyDTwwQQEIPdUpaENhJ17iQw2uHdsX0LhAXK8RHHhe8hPy3iRIAb", + "9C7FlQADbwwzvXeBcMM5c+IUrA5ijSdN8+G3mJTDY0YLLlG7YedK0hx8N9TqrtTU95ii2Tv7/YveInjU", + "jQavQjG8oiBgBAWmDwJdk6WHuxmY+XgqjD+8ftoMBo/uCXjze2Dyk6mYiv/83//n//3f/0nOzuoeaWdn", + "z8hbzciK29C3RUteKeEqCTILXBz1zr4afF0AQk6Kanb3h6dmCIBifQbehjs+VbhSbReQOEJgdbFUGp1B", + "sFHvBBu1fWXAYbQC277UZvhhdFLYW/9hVxCsjchM7YBEmEltQiYa3DZ4HqBwoKhoMR05eeyCX7O8+SEE", + "o01HRbGYjuy2FFYvqUp4NhXBLf/y5Sucx574c6vghC5B0ZHcOV9Gtu24ENtbP9+XkY7QErD7Av/RH+Gs", + "eDxfJXevDnLeyuBfvgy+lUW2sshWFtnKIltZ5MPJIq17PLqvV1zVL1++ehshs4mSAJwFHmBv4uIVLXUb", + "zJwvXECJXXV3efUl1byTwz3VNYzzDI8xOTxwvp0HbDKbjMkUjx6WnM4KWuVs5+nONztaCsHMdPTQ7Rfc", + "o1dtXoEsilCiuZgVjqnYVVUGy1+z66yoNL90vOhXeMEx3OWv8S68AuBTt0b8SU/zzM4Wu/rec2lZXmB3", + "5PAguRzEP0TvJXahZoJrV9ZdUQAotbRS8cylnm10BCOKO3JDdA/jMdOyuHRnCu8ENx/pPzqTqYDoglKW", + "Fbr3uAhulC4BfNWhXceZpwIdxBZPNDO+76cCyRL3AsWwNT4htwK/SKB4GKiXzO2SwmwtUpclE5QjrVNh", + "5kqWPNuUxv3gq4jBv5Ok9CO/hCRFND+8Mb3HaLgpzW+y0uQKVxI/kORp0hHtthKJFrzOGPmyyTZFH7v9", + "B9MjSBb4UD8E2apkEHGO5PgMXxgTWRn4b0azOTuzFDomilEtBRcz//OV4oaNoQgVs9dV8LZOxa/ux19B", + "3hCEFpyi8PUrzPDrmPzqX0+8g9P/ugrzAX9JIjsNy1+J+1vTWY3mm1JZY4T1q+1Z5WpSa5VGKIpFwiuZ", + "yuYfdu0f1Xz8Lnhw17dpqe2Y0fyIKVjy8BvjdbVgimeJ+8ECDjmfMDrEW7q94IK8PTmI8bxfv2K/gNfA", + "02J//9megnuEDE7ZGtDwnQZscMzuBayIhyQAAptNExQ8zfcCCw7dC8wbfNyAJrCxewEojN4L03F4IwKr", + "HeXT2LwOBlccS+y80i+Q76U0Dd9WpmvmCukAt0XQD72zBhSlWk7AagYyq7EHdxV6mEnEZ0IHJsiKd3bF", + "EM9TmxdroysE+3GRFVXOtLtWjfY6de3Q0+QBz8dW6U60bk85CN+2R2hA8AGqJzkKdbgiDp4QvZkU2d71", + "lVbyxgZB+GJRGVDOq9QKYzEGTRBzJavZXGJmDNk7OhxPBZSycJYguF+5MEzRDCLu4JKkPjLyK93txREQ", + "NyvN12coACWWjAH8A0Lw7LJX0NlmnUN89nwcoRxmCRbz4X1EHBCfQUUIH2azrQVxX7Ug2marLgn0G6u8", + "bcoxoFCR1purkD2HjC37IF8KunB6aGT4WVdSyIqkg5V+MDnCxbD6k9ZdeNsCMX2jbmqzSNdyae1TWjM8", + "jcKQw57FXMPicdx/bY5HaI5+7iv9pMSDYPmmvkRHnQzVZA3g7kmW1bPvh3wR9k9LJS5Q2mnMeZ1u0xOu", + "XRffut6R9n5elCbqcNpFIAD+QyGpWbuuC/tW76qoSFzOTqknlBRcQ9yhs/W4wqSZXJxDNS13FxVyxjNa", + "kL3XB8O5YbSE972IQQ6ZQsv4jnakm5jYA4pLTOyBZWaGwDKDa815gO4ZHrYxQFbq+CDIKgYhq4Dk6nvH", + "VDEMUzU0HwxNYj1gQn5AGpfq7ljFm+MPxin6GejhwYtrmq1noYcH5MHbl4cHDx3qId0Osl+sQgTI5wYq", + "1oOqpLkUCVbLxRA64y1y92itbeg9QiqEWD54K/glUxoMa06necmueSZnipZz1xX2RCrUUWp152Fb5frz", + "t9/87U/ffLP3w897f/nxxeMnr/+6u/8f3/3w4x0WrL3LnXSi5JqdRE1qZv/8NO/Dw1rW/mg3Ys/EXlq/", + "7wvwptPfx313M1ju5nq76dx3fpvdDJA7u7xuNv1Hvatuc4r7eZwLl1t3WblAl0+UwZ3cnPvfM3+Lqhx/", + "BPa2bvYPyN1Wg8IL/m49MAtqXJZ4c9ox4TMhgUAz5/+6GRR3LUvdXjixzPc2qLkxLu71ulk39Ye6bVbD", + "cd+XzZrZh50JC8F9nwsx4GA4THzowyFujaQbY+WjCgMn96HvnCaLUbQkAUwW/jTlAFjADSnpHmxtgytq", + "fCRz223hu2uL2+3huUej222B+6js4sYHI8ksCgoRSwlk20cQocTuMxQCesOFIofg/Y7m7S1PE/t+cLcd", + "nN73Y0e5k1AJj6CfuZkf0SW0V2FqsQpfuMUlvkwMU4uPisGyCfXALmj283i9OLGvEsXFmcvvSBaLitee", + "gGoqDnAkOBxc+FyRT2LDpTrnec6EK+kYhwsMQ91bwVwgaXuI9OZppi6hLVzOlDZS5i6vEWJGoSSqYheV", + "hpJohFZmLhX/jREOvs4O/H+mhl3RpeUSsjIfeBFjcjXnUKwQIlEw1BMBIhhEfL0ck5znIMYpljEogAqC", + "SLGsa/RAQCQVpCq1UYwuPI64IYKxHDNzXHVdbnk/ZE1Jy2TLghkWYzCNJah1XClxIK/Ej1wbqZYnbLZI", + "FnHcIxofeeLDWjTnlRIkl1eCzHEAyIjaIzN+yUT4JFlJF0KZ3CjMXDHmar5pl7g5p2LGcsJ4KCvcnrJU", + "XCr0Kdi1u0QuO3pUuyZZ5XvPvBA9NXbiKsS+/DI1rtZ0aHuVqo1zw9KzAaQTQ1UC8ysAavRkvUOQGlWw", + "A67urBQ2FOVyKzlXjL6D3eyrcZ3E/DMC1Ht48MyXQG/m0a1wzVisvB9Q67qFhLA7HxENif3+UIiANqLJ", + "st88m7tKzFixmmYuZN0eVIMntVnhmgqoNgjJnXWg6SDx788BlmOWSZWP+hcQ4sb6K4JfMoU50Stqet/J", + "gSrvsv9qswGf47GTFVWs66CzwHlrdtrYmjtYbEvYcCv3sNW70WF8PSdu3OTZSebUpNFf+u66zWIwo+2P", + "IzCHB13CnJ9XEy4AeRt7eW+xlx321Q1QgBPqnrbJAEiyv7ty42B/+EiFFdynUQQ/sIR1nGY1Z/HI8BP3", + "4vtz64TngN4ew3s7hocHx6y3NHV4hpURIM3D2zOoIIcHw3I39hK5Db7WRLqIwn0c0r5U4sODIVkNSdyJ", + "GdMGq14/dzV3qVgOqeOJVYHHvw88Ee711iFIikRxiV+nRHrNN4pRd5mwWJEWw5nBieJLOOtJvUCW93Qz", + "2LPSLL7ha9taypC+1AO0oHCFYTttGX7HIsufSSMBv849s/pDq/j3vvUE3+r0JYg6OSdZhH9ODg98pRhX", + "2FwTqrXMOHBrZ0n2b3+EAL2wowOr2SJZJ8nY1QwvQgl3xP+kvRnJotO+BRo4tJqVl+uBblN/tFuePuz7", + "pgDhl3cMTn3yoE9NGqr28WzS1gXlBbpL3EuTtWzS12yP9ifCTD8HdQxmv1JaqgECyl5kGYS+dvY7eyFD", + "kflULO1QeSWuiT6IMzc55Huo93OIH8byQJBaBLt26+w76rAWx7+hfp2Fw8NX8IYBs++66r/thTa0KF4x", + "M08V1naPyQKeeyiijh+xCmjZzZmklZk/GY3xL1py12lIyLNMMbjuaaHPAnQp5fBQWOZDixMw6gLBfmhj", + "OxNQ7RrMHVSQKoxCMinQxoWmkVIBkbOccINm6YuquOBF4RshrLIyH4pLmfStuQexcRhCj/FXt/d6qQ1L", + "uI4yWRQssyP1sR/gOqHugh/2ihcFOWeP5lSTc8YEcQPdeW3mL6kGs2tesRxOkfvuC2gckEiOd48xBKMo", + "wvYUXDjmBH6EV1VhOPHT+7dcUyhpiK7KUipLmEuGFjAvBwwH9TnSsaPGffc99DDLWX7ADOWFTqzhJZtR", + "17Nw6bw4/jjMpMw1NLFGcQ3lyi+lknUD9N/7Kp4lupQFrYe8cirm490nX5NsThXNoDRgs3ScfRrDVc+T", + "gkrRC/NWGF6sYAeVfd7gBxxuQfiYYDMNILw3/jf/XubPCAcB1LdujTuzXkn17qKQV0QzY7iY4UiHFyEp", + "tiyVvKSF/d5fDdDOkdSwI5hc2zHuWDrKK5YivYPK4cZ7qJGzx54+j4MHcdeQh/fML9k13o+HuR5+lt0h", + "3ivLF9Hn3bPrn5LDA91eJRdEor5YlproKpsTqsmJUTzVi6Snsvvnp/yPR9hZeOV12rhJrV4BnwCdH7CS", + "iRzTvbyvylQd7EI1pIwKsmD2/yx/Lwv4Wcz0s6nYwcMwJjNqN4GL2TOSnh4vct8POVQ47DuJO+7NvuHq", + "1dwvXdsbTqcKjmC8VHwR6lo0sngFr6BHJ8jvWhah3VSsAA8U4mGml1wkiy3csjZt6zgEl2moRJs8Dp1w", + "rroGKA6dkC+ddXhTHvHaGZU7sOID38/NdVhrteB8x5ahNmroN4e07YaHM3EaEZizdVrSx8gGL+HiPVPO", + "qWZ6bFnNFQP5hhaFzLB9mGGLUiqqlvjyVDQH1WMIkIFu3hdgPrAatsQGrTGRz5hxb/DfWE4euLMD3dMf", + "AsRHBaMaZCvnFTV1uyCuyYO8fcqj4BQ8ag99wIZjgG6bp+JqLgtGpJpRwX9z5XTabwUqHmOaKDII8kAD", + "930I/T8rYexkVak7U7jHSS7torE2ppMo/Ct1kxwKZAOwHGjjLsZkLq/GaPmQ5GruG7e7TdBzX6y4pDxP", + "w3oP3uIYBPBx6wk5bPJmqxMJGcngrkM8SNpOvi6tpJsnM6z+wqyEXqNDsRnFZq1Wf+Sy0pEAL3JSSoOa", + "Mki0IGYDwVqcLaMO2JlUKmhom7C2A5lVdu+O2cWQMIF/VhSE+RNBSz2XZs1dGMR0/x3R7kPtD0eTmcNi", + "DH3HxD1fMfbCOJVek9noQocWbUb2mFPvHlKQETY+k9iVrs+4kZI7HDvm2oVOQ0p6JqE9I9bIXJQFtsHE", + "78euyK1ijjah8mtN3Bg24mdzWmKdRtA50o33brjgfl0UzK0OBrdw74QMbAeVmyRsVVkW/AY68xFVps8j", + "Y+g1XJVOQYY5lqsVZHDnbY6cU/ysC8ZJtVjYS9P1m2+IofDN2BVtA7DoNdPkQa3YPUziygfmbgYhVBXq", + "oikK5eUtscGH+XqAc2aYWgAfARd6pUqp218DW53LK6uk1tfMnIq8cFL6STCY2AlQ4NaGipyq/BnZszy7", + "KqgimVwsmMo4rU0zueOmIViTEk84MG9gGXbMTLGcmzMrRzwjx+yiYJlBZ+pFJUJMZ0mV5f+WEELQaght", + "dvdMmHdC9tywKJ6wiwsGIXLFkvwrA3ON/lf/LV434dPUTn7+TVZij8ehFeUSesVPtbsDpD3QKZACzpdN", + "9u+UpsG37E//f/b+dTmOG1sUhF8FUV+fsOVTLJGS5bYZsaODIqU225bEJimrvU0FBWaiqrCVBZQTSJJl", + "f3qG+T+/5jHmeeYF5hUmsBaARGYis7IoUjdnxznbVCXuWFj3S3XyPiT2UvJ0QxETuzhVSvzrGFlvRO1O", + "MFRMO9moa+C7JXDuUDdGGa9sxxPLVrdgWS/p1i2idZxyiHbT7IqugN5ZVsU9t4bE7DxOnWqorgebGDH6", + "TOCRc1Wav40cHWIfdr3MeMI1eLaDlcAtkV0vDd6wLneTeFbFtspBvrKxJV2B5ndcJujximtPXDzPUSfJ", + "wV29brdi1DRLbTaNajOowQ11pLEe6c11TzX7HvSK8uKn1Yki85T/hCCF5XJ9TeBGbvZSpLrJ7C4+5kZz", + "a3p903k1vb7JnO86oMINswcWqYDLi0NHtbmTViz/VouVqLF1ntInLh3jmRBSbHl1mZexmvCSM2XEaTEz", + "7GSL8xfoApqKthyUT9ZUbuc2+MQQYEA6VKRnAi05hlFhqcFFRGm2RGuNKiBQZVpkgI6eBrlbMe4JoBD1", + "G+f20deXYFYPgVK2GerVz51e/dxGxTi01+tKQ4RTO5/XvS+8eoMf7N7jd95zzb2X2VgZtT+H5dWWLDcE", + "slTBBpcQrZO2uU4//sZiukaYoMbuoyKLXesuQQgh6S7XhhOEdm44RQuFqm4qiq4SrX93t0gwAFbP72uQ", + "lw2esSpDr8ix928tknGZiZceAO+z4tori+ni7BshjZcRW1bOdL66u2M8NsNXPBqUKsySDFLEa0dvo7hM", + "bhm0f6NyyT2eO1mpU3g5TRZnGACBTttoWQkM87HlGmb67hb4i+Qp1gMxE69IFQgjC+qg1QdWmwN2jzYU", + "GDaq+KeU5+BrpMWMMBj0iY85WxGaGro0ZdFKFprN5A3gMFzivlR63w1UjVG2An0jQNk1rwQm2xU2bvez", + "9l0BlcGeNaZE6d4+ahVo2Qa9v5i9V67g2oFxwbbI06QsLZKKCwBAB/q2X7CpBH3vtfVXsUPexD63X9tD", + "H1H71n12Tr1SMbFQ485lcG65c+cWrsCytTkRMOBz4HtHiL375tTcHbD/nF0RvxJH+RG3XXIaMgxfqaDh", + "3tHhGCrO0oRn3LDWZ6L8CmgU3gfq88Ss9AoAu0kUI72Pd4g5ko/vIVKKp/iGPrjb+k25smNn727BERVP", + "D6CUFyyTYqaIlpNgYocquovJBnpBC4o4ZqlgssPdtjP5ggo6Y+nj1Y3g65nv3TwkP3LgY8BLUDA8RY1z", + "cK+LLjmRObEDkIsVebFkAgqTReHu8/HhoLFEXT9G6rg2ZiSPrTliB6wQDx59145zHzz6rl6M1iNgrpYZ", + "XREbWNOm67rL/DHdD+Eokk3GU98ly18KrvfeK5/OmvkhqU/gfkQuGEgzMksntxriflQJby+fPNIlLF4u", + "cwI+6YWBhETOBHqrL/NiKRVDz0trpHRKb204RWXdIcDTALMp4DZsSvJLZku9p/Z3X3ZvEroI3M0R/9s5", + "EnScck4126d5+l7ywrEbJI7BzRwkoXlarQONTy9k+m5ovjdLaDXhn1TM95738PQ4oVnmDRkoWmC4DnIL", + "Y0uakRNfLS3zHaBM8BS6sLDBxMw0lNM1mFQVFxW+cPP9BgN0UdCwHawckZ3toJygadejl6UmLiCQiuQM", + "nZMNyY1Zsen1PpT16b+XU9+lDyif0mtbOIi4urdO9d6sJ1QFKpCYIlIEClIhb1o3599EtDrFyKU+EtVt", + "uyfgh/oJdPgcrD30wJ/AM5VBZrDzKQOt9lrjyudvGq9p9jvrpY3R0lgyfIGNMGZA9OkLSkZ23F4cdZ26", + "po8KKuwQeoLwqu7GxaujC4f5IS1A910o/yc9E4lcLLh2fhEOQEpFUfm9JXCtnZ702YxrXDcrlFTnay40", + "E/qeL81kt+dguqpBu4FsbDmDLrkYPKoiQmoV/5QMWL6RKNWaULHFhTPkvfw5Tc7EK/MADcM9rtRMLB2r", + "DEhMc8ZqQegu8eJoZ3t7VGNugS3Nc0ZzVb4rSCz4rp25x/SZEfB/X45pE/4IwxCAu94lO6PboXMRvzZH", + "2doupBApm3LhonuaPYJ7QlMfrDnScJlR4fivSpln37KZbwluogsTWah+TFWHAjxoVFWAG+FqBkt3z6Ni", + "CAweiFWW200yoXneYRf8nHXMfwnl5ym71hXFZ8VXu4QGs6VA132ngV6fmiqv+Tg+QpBX/YCxAPWNqSNW", + "p44aOM0HksiUfaEOljXU2sk+2lPuQrxBOEJ/owyYfp5LzV7Y3CClGrbdBB5M5cV3Le3rNVg6jFqShArC", + "rrnSobut4cJgrHtdTiXBRPH6pPF2BAkkMn7O1dnP7LQOSNr9StOQXQ0cjM9d1pRzp9LuYFufgNNh6zrx", + "cy34a0lz3QxklM6BMchSYavPV+qvQrxfGDhTehpODNbpWu0/mTC8UA1yakapBddghOQsS9XumXB5QQ2T", + "YIN/uLBFyr02IWdpeeBzCuZ19Kj2scnkYkWUXCADk7OZebOgHcNXpiZnAt6w2iUnjKKrko9xBpMoolYM", + "+VI08Bpa0BXkMLZp4c3RgY8vu9a75ExD8L3yiRjLhKuAbIIxLphfbUQw6KJmgTbbxx5duPri7X7jneg1", + "or0uQwYrJkNhySZoatxD5IrMGXKF5mxcznzH+613ibxJaEL9AXdHKXiIqT7KpvdFI9346yD6uA2246gq", + "hpuwhBc+0gTeJyaR+wp9bV2N9zas1en7AQkYDd97c+8PH4wMHjQRXnfOszRnLUVoMFoModIFzMCcgViH", + "+uANw+FCz5c+HgSD18fg9TF4fQxeH4PXx41ERavl+Ymt+jo6OL2Qj7y3aXOVpyg1cPru27o9OxQi6dYf", + "21s/vP7fX/9j99z/4943cW+QwUWl3UVlcEj5qzmkLBikxTvK4fDQI+Hft6jKhjzLOEeZPyBUawMfzIVn", + "KBywfeU8GCCGzggsVKwCtOv4jTLmT0ix9QfLocRQQjFmeJnLWc4U+DtYU/jYEWnD1M7llYJA4kVR5pxB", + "ZATqPeuHbbq2+K/bzd32mUXPCtClT+jnjtWBgj0ue5DV08J6FW3Kys/DMekv4HazvMtn2P78Wt/eB31d", + "UE9JrGyDxkv30e4GOUfEE678DuO5ZjazXDrrbSklo+lvYxcy2M4W8jUxR6ffP8Q114yHd3jMN/bbKg/6", + "Nry2XHqJsnFCl4bndImidJD3D83O5mGWxzENimyF1zf4gw3+YIM/2OfjDwbv9xze7+AS9nFcwkAjAY44", + "Th3TqpNuNq1lzba1T+O6ScxF5/KiuCcTqirvsjTrU37NSgriVqolLGQVZlwyQueS5QnUzsHN3Zt03Dme", + "SLXqTrKq6W0+d0324Fsy+JYMviWDbwmYCDpKNrdDbSdR+UskKvqkkgWZY+/0vWyanW3dqpgRuJH+2Se6", + "BGdww+CRJKNK+VILpSSEfIFVXAupnbcBSXnOEp2tviwvzcEmPNiEB5vwYBMeMgEMZtbBzDrE/Q/mtcsh", + "jHtQ2w9q+w+stt8Y6E4N/Pe7r7rGH6yazngNgRYJFVbUwzI0KaFTzfIysfNfQt3SR/tvU0y/jxFgjaKm", + "Ic11qQTqjWthmVZyRZW4FWCrgcqdguhdaf/36gsCCRlXq25Fuf8+imV7auh1YVe4ed7gflq5g1Bya73l", + "Ugqr5wNueCTUkCde8QpeedeNRu8HDfmtc5S4pKW504GEKhDUflRi1x1u3BS918xkkXJlYM9sbu9lkMJ0", + "/e5aWsc2h24iITdnXxfu1xm1UIX0fjofWFX73teoGp+F8kwr2D2LyCZXc2kZLhU1IVeYqfEIK/Uiwixo", + "1hXWBmkg2DKjCUOk3bm2Ssv6s0CsTRYyZRmqOAV5+fio8ipKnShQwAV9yxRofJ0SR0t4/ldYWBsIoZgR", + "wa5sLA5VPsaonHPDgLOPpjH67N3QzZI+FR3Jp6WqGMT8QczfxIv20/T0/Eu4Rn66onpcMtpcmDnxWqR6", + "ZVvhi/JV4+pVU0cUsBegDYLEmBi2aliMZcb1OsYirqLpYjCiPaq28FbVDdLxdZqbKp9gtVZHt1nl02nC", + "lhX8Ey5yQg6ti3pj+QZKv1L1MbgiKZ/CvvWZ8Jxv2LPRqVmJyx4jdF2/SMK1Ytm0XiNmHLjXQ826PbKQ", + "Qs8z5yVfHYSKZC5zZPAfbD94hFQW+zU27kZIKc9W6AXuS9PAbV4BGZ/TSxbGk8hpOfSDykQPfdldMzpX", + "lQmwVO/aczwTzl2vXH84ycOduHnJcOD90ejBsSWzbQYcjK7pr5CEKsa3uAAYLwrMt6jdXbeINfPW8GdN", + "KsITsTczrj39NRj1lF4/ZnN6yWXeib+Cdj6ZxVxeefzv4LAm9oJvCOoFMKDFcxELRi3eg+7KlslkPtdJ", + "teuT69aOaMeKTBgges+9AHfs/l6D5Z3CN6Zg3rdkUEtHvJsUkMIKM3S1MYL6pcuEU5Ecm7g7uJDNFbnB", + "hUZy96jajfn7AETo/zGNHWazZsdt5r2j12SZy0uesrx6lm3lq5ONSm0fYQc6Y3GOGjyCw5RBS98Byjx6", + "syk+AEyPicqaM+FT9L1lDW9j+N27GpM9InjmXZChJLDNNmOG4cpyU4sLaWD7m2/YNVss9TffWLUQvZ6c", + "je7FMVOO7pu3oVI9kQsD0YXQOYd6noB8wAu8lOH8jN1b3qh0TmmL6KFI8I2bikzLU1i7npxaLUuYRtCF", + "v5bvMZrMdlyPY+hCGVU9WhdCrbSsedqH3H3p1N6iUMS6zGnhC+alMtDDWzkCxbyZzLmeh3h6yJE4+LEP", + "fuwfxo/9TiOMqyGlPr63hjR81WqQcq3Hm0EiZuFA5ng0tNhgDCboRYZVOCv+RDQYrMvYhoYPHyJrubxC", + "8FLnLVKWYwF3CLC/ixBdPCcXGXT76x2CFT5osIIHjw4x5zlWam4jxvgZIbkQ/PeCEZ4yofmUs9wr3Cyi", + "GpMZEyynOnAQqgQOeJKMQwmmFEnZkolUEYOrSYYFsac00TLH4vh0uXQ1scnXdglLxIUGhQW/OA/8e6ab", + "d1yF/gkTNOdSka/D35Vbb1jBtazeregCkMKUX9+rXPvh81+2yqvf2t5ZrwVv4Ype5CnLOyyD9ntNbSfN", + "r2bNtnI33EMpNUGqvkqqTheaYFWLWL0RAKb0p2iBKNSGnGiad+r9juiMC9PpmKmlFLHgCt/EvC5s0whT", + "cYbZuCZEVZ0RNFna5H6bGHRjtutl1HQN+g+wu4mUXVdefnmlXGg2Q+xm2p7wP1pGWljDIpZGx2yJZksG", + "ct0+yvG3t2MzgEF/P849n3qDf22GysCPYgPX00WWs9ijCfbmDrsDpQTp9FUMDLCMktfu+uyfwKk5tYkD", + "59KGt6Q8wpFrN0tPQTdcW0t+efMNsojYldaw3KTT4n/ERMrFzPoLdVnWGy3rcpp1yqxY1iu+Ju+VAnOw", + "lb+/rXwwSQ8m6cEkPZikB5N0H0p4KJaFvk1ySJbYZ43F4AOEX7qc0Zgw3Ov53o1t9vmONNO1Lpsxs01u", + "4x1gu0McYyfiqlgRI0snalznJtfZzumv69EoPOV+9yZue9fufgFlMpEuJUdlVSy6fXPX/jVRc5ZDdRnA", + "7RV1REJy5aRmdtU8lVdzBkq8kLu9oooIdpWtQgBo0ZVdSJkxKvoBlUFpkFvxhoDVL0V5DZxcpQV3H7UT", + "6Qdcag909U95Zqh5b5wR6VbxpOXJvHxw1ppaTW4QwRymQzSBA4iGIXCiLNc69JjwKQT4WyNeiqoNlwzA", + "9sYsmpe+1znV5KzY3n6YEKpeTH0CIWcMNmP8FlNISpGtXsPwReBQHUxVH4kUS1D7qRfTsQHIMxESrEhH", + "pSEMLGDNPBl0i0hWScbAncNu8/BAObtXWLJjTBaF0lhjAMtbwL89iwyMIMXiFrA+OydFmw6saEp5VgHx", + "mhP6z4cH5OuXgl+yXIGd8iWqjX5m1zyRs5wu5zyBDycy1zDjoVdz3fsI3q69PcybT6DlyVjm0XYLmhrW", + "B0HV/KPigB0Y/9A/wSJGZ2riPoDQS5tOtx55HQ6BomrQwQmSBsjJsdq3wuuZMK8Q7dvkyWIJGmarnqM5", + "g5cE/uLR0Bn1YtohkCEklcVYvJGltM/BXqvvdVzRO8FAQVW4W5TfnPx+2OKH7eX7wwO4K7sR6UhmDZ99", + "YLCdIvrdmBKvwf+xnGbwucxiBqp7D7hVdQ1AiEOS9h28uGR5ztMI9+K+WJ6+iV2dNtqZ08LEL/uB9VxL", + "IwgYZHIfzUNx41HgE3hRKA5K8UzOeHImLHFVhOsGBan68+VyyjPIj9uxYIe8fTHDGmPR4A49KHaQ7g4P", + "z+NaiatWOrs+6OCDgfRaQ6XwBpONINzaWeIcZ6mxre2129ONr7mYPvE9G8f2tNePtOCysXnviOZ6VV1t", + "m8xlcV8NbwNHYTNafJpqzbUMe92/LzjlTdn22kk2rR2fjYpQFaAgu0OIcjNUpfjWy3hXVo7bGAG8sh37", + "LMtN4jC3itsgql6v9qxKFsJL9cGqO/DFCV/YgMluoavWrsk+KtugykDevVrGffaJ1irGErSFGRr9rMg0", + "LxU4Dc7SHKXMDae6YrpLifNzoMCpw0xpCb/hUy6P2cni9Xf8ASnR+yiOahtZD1bN9HtRYbTirojQ5yJD", + "/FAdSqPB/vUhShYRK0c5VUxKuC4TIRdabvmHAm8TyndXI799Vxva4rQDpWimZLl77+SVQO1HX9pRDyGr", + "g31wsA9+7oVfxvWEbTa0KxB7s9Unbdn80GVVBmvq52NN7eey2RbnW/ns6/fWI33jAR0zqufgUzgaj9Kc", + "TrV1E8Rf0GEQKCO4RJ0vc5mY1wZf5SXL0wK9xMABtRCJzDKWaG5w/nh0KQ2d7nIfxDVjfdx1O7OtGlEt", + "9uea7zxuHFPnHB0aqMyRrWAikUUOVgwtSc6yFZFW3FssCrAB3J9C3PN9ekkzbn5A1aSNrlVYJdkGO2GY", + "k2DXmijNlhEffqUZ9UieXWsmUpbay4IBI6psl/DaTrzx+92rDxB/vTQJSoNbjnrJcsNRoFa/LgVXl9+8", + "sCf2u4M7LpA7KV9Hh5orxhZjAHoTMFQ9UIISbAszs3/0Mqf6C187AUs5NOwzbl1Z5yfx22mc47h54x14", + "4NTn0Yvmw6uEz6tisaAQrWZQQJZV8yNFruSu0pGVbqqXNCuiCZwgPdo4lAJEShK5WHC9cIXFm9GWENSi", + "YO+3tU6by01OI2v1uZLTAtXbQYl8XEp8mZh37aMtszXvW5jZ+qOtzq+gLdkmUz7U+VYXiRBZLhUz9JX5", + "sCGI2uBBCXEitmEl13z7kn1Y94dccl0f1b3ED7CyHuk572wRTcjDlJs3wDTxzIM1/NN4S7WHHweMOIRX", + "bsgdUhdV8LXJIhwUpCetMU7apiwNLf2nzd9LVsdGgBe5kTzrfI45wbm8IlwHuow5FamtU+tz12kqUiNP", + "uKM5F1J3Jh2IyCJt22w2bbiceRHkaxQ77jn7Vl3XGNEcbl4BoBbI1jOXbCXpZImMIqHOMdVhu6IwsKRB", + "6CIoPGDAQrFb0xZaLcpTO+1btooqUW5TTG+4aIWCub/yiVUziiLL0K/DHU1Q2oUrMs1ZRHt1O5JmA12V", + "smXbcguBCRisL0qzR7ALFIimtMh0pOEyoyJ0X3FXVQq4De4Vr6kD7Tjz1qGL9zuxpqt+Zuh+3dfap6ul", + "irz1rCL2eutahM0ttNxLL6n3ZoATjL9O784pQY9thBv0IANhuYoTkdiYOzGitVX3zSGppWrxxRi72U9v", + "F9gOGlDhtBbelaaa1hZlZ3sdNmtLIlNGvn6jMALd/OsNuU/ewLtI2WH65h6Gc5ZuKRFg5OpMlCgQSS8V", + "REiSSTFjeVnRROYuVfaujX+cUcH/wGVXR04ZjGuzV4DIPSFPrjEm0rTZgjbAECiyoCuitLVG5GwhL83r", + "Mit549LMvDG/GzHqTEwLc73eOojuBuWFViBmdLR9MIqiJLz8msRljYhv2RJcI2FUJztPsfBEQTOSs0vO", + "rqoRfaOjnYNQ+3948uL77yAktZk5oWB7BhRrK33YvVSE3qjDXFoYduEV13Oi5IL5iDklswIlS66/UuCO", + "imQLnTmDHTlFkYSy8XNZM3fYtfXZXJj26YlIj3KJcP1MpmxjQt1ER12j4ytz53nBs+ycJrqg2bnX8dUs", + "1VLoXNokUeHCt6zXpJobEBMs9fTIa/Fz5qv+d/mFxt0N1qHfm3oDlTgV8sZZ9ZiXRZzqg1CS+4dWik8w", + "4oS4omnel7S2OEcSmnj7vZ0y4sRqjXNGVcPdaivv43tRX8fai3IN63fU9BxBe8qqot+plqhLMilY3Xu7", + "RN3NIa2pFeyXgYDg3ILPBITQex5TWodKUEkpnrI86ra7XG7OUB/hKveWS/UiX1cNCSL+MTIicIQ0qFfm", + "yZwpndccaIPNx9PdgbmxupSY32603YFznKmduAH8Etn6w7+igUHfiWiuC1dECbpUc6k1Pp36nYwraJx7", + "LS/NtLkOCHFfMpFCgp8z4W0wdnzMCfnxnS83f+g1hL7uTTsrQvlqup52CwCMb/Tm12DqZxaFxn3Dap76", + "L4A1tWaKqv4+fNHO48miZxAsVkBywE+ekjlXWub1og/BEGeC6jIewGCENcVHb4Se1wgVXWFcFTnAI2t/", + "P++8TevGIGVTCnjU3SKKOtaoYy11i4E/t3KRUXgyAgcwdsdMsZjjHkgkiAByaNK3OAWeI9ecZmSWU189", + "vOJuIgu0aiy44ItiMdrdLkXKw3hnuwfrwYZqAJlbq7hnpXZaZHpo6WEysjm/toIL/T0qNHBpDx49ChYa", + "OHvgGdllloP56UZr02Z0FCH5mSttaNQx+71gKnLO/y5YviJLmtMFQobN4gIyDAUPB6CP9XsrE5e0HdlR", + "mcDEIAYn/nFFduoZTSrHsia7iZtue3t8k1wn9aVsbzfTn/g729mGf3as7l3LmT9B1Rboco+ZgiU3nTiV", + "djowaGgu3rQcj6RgFh30ctwMZou4a/bu20yl8+613Y/VpXXvxaqBbr4PO8vGe7D9Wtb/jOZvmQa0fYhA", + "bV/DEV1lkkbYpqCHeweQa5MpbdCp6dSWobFKktfqcg6nBH4mtMGNOVbRBa85wR2zWRlgxzx8kGfKOzZm", + "SkLCOKoqqrj64HxaCStLyxdByQkV6YWE2tdx/VDcQe45XXhe3orcTrtjz9CHt1EMYqsEFdkl+CTri+AO", + "LE76SkHXyahXze3YtbfFjccvHFtHBYZ1kLy3XAaatKcy36dLesEzrldBGtWYegzCIF1jjlHNfd7O3nJZ", + "nSMazFkhG8vlqGuJr7sP9We8lEhdqdjdTc7EsRMYIV+tczfAEuvCgU2lb9XP2tEjCyChLg6964OeIHGB", + "9geieyHWzTpQSeQ1Uym+0tYbBsZzqcCtUiCkCn+OKjdi8Fm95CW8RFBju5S7mDJ4KfPQhdurNkfj0Vu2", + "siC8ZOe+27mm1yP3xkb77mczdgn3vrX51WDH6HJ8fIETiG2KubQI00dXluHiv32PcikuBnc/+OTJIXwq", + "v7QuyXKTyqnfFJGFBoucwU7OzxRWaXu4lQSqXMfRlnq76lHi0OduruA08Qs5Kr+4A8Uv/kOsqqk9U81m", + "Vm8NgcCKrGQBDg52cL/FYBcQgoEA/AwWrUA/w/X8XNJCzx8Yyc38iy75udnMa79mHKCK8vBx18hPBUL/", + "jGshvlIV3DK5EXKJRYR0p8b1kwe/T+J+69UzauqiEDfjzaOBAFgPOXW/BfTGk8v+ATDB9NHAlyjlK/fX", + "Qp42LQC6t1wiBm/TJtmKns0Eeli30vp5ppWIjzpRqR51P2T/GSRbjFCoIe/iXeVdfMaoKnL0eniay0hN", + "BtvCxgZNTZtQLOgO/6gOfoRC9jphoN4N0tqiIBAfcLdJq2zFvwV2AGJjM54GjiT7L4+Pnzw/PT96cnz4", + "4uD85HTv+HQ0Hj1/8arpTDIeXW+ZfluXNDevE/A/hg1aIx4mOh2PnsurUWyxsI3GUn87frr/8OHDH15/", + "Pdd6qXbv39dSZmrCmZ5OZD67P9eL7H4+TUwj8DRZUNDU+lAdgis0b+7l6f4tx/w8C2N+vJ/iUTWPZmea", + "9dEJg6t4y1Zb6Ey1pDw3mN+NXakboCXW/gi9IkMXYHohCw3GoDJGKGDzymTroGf+YefbB0myRbd3vtv6", + "+w/f0a3vd3Yebu3QH759MGVJ+uC7kEjYV2Fueia37I8LuvwNd/a6ciqxxMd7mK7amkaqFnLDCLsqGJCo", + "VJIF1ckcTMZ0NsvZzDCJhn/SqrYp99me58tnlaS7nbmkaws8JKfyLRMEgNJMYqZDty+D4hdLs/1ZLosl", + "ZhYGTnq0O/rbBP/yZ/W3ibYSCk/XafQtHwQzK+K80VRWzEa7Iw2/nmv7a5Buu2tbAEgWCle4HBinyVVV", + "zm6DuDWW7wU9W+h42QJd3tANygv6C1fLvnyQ5vLejUdQx5tu6Ji/F3SKsLfRZ1aruk+w0OuE7PtK4guZ", + "YnTlxQpCHGJBd611noMVRYjLUPLiEy958dFilQHvxPkNcF00qFBxSP/i3pHzCXVZ0iymPBMvFZsWUAdY", + "veVLIrO0/FYPIR5DAAOapnhCM9uy4vZ8yxQ0QLGxrcJnjz08IaguwqPmNanhA8x9Q2L9nC5YSv518uL5", + "EdVzwq6XEBoJET6SsGttLh+zFJi5DNKwDlHeJQN3ZAg7SHc/sVUZeG1T7qOvtFAg+IGHT7acU4Fe2fAV", + "SkCoxDACVYgLyGKDFDUQUCzKfK+jGEGUqfgw5mpnSzoYIq9jkdfe5lPW8MyKmUts5d/37UVoI3vSBjxj", + "Mq/uKQJMSP3PxDMD++8L7XU+6U6SMnz+tU4anGF9HxHMVkdsyD15dMbFjCkjcAFe+0oBZiOWyVx5fxrf", + "zHaXOTl5+WxM9n7555g8O3yOvqHP9v4Tco3Wi8pJ/zmhTpirhFPS3EpGrqkvsfry+eG/Xz4533/x8vlp", + "OPC4unRck0PCbpIJMUM0+paH4I4RqkjOhMzrF+vZ7jWUqZl8rL1qCDy8cYVvD4loXIlRY9fjCr7e3LpV", + "D6CgBeczGo/Cox6NR3u//HM0Hj07fG7+795/RuPRz3unT05Oe2oOToqFGdtqbDClqPvX3qXp9IybjT8D", + "o8HPVDOlrVZBs7ytPIQTQMN81z1kybsXEjcRAT932W7guAeO+y/LcQ+c6sCpfgBOdeDyPn0u76aMXGth", + "O/hg8F9Yuw5gV4VsG0aL2tdSnT3Oc76O2z1YDq6VrY6Xjtn6HRwwrXdZxNcIgwJTGPGfSC6eBrmuW6hG", + "p7ccdD9pISiexXAz23V68mEzbU/OxK+yAPArlE2YpaX9Cmdr6YxlT4JRHq+sg3iNPlhO8M/R37iA1EBL", + "vfWtYRbNfyXwr86O/jf2O9gzIUd3jJIkGWdCx2Ii9uELOTwIORHzst/6XF4Qtok3U4Xl6d+/ZY++Z+nW", + "D98mbOvb7W93tijb/m4rmX776NsH298+2qEPq0jr4fqKjHhk+x3p1/HGzJO/WJX1Jb2PTmWNRj7a2oGK", + "nFsPDHB6q3lTL4SF9FXV+uxt5Liuf65nUdpn6HQTGZ1ws+QQZByQWecZdm3wLRi64qBiYWRLF/mFDCDF", + "zfyb48Rex2BkGuVn0fpb2ke5IMdP98nDhw9/sPZTW5LAZ6u7VfYzYAkbrqLVfJbUcNyzjAX2vysfUaqL", + "XFinUUaTOVEFbBvLBJttXXGRQtTcG/vpDdKZnEEURlrjF2swVhHV3gfI7OR9Yd42r4O8/Rng3v39fsCv", + "ZSS3lEg/HlzgfTlvk37M8auyT5M9johaDqDQWWMNWIHoIDTPWRkSUQJnEG3cgD+ArOrxHOz9Wm7ylC/Y", + "f0tR9Z4evTzdjwYLI99iQ9pE4IQMt/SHFBBRZDMYONeiw73ne6AEJGYickA1vaCKEXCj2L1//+rqasKp", + "oOBDYQbaMgOpe1ER1Qz48nQfJoT56uUOyn3iJvp4LwccRNzl/hSFiiLTSK4CdqKGLFGi+u3PmNalij91", + "RU0TPk+f2xveGJz5aHfngbuyJyINgfzB6fb2Lvy//x550AUHl+pL8I0MeCI6jn/HB7lmAngbDpRqmVOs", + "UNlaoR2lX7hbZN4NMnQ+yoYvJwyqwQCCMB/dW+jvmFbeKIZ/Nehtq3pFOYckXQbHVxIum1vnNrC5FUSj", + "rTEQlM24EK6yiA2lu0XcFUOmoEsRaZ9dadl/T1hOql4y51PHxRAJCg2I4n/EUmp7ZJyuP4uyLURAB5ja", + "HnMznhTex+tuPCSvYlJMLq8cUu2HjT5hJNRWWKRPSSQdkqLaDUxGN9P9NTRT3brA04iWr+eywtIXLQwZ", + "Vq1AKt45aht8tnUAFW/I2K3dtr35LjONU2hMogGjjSjQAIDWICr7TNed6+1jG4TcteThQ6+vhkjwaqqL", + "Do+3BLDyBbTinbaIdKc7CfOCYPS5yFYuf4B9RxUtmdXaVM0HqCWzBzIuda6hayWXwoxhnd5iZuo/19nB", + "3t/k9e7zqCQxGDUGo8ZHNWrELuG51E9lAfmTLjK2CONX+t3JS8GulyzRrDFEnJ2TOZ9xgSktcpLyFPY6", + "5QapeN7U59CpJqjWNJ8xXfrHyNyFy17ZOF6bsjaTyjKLRuzEQqZRqv5c6kMDsQsmIju4s0Nwu5dMhQWO", + "MGlgIRKEZK5RAW5oCOiQi2zKbfhWoBiPbYpPbZjx/pwKwTZJ4trs/IpdzKV8G9lL2Bgywgn0jOizJFeB", + "2tsB3nd91QGbi30pvNcBFu+AhqqsUSnYlbmNxo5Q6ZqwXFOOA/Tdo8Eqsdgfi6AAu7qcMEY6EC3nub44", + "oy+Oa/U9LQOF7pd7x//98PnBk59OT3759vj46dN/f/fDPx893fvl9t0v7Wm4Gr9lId/3DwmMHHpLiGAM", + "VsvLrK30NBZFCA5Wus3KFlnJZja32J1VTHDl/JvY3CLr+gzCFWM4bIhXvKt4xbZX1FyrTUHdiWMsuL56", + "8vjHFy9+6um654jM6/hy3Odmeo1WhH2FXfwbrxmQP+1YoT6xQZ95LBBqiX5kNF1jtF8jFaGFmPx4enpE", + "5jgaFqCFdL6BBsDCQ8g6ubUGQ7gFRZ7JFxO9hEWwqwlypzRT7TmV58w/Lq5cFW1IBCxktZJfnPQfuCmj", + "5V6+aIbmM5dzXyqWk2nOmUizVcWQGL0Gr4q2z6237OrO9HmbQx6fCUg4mOTR4HT8TBR8L1PB1l49uaQZ", + "TxGMpHukCeOXUGlPpM47bEH1LnlzQRX77ts3UJoqNbwQFalckIuVZsrybpBhfJmzKb9mKRKeN1dzxZLz", + "NxNyzBK5WNjCS/wPtksefFs5LWx58t3swY8/i9Or9Ie9+Y9XLw+fPZ3Nfjn54cVUHtHp8++rAPw1drr3", + "j9/o1h97W/+9vfXD/77/X6//fPhgvLO9/S5M9e8OxR5aB7e9Aa8co+8x9vkLDYUp8qy5esuekJfHP5vF", + "26IOFaRly6JXF+6yE9hfJolc3C8fjltWMPpaRXNbAEgoPFj1kNlJT24wKmI3TsF+wFeABYAhgyI4E2IG", + "r36ydjfr9hkyDp8YwR1I0kCSBpL0OaDzzTH2k0sW1TK0Se5gEfpLy8ee22ieSygmxzwb38ti/D5ZNPgl", + "y1dtxT4h9My2CQrNtl/9xio5ALKD6jLedUqkuBhfVrOuyOubU6BzG6Ew+K8HPz0/2vn19D//Pv7Pj6cH", + "//r2p6Pjvx/99/btC4NwFmtkwGWZUndzvTZM4JLyRgxKtwTIjWoKeZHdUBN/bHrGTV+isjYzhS2BMGOC", + "5bA8iJnwl9qsSnhjA8ETHyYTWdta/Nh9/2ssBlWNPZxs4x2XYNILxz+mGRUJO53nTM1llrambbYfmkYG", + "CxnAIIQJtycXOPREu7HftLDimzGRfbdwEGc0bUQt9b6RZcrptrtxW8cRN09dEjmuYGZywTIpZopo+fHQ", + "T4Ux6oOLtMMXXxRN1JvZK0qaYVnHbvg3L3KDC4gzmx3IobyTcbvP6UbPp5lIu/ly7gIjOGGrP1ZwEV7w", + "4lvv3zcah1fVf5Ygnz/40LG0c75a6QCbwr//dD5lf8ccQVr/wLu03/gntkPX+L7NeFQC8o3peR3YfgGP", + "xq75fdOKb+rG17V+oqAxsa1rby0EmfI2Q6dL56BZefLrn6DjbPe0ZoulXsOLU2y1iRyWb+yMFFtXhz+S", + "+1RGMVlBLIIYcpbwJV/DD91oQHgE2nq13pCbqMojJzpeiQh+hxtg88bN1FOP7O8/OTnp2GvnYL2JrQWH", + "7sXcFiVdO+1awoX3NB4FniHlNjd6NbcmwH6Jugt7HaqlqoycNm5Ovb8sv1eC7lphfs8tsCnOJ7fgdgjO", + "c339uCIAQ5WSCQcu1TA0k748dOBuJNi1bsfs9YdkWjcfMTmcQmFrwjVZMCrAnp2XwZBCkoXMWfwyP8Dz", + "j646xmHnjKq2LGD4zRf0p8oPae/DBQdUN/WUclu5JOVqCYmbrYN6AWmEbBWcnLA8l51vBxHxMS4xpqr/", + "ILTlIATBDsHDx+LFzBVtVOcm9lP7FOrW0w8mtq03qLbSFnuToQ3TYZUAN96A3JzoaPBMg+ZseH8+vZ27", + "vad7hz8/ORiNRydPnh8cPv/naDw68n8dP3G/vm5RkzbPqiXlXZIwZXAwPiYzH9YsNvP5v46Zsn+/jp1Q", + "nd22kuRjGvMNNb8Sb+ajYuXlScxOEXDj4d8+7mwQGD99gfHzENd6vX5boAl9F95TS+pKulr11+2oRe0C", + "B43noPH8kBrPGix/mipO+zaQhbilx2tZiuHxDo/3s3+8FpY/zcd7F/FPpRl1XbCTNZt/VqFO6LwzBDp9", + "iECnilvF+6sgU266LwwoSRBmFnS5tIVg1xgX39NcPhpXJ7Dl23oOCiXqy5HqXEHfYeJc9riBqDYcr0b4", + "y1QPq+eYCcKlF+hXO6979+tK6PW+kI0Hip/eTYepH1qvl4Aago68rFHmguogC96WiqrjHS7v59QJuRDQ", + "JahMWGFzpldnacHKL38+PCBfvxTm6SrwhbVhOj+za57IWU6Xc57AhxOZa8jeULIg9+6+Sk2Exan4qjYV", + "6u/6XqC+RScgQCN35PjTpW8aOOmBk/5Yjj9IOj9JZvr0bh2cojxEkx0YxySPTjb8uMjWufObJnfPQsWc", + "WG7MOpnBAiR23HJcPUeqkv+bcU3BOJb+3yq3FD29TRiU6IltOkDtoG7Y3Z/PuocX3XQ3LKNHc80OEoHY", + "LzstQSvH51wXRJzzmzM8QLpcZhD6Ld8nYwh6EDT5K0KV4jOBlufjIkx9WHowDFVWP9M8BQBAG8VMGhDo", + "Dpi0JijVkU4Q8jiRRApNOUS4ZRbUXd/3gm5r+nMQveDCZWlvmAf7htd0ZVjILUX+OOkV4D7+CrkVMNF2", + "WzDrmhuxhImUJCVnNJkDBPeLb4Vzbgtu9cN2YPGyTQnckMtOgfvOBSM657MZyzfIB97T77haqaDlRYSW", + "Zndcp+W+IuUN1seewibrgafrowcqZ/7l5ke4eTaCJFB+lFd0Ew7tDrMUvCd39958EVeWeKR14vG568Ci", + "77dVIfZZ8gYGtKDeBhYpY0QlEqX3yq1frBzLMCGHmizoynEVJStxsSIcFv+Wre4QDM7EnpkBK+BYZVlY", + "ZI0rzGqgpdOhrbBUDtJKqO/24uDFLoZ0wiiaLZYyp/mKKJkV2taQcwlQL6SeE1g1FSn5yUxtHRkNXVRL", + "luADlSmbMTG5jUJ4//87gNsOTmzgWAaO5YvhWDqTVehw2Z7y3YSg/9JW18CBEeo1gC4HJbEApTCkxapJ", + "jG8eR966xh6x5f5Uqk8DipScXzpIaankAJN0jwR2+Uhlh3pMnvW8bNR8aKlb0Cvtbfe5dOqukTAjrr9o", + "oAmbCh1n2T0T35A3thEe2ZvdoLEraWUVWzlbWIHcjYvQckEN5ZLCVfUSWGUHHRTklMxyKnTDswMbY7kY", + "WAde3JLlCROazjqX4jvbtsTAGbXZvW8++dojwH627MWaIZ+/fPb4yfEb8vU336RsmbPE8OzffHNvlyjG", + "qjNC+6Mnx/tPnp+u6RCcT4CDbN/ReISzjsajyrUaoaHW3f9UOgDHLDNNENIxBBb1qD/Cycyq8E2MHeFy", + "TwZKVxyFa4Jf8PPryKNYI5Fsnpm8lEPqack/vA2lurnbNKjUR74V60rboO9laqnlnr9ju0t9tvczwrzf", + "aF2H+37mmWY+/7XEp2FfupGtBmB2sM8M9pnBPjPYZwb7zGCf+TS1Hbch+Ht/p8E80dc8cRM+5MNbJLp4", + "mMEKMVghBivEYIUY6PIXQZc7lfAbka2ad2Vf4bmmlhkk50FyHiTnz0VyHiTPgcJ9IAoXSTgxiJ23KXZ2", + "6eLvSOjsR/sHifMLlDgHDPuFYNhbFyBcfNWmAoTLTjgIEIMAMQgQgwAxCBADeVuT9GoQIO5AgIg64Nyx", + "AOFo/yBBDBLEgGI/MxR7exIE8KWNdbu7IVJkK7RjQjY22loXvpa/7wvlUe6mFF47lHSueE0FvD63fxcJ", + "IyPl90qS2Sd5zWeWQhJrLw4ZJO8qg2SxYDlPIrgVP5CcLXOmzPUQKgjNL7gGR4NlzhKuDKji2idVxHF2", + "tvWP39A14Oxsgn/d+0eU4L/YK/T8gfk/Mud/oFQvU/bPnAr9JM9lHg+3wW6Ehv3AhwGjTbDGRhksFVAE", + "mvH0PPce84VwY7D0PMk4BktQqENwnjLBgYgVwkdgnbtXcW4foxsTXE9G45Fi+SXLz2EFZsfWO4Nnq/NC", + "0EvKkWLHXusRTd7SGTvKeRJ9mPCVLM1n9ASxDw4KOBuyywVZYis1IU9oMnf/dP4uivxeUKG5Xh2x3A0I", + "ADLGnHBmbEv1z4TrDPWhtRmdLgyY+ckRfsNONgjH5VFkQhYzvwqFPi6JgaUkkQsJUgLNsrInDP0EoV+R", + "r2f8kglC/TYU/wNmerA9Bn8W6pZkfvzbzva93TOxRTguxW3VrP+H78MNuuU9+uZvO9v/9bdH25OWbn+w", + "XMY6bmNHswos7wptpjxXmgSnJqQmyyJP5lSxtG0Os5fmDDs4ww5OUZ7slEMslQ2yqszYPsFkJzbFA5zi", + "QTkFLfnO7cmOnfHrWmTXmVjm7JLLQhGLpu4Ri46U4WLYlV9QU++5cMiwJ5m3GCqeR9EDnhQsnNOrK3G2", + "d+NRE+pvaw3+oJEuNNbw78j3jlR/c2RQfHZIeOsBBnMjvO7Jt9oDj55AjCSEKOgV1/N9uVhwDY48azAS", + "isBqyURKkrLXpwMDlqDv3er0ruKLeWcZX3CNzwSPgWqykAqzbVrMGazsmWUwaLlCLu52hXgv9TVmjLYv", + "EpcULHJ4Sr2f0sq8gIOCHUSLNFW/lxS6pGlALct0wUvKvR0HCaOrQnZXD+xHeUUWRTIngrFU2aQC4TLc", + "AhrVvZD1T1abVELCHob9iyzlcEpSPp0yECimuVzYHLbw71QmhTnLrxSEQhM3e3RpacFi2tNXTmG6xHsB", + "BVHBbjkTbJ3lE1JH/ZxBV5UyTTkmkdb0LUOybzgnAxxOH5QWbdcQq91v44F730oQGdy8k/Kjj+MHhrAD", + "blsApvbi8Ir8k+t4XacsX6x7YUEbG02O3I5m+QKlb3fl0vCaLkC/5XXhpUTwDdYeNB/daSRzqZjwo8N8", + "va5pcxDtJVrXMFJd39qyLC91t8DqQfkvv3EpkJGsHG+vra9JgQxXhnjIqsBDlJ4W7NzcWm+cjge9Br4O", + "hdI0JsI326yHr5wljGPZZKef/Cgg9ulfJrfH3u8u19xhXI1Qa1C9vQ1Bbtyx4MpSrAPIqg/2bQLhujj0", + "CF6MIO5gNd0gO4HFl0RgvaqIOtihQXYQI9U/2v5fBmH5hiw1Yuej7aq6K5rwpZLWZTy63prJLce+7Y5m", + "XM+Li0kiF/flkgkw2nFZ/n1/+XZ2fyFTNCFBZzsi/jgJiRzslstoin1MLYKCDiVK01yDFsLw0YbgN1+y", + "YVQiYIfj4ACu482ZjOazk61zhkutz/jgpjPW3iNsGlYRfZQZjRTeNb8qVyPXBjVlhmAbWFTFhW8bEygz", + "PhObFcTc810ixjf3zWC+KZ8VOYK0Y7iWGRXwLC54lnEx26cpE0lrFVYwShLbliTYuLktUigMAuMKZzgT", + "B/ZhzuUVkVPNhJflFKE5gzFZajsenrz4/rvtHZIGy11QPSm1abvkbHS08+xsRL5eSKHn2ere2Pz0EH76", + "vaC5Zrn7cedX8yMVoqBZtqqZgo92nlUgw04ZiGqPq9uNAenn7Hl1K9KNtVaPXp4cjOKCO3ZBvbaTYgH4", + "wtKwdiVfkj9YuPTWCNC0yal40zhxupWd7QffkmROc5polqtaeKP5Gq6rnCeyKjadskTzS/Y0itNtXReb", + "fIsvWHnM5s7IBUvkginih5kQYOeF1E7iYOm4bA+hnWlOp3dUi+SJW4clQ2msSnO47VO5+aZBBU4yKWYs", + "32TnvimY8qZccM2y1V0fhKGNbcewac2d0Evjbn1o2vZ1eBDbx1u2im1EsQXf6reb9w4PDrDXT2z1Bbor", + "/lgsqNgy9wIeVeBI05iRPGb6ijFBduDxPHj0XTue6nCcOeBqmVH01okd5XJOFWux1cNrgwbEMPw5TwzJ", + "zg2VoFkmrxQ4IszMjxQaf6VIDqpKmqeKyEuW46OnBleF3Ixh5GY5U4opiHjHSdQV18mcyCQpcoXuLxT1", + "zublgcTg2CTktMeECVWUwfGUGFYH8mEGc1kxGs1aBqlwkWRFChXt8xlTqC0slYe4GFAHq/6qk4yKozmU", + "9GrxUjvypxlzVFvm8hj8B/eBp9xAAVfrWOEd/hwxYf3fEGiNQDPaNbOZizrHTTZo6ujAcqXLXG7l6NbY", + "5HW72dPgFR+1jAK13Zl2hedhaX23bRnIk2r3KuOU5Czl+lzPmTi3QBBlpMo1kEWdlToTh6BSYfnC89qQ", + "t9MCIsZLkBkTzJyoctCm4NXiCpR/3es4+i0SWfNuOYxXazsDa/U9ANfvPD/B9AtkU7TkBuV+tWk4t3l4", + "u/j8NprYnUGKlnerCiHPZXAmlWaxU5mciVObuUIH4pEZEUxliVwspKhfWQhtJ9VPAGRQ0nSDN5VRcYJ9", + "4paoao1Ue3n7crEszL58tlVAXTU+yukDDCOhwBsBmDjyX4YTqvCQ5hvFrv9V/ULOiu3th4npcmX/JgEf", + "Bh3zZM4vWUruEy6ao5zKcAzTwew9LYy8GB82mDccpoPBcCf4JfikQ5ZinqI7YZ7LvMM5u2yJbkb9icgv", + "1TmAg6hxHW1b+KU+aYTGXLJceZnJIsmdOnj/go0qsE0ORZLDk2Jpk4MPrsYaqOPWArdSu4q1bmvg0ej8", + "aluCAN4Cg3jph/SCd0P74rGA53kid9qmj9pL05isaVCB/2wFzgurKaVKyYTb/EKWlUMuCdFjmm5JEdFV", + "uZl66qmgeZSp3TKXCLvojNjDAcZfSsThEK730dUzhlko2eHoo3nLViGCsSy35zLwcXiViHeKRMOD9Zeb", + "VDK99xrIdqUVq0EgVtJr50LS1+UXypuGUyWgyimd+qpaYeAmrd8fMEiJ3xb2V9ZLCsUYNBglpU964BpU", + "esPYg8QBRjE3448iLzfk44ER+DQYgZ7xdUiJ6s95U6KJcXVRYxmQQnw1GIiNNhXo4PLCtxDIwzT+QO1w", + "TUUVF5jjLla9+U4C10ryGl3QgDcHvNkbb0bMp+GDdC+i8x1uFm0Uf5vNeKMG+4245JwGyMT8I+rx4Jb2", + "GcQclTLAEGx0V8FG/oyP2TKjLjA7FoptWQKEL2KAAOkdeGvEfSwGvDrg1c3wahuItjE0HiwtA7MWLAev", + "lM/SK+UT9ez4FD0iBlvyYEsebMmDLXmwJQ+25C/EllxjGS0mRDG4y/Zk32obU7m5dH77svhnIoYPEvid", + "SuAdQvKHIeGRYKdPkbf10kNcfnK0zaF/pyAIpZFfW6SRNubwIBBYBlb7r81qm3e1b55VHP7CZ1eVHnvh", + "2WM7epg099gPuc6ghITIrjyA63LNbcjnmAHbnETVK/YTxL+za5pov6f1+c88+jo8+AhJC6OP0y/J1pO6", + "lffXsFWGHj/R2W2LSU93nCqTsfYeD8Wy0P0v07FowMrKCp9gXdiC5VZv/cs4Y7OL9kO9XbX4oH/8HPWP", + "nyY3NFD2QYk2KNEGJdqgRBuUaDdVom2qMzvxQR1d8RnUA79PyJHTKebwNByl+cOGSozGIx8E0aolOwmO", + "Zt8g2wg5wd+rOM/HhMSFlltmxl4B8vUcmbkcLmaqcbkuCdOcXrKQOdsTyVzm8bN1gEahjXubFZAhmHgP", + "cjVgpIvPKSkM+5PxPwxQJonM04DXr3N79mfBaM6UJjmzGlZGLthU5ixMkEEOp5hN0846rr6O6l1Ud+CW", + "VqiIW+n7Jdro5NbCVDru5YXgNbl7Tssn7PWMlgtbYDaNSeNuu1PEh0nhK3up30/pawNdbFnj6JaXNiFI", + "/9itmvzZkhjSTJ67lgbYEny3Wk7uihD2JHSNAwdA52LW04UJ+CUt3fuYN/gvQ0Vj76XSDN4FDsEr+WuR", + "Aa3qlWrMbiPjDF+Yv3ofYgg7p9g3coLwoUXexMscl67k9nYtxoN8eRjHNjkTT2Uess7hMeDB0CRhS/Mo", + "IJBFkZRBckwb41c5tspyJk3tPO7GgnUrcQvJTIvHEf4+kJmPT2aqe/Wt75KyOJ1Gmyf84YFPz2ZbTsiR", + "zZ7EuK90AlgjJ4cHE/IjVQQyb+GpoLCITT6CztSt+qc2vV6A73rucL2IPpDvgXwP5PsuybfTBPDFgqUc", + "c+ncFVEPFclGgHVTNmmyJ8VhqKZ124ZvMSotc02zU/mWiZjlNZFCFQuWkyW0I9o0hOIFNkBL5iSVTImv", + "NJEXbOUy5KMQ7oK7SEm+z8QJY7tkrvVS7d6/H+Q0VFouMz6bay7vqyVLdE6z+1ypgqn7Ow/+/m2EC8jk", + "FUufMc3yk6yYqXZN8pjwqU0AmaIGAuDMZWUitgCaI3R25Aq9+G0Ee1fn4Jdgjtnr71rygfaqvvnb8dP9", + "hw8f/vD6a3ckWspMTTjT04nMZ/fnepHdz6eJaXTP6vW15ROArBKcF2LDTvfvOI8zu14itP3Z1jaoFYaN", + "1Rew7Zgx9pOvOrd2V6pANLD7Z7ASx4Vs7cRTbkYRBXr9vGWQSAHeV850kZvXRm0spGUlyonk4hyRyvnh", + "njh4eLR89erB3oNX+feLH/5n+gf7Mfvnf76/Xuz/5+qfk9Wj37892dp79fvT4rvf/2dKn/6x/ce/f//2", + "yR8Pvj9WYvXL1b+m0/88+v362aVcv+8a0nSHEBVhcuazAj+lPGPpUS4vMrYIfcv6kZKXgl0bpNYcokmT", + "XwgwjCwM0x5kJcZc+NxpXbGS45zRlOWuvhozch21hQ+gPqClMUzpMpcLlu6ZRMlBS00eW4sHVjbdJdOM", + "6jEpBNdjs1LNWY7oMuWm24ILQxnMOAu6XFqam64EXfCk7YQO8DOuYDwyU7Q1fZpR7dqV+XFb8gQHtYYM", + "aWRw7/HGp/DVtTXba79OblfwzpOlFRT228VDfTceScF6AEa5l3Upj8M5u1uG+1jXtnLs67MuB6f57nUb", + "AAV5l9v8Gcs83qjeNtftSz45MOPinKaXYFOQOfwrzxnNa7WuXBtITe2axDXfZnxzONFAbqiwYgBkcib2", + "XLkQKLcCX/xxYHZny+ZwQRhN5tivGbPnL7c3ogjgIcqslwcVrMiVJbCLaDMpP430jWGBwkPaBviNdy7b", + "DHnTZb+M9I0ue3kqb6+ozMulQaJUpNau61UvvKwu5jlGW9UEAcLvCeWbIsvG/jcgkEsmtphIraTpdgnz", + "uZGbYX0Bzivvp/UJnt6sWAxgXYv6PLYce9Q97qgmYyZu2Jprqr6GNBQYgi/YnF5yGXlF3tYcJHxCCInX", + "vg0G5YrY3lb4ipiRn0CDoFe88O1G4rc/ioj5uGYkjxWj0ZLMqUgrq4IN1MyjKDeqFqN41EzpDtPuKA5A", + "4eIjzEBlhopPP6wabrN1ob4uUfUYWgAKvDmia4AvQbYq6p0/kKJoqt5GMDKwcc0Bkb1z5uG6dzx4gdiu", + "gQxRcKG/+zYaG6wKqK3YnOgEP3TOBJ1Z2nsyFEn7++Ib+FrmEhbYb4aujDeA2RbMIhR7BfVEN7epNm5w", + "8InbibshPJB41dgSzr1/cIQb8P5GlboRzlcJsx/Ck1tYQkbJlFFd5MCqGA7bYtYujthg2/MpY+scmA3d", + "fsoA8ys6Y+dgHlnX6aVp+hhavi+PWl/HOjYxtoSuC3iMaPZJeaLNKwk+llUT0HcLe4cX0nz3H8y1z0LB", + "JKwL41CeIyc3L/XiTmzjo0IfmUKhaIgwbV3gfOPQ0+RMPMWNYEdp6+l5hx0WmcPV11xBF6ducwKre1Dr", + "HoU7pDWwFYEZsEt0yXeu7zNsVu2rNNXt0qnregKtwp639bgii+r7zmKL6tczcoqdL9VhgAjGBMFkylgE", + "dVIjRqHWzmXwMFiSWiMlMDcsUlamj4913Qzq/IQ9uJ0JTMNfZBnhmiwYFcr8we26kHjZ+TcJZPps3ZzN", + "6zNS0gYZMg98l7h454ZsHj95KvMIbFg1YVk6yQ+BCMcXogZ1QLYKstWARgvFQazYHLK/wUINq+nB+tTi", + "qP5bjqHa+OZrnEAd/GLLt1TiJ7bye3g3HpW/xmHdcRi6Vu/ULgBQe6FuPQ7OUgLyNh4PNwTt/cVc+2+o", + "0HrF9TzUDK4pdNyKxcchnxVw2+YlTHNWDVAty8SOdra3QYER6CZDhaHfKehA3rXfntcl169O0+tNvexP", + "fZf4aWh6bW3IrUdSCMtpWSVTo0dwUqHrc7Ohz4StqpqpU9+yfxlihz3ryiUQd15X4zFNO2IrVfYqZ1kJ", + "zWw6XLdqxjpYreiGYkyuK4tnWc1uqYOrEznVP/MF1xXtFZhmIqV/lWv9XwbknDOEWT5kQCsUq9woVOS3", + "lfDDtRqScD2nhdIGKuZU7aHOAbSVNLuiK0UuGDFzVDzc5VRjde+oBgxs8XtTzfJjpljkyH6VBSxzllOh", + "bVV9Wmi5MNwpGEJpJsVM8bQheiDs2ldLVMIEzbkkV662LpoQ0avReqG4cAPUspbVpA099Yb9OcuNWGKX", + "5LW1aI9vX07gdeSHskXDz8TpnOpwwDm9ZITrrxTJZZaBw5l3IXT+HygHUXJFVzakyJwjmg5yc5ploCMe", + "hYulgBnQmAq/y5zPuCE8drfVrU7OxDOKUXvlkakimZdHACdqmGCzbowTYeTMYsmz0ZicGbJwbHey5382", + "FOXMUJD6J2d7pHi2cGh0UeOmXYlLn1l/O6jgJLjmNLML9OXHq9Uwm/B3lHOZ+5yCbXUADgLtDU6wtP3K", + "ytIWIcLnSV0h9v3Il9Q3VPNRtTqA34NZm9sBXC3eqpvs4+YPDHUS4BuZX7IXlyynM7ang8e8BjsBGUQo", + "xM7mrbnxwNIPmwYvOxwDGiMiAKOZORItyXZVYY0D+EHdOFEkVFepOIk/pj6GidvKnEIqF6FZfkl9leEY", + "TodIXHMuqs3xtkGY14THglaM2HW9tyaoKftvoDpDnUc3DUtajDnmAP918uI5WdIccn/WuIlwUAKxV1g9", + "wcjdmZKlhwgIRMmcJW/NqYZYmCLZAhuctpzJtMgArh1mBeUBF2xrlqMBznYqvbhl+AbGhBsSY4uAcEFW", + "ssiJvBK+gMOP1JdBDitPlNrrP8kZvmK8WXU22iW/ndnyvGej1+RdCAD/oz5yrHGXQtLqvPqWEbeg0AWO", + "/eyOlbfSYA+rau7Yy44omGNlC83XLYwliCmlUNTwsQbQ/I6UUF9qxPwdqpJUTOI5E0/bVElWYxRVKQ0a", + "okFDNGiIPlUNURObd3kS3Y6CqHrwg/JmrfKmTpI/pv6mDihxH8MQTlAGqbECt+iw+orr+b5cLLgGQ2pf", + "/9W6SnQjd9bmnL29W5tdezm71rvdmu9rQzXc1xW2uaLenrGbdu267k38Zht9o5DuDKOh+LrMWQK+NFHv", + "N9/F+VyholKUUi6kzxA2FLWuJbcxrF2+OW4gQwH2fg1+ODx5AYmhDgKIcEE6LbGxe0Ekh42NNUIXtRrO", + "vL6ZevTAxi5EvtAeztUSj1pusTfxqt7UoRugww3WFrjw5NlNOiE/siLnymlLF3SpyOHJC0jrxbUUIJga", + "hOzityHGyojRqOBybX3cptewuUXV7uzPTZdoJGaXbKwsQhUVbToJgT/nsYOQ6sp6vAmMbmtNzfeBH8MA", + "+O8D+FFYbQOZHrBxGO5GrOxuAjnh6Ot/7J6dpf8b/jMxf937x6/3/hH59Vn011fRXw/g19PIlx83GPvk", + "3j/u/SMWTX6j+3hi+LfmnWCjSsLAAP6AE2s/Vhhzc+QRRHa8SenqzZi8uWLsrfkv5CR8A8FEb1aM5m9C", + "1hOJzasnT34ajUfPXjw//XE0Hv36ZO84rhuqrvmXB7eCHYbH/QlTtbXEJY4yFvKSQSz7yZxPtWP6Iwqp", + "nCWNNNhEmU6oq6H2J7BxmFErkpNg15DCPGeXLQCrmA50SCDdtNI1sCrRnGLIcjNWwtU073TVpmbhPJk7", + "7QDTEHSubNT52MmZcDVCXmGOEmyY+ALHLh6/AP1yNY2J1/XrvBCJC0kEIwsXhWYkLSA5wFxekTlXWuYG", + "PNACQ0BdwhUxP996ypGaASyWEcNn5buyESWtNi8J6iqIzBxDi5ynzqgaKP2+UmUuWBfmcia2yFqjmmsV", + "mNOCZm7qSdRUljNNuWhLTtOySxSUXfY9RCsA1ja8SealGQ82WcIbppZpbGvNiJEdtvbomjdyBO8ir/6E", + "ivRCXu8tl5HQDPxG6HLpCs4VvtYcU2BMf7FkAtxHnGZGgVYaqrYul64IXemuIFZ6bsPU2bXhPmhmLU3K", + "bLZwrqiKTplVzpr5zsQly/l01TJl00g3FAz/6AXDP00LDY+bxnpp3T9wfgJH1w9i+8i40hslb3lG87dM", + "Q7Lxn23fOPeyKBsSOwv66EC0IBSLhFTb9n07e2GznP9gRLhNI4LyiVF7ZnhbLm0u1eZJnvhEqtoi6kQK", + "gVxd9B7b9eR0ufxKobacK2JJRsjuKfwp7pHy2ReOj1VTsDfYVoHdvVx/peN2r5aSPN92nYAh4/wXji/u", + "5MnGczyvA999a3nfWy4P7OXGOU3XkOwtl8Q0jagakFPtmbCs5G7jtK6kZipgdoHQAbhcMHCJhexzEbTY", + "VpTGDHJ4EMvnxq2TrHNdnmXyAt4ZSkMOWGAVthrzHadodCoTWPLGgATg1wY7wdCnvc2hUThCg/VL4Z1C", + "PkjioVOfHMg8FFuzJluRAjMklFkJwgxEVpCn4FooIY+jEVEzSUFa9LnIyYJyoZmgIoHUdzyZI2hk/C3L", + "VjbvGrvEtI/oRKvkghmunq6i2YpOZK6htGD8uiRUHfTqm/DW9k72R+PRwZOT/SidPlkykYZGuuYLNi0w", + "w59vZZP1hX43+NVqPxQk26UutYxVhgBJsd7cFL9DRnodVOuzvufNqGb8fntJT+rrh2iA2ur96spVBQXU", + "g/XakhV3u8J1JxxZZOXMW9QEOudLtnd0+BNbtajizEKwGdk7OoTMl9y0nJyJlzbMmhZ6bgSsxMeN6Eqn", + "5oUqluRM47yR1IL1zAdh69ft24gpO/YCWmBXZNBbxOG1ol3oYjUNdejG2YEQl9AlveAZx53/1nhfuCTw", + "XqFZUmAMu6bXkIkyYM9cDYiJ9SvBw1qyc9/tXNNrx6Xujvbdz2bsEqn41ubXd+OW5fiCE2UtJrhWgwNL", + "QKssw3Y59z3KpRzaAjL7wScfJQCfyi+tS7LxbOYhZBlLtCKy0EpTxE45u2SisMBne7iVBEpJl49rwfRc", + "ps2jxKHP3VzBaeIXclR+cQeKX/yHmFBmz9S7UrvyPytZQCZcO7jfYrALKKCDAPwMFm2AaGQanEvz7B6M", + "xvgvuuTnth6ZXTMOUCXO6LWS8UuGeX5sVRuq3rLUvcaRentuWpx/E/yPXiSj5shOdgUOagU/wENMwPP0", + "0LwTmiT6fOfBw28ffff3739orKYiK7Y/uneDInBQBA6KwE9PEViikvqZ/2y/jMFG4sI37ZgcSpilReJV", + "GZP2jKZhdrIKpooXfjYtHKvinM7V3ODbMqv298CCgqLpYQ3u1qaTHXQZX4bus0GrOjhfiq1sXYK1INJb", + "R+NpfBmpBGRxUKquUao2ry/ARTU80SkxHJvd5Ohk9yLH5b/IgfaxF/m/C5avBqFiECoGoWIQKgahYhAq", + "BqFiECoGoeLTFipquuV16uxKZMeSKnUl83SQVgZp5ZOUVgZvkQEZfgrI8A6QxqZOKDDO/pwlb2WhT5hS", + "XIp4Kn+7x1rbiX1+fmFMF8u4nRynWuvuYqeJebsEGgFVGQ0EmqRQ59eV/8VErPfxmPEW0rUOM6U+Y/CX", + "qZL/+rV1PCdvukca3DKYTbll5XyUxdcMHNc6tE2zoY9P+TJv5OITOaOOh1t9TY+jtTbbXhQxzSNuBZ/d", + "FdU9HW58flUN5qFmi4+NnwakMCCFmyIFLNdq6XQrIPvztFVblaXrZ6JWfjWViZrgMqAGK13y+66zrc54", + "33ZW9+2a4vkBbXxm7D6qVZ9cCQqchv9Ry1WFk97KSv9/tryk/fkcf92qrDdas7td27nvEsfqO10hznK7", + "YY+8d4X1u4Calp3yNK6MW6fmuss1BfJnUyWWyYRmUXpsxNrJmSDk/jffoB/o4ZPTpySjYlbQGSOa+lRN", + "OEjjvA1PiVILZKa80z3iNiJnj4HXL/MsJkRDFuKXxz/f5dJwAedFnt2crJQwraoIMYr2i9hmy1tsvI+J", + "+fnl8c8Gi+UM3YurD0hL678MxXAgP7QRPcB8cCb0nPHcuU9DwlJIIzrpp2lpnMC4gYErOpRQJVNerodk", + "3H474TkN06J1pjgzXEgp1NZpREshubRIXDKzPq9a02vz/7dMa1XBj/o6Sc93tvF/VcYGPp2dpX9+X+Fd", + "Tu2sa489aauTh7t9xS7mUr59chnNvWsp8hU2goztujV8tyULvenjc5ZrpySsaCS40A8fRJNMp1GJvBw3", + "jUadSFcZun4Ysr1aMu9cfwvP1Y3rvbGiPRF023yOEe7xpCw71nw0I3t8ay8/DMvovP/cNozG+Rx+jlXG", + "m+xTB3L+/HazYErZLBGNb0YiUEuasC9hqxElo9vb2AJn9BmUNeTXJajb87UsoPRW3EhMXd0IrXN+UYDI", + "cLEiXCtrYbQT2qS/7Jor7RKRJFIkbAmZaCCPCBezsAPUsXOqeyOBwCMHLfOVzN8SqghUEcx5Mgdp0cnV", + "btlv2QqClRyb9pwu2Ngrz8eE6aQ+n01YDsaclSzgt5yBt5GY2a0CvrJ+KD4buRkR8gYdHpCLQpMrKjTm", + "ycld3ha3LFuQZB7RrsvcL29yJp5CUXmlQY+QUMXUmNDwUsz9X9KM4VS05HgMYf5//s//6//9v/8Pcn5+", + "4O/5/HyXlNtVZEEFncHskPuE2+KBF8xs1oAHhW5jXEDV2yk85CYIcKE0o2m3C9mjFgEpcAGxzR5Gm5W3", + "akQ9x8w9R3X7ej809G5y20LZJrTYzIsLtZToqIM+OnGOFpRK/3r2Iku0+umX75teO4+2th984V47NvYQ", + "s089Eb0SYGKi7bRk12EIl0em9phjSYXwULd34f/1l6wraz3RNNd9VwulbG6+3p2brfeL8YgK32vTCamG", + "D9PAINh9uPWX3zCAvq8TVHTWD+ID1TMxOy59XD/Cjq0YWZljUevV0hV7qhAxoO1eQrYW1XL7Hm2mF1s8", + "3dp58HCtAdzbr49CtFd3lfN26s7jb8POLXdf8j9xhcT6p9/UfHeDR4MmrIXKL87RpM25BAjt2zYPETzM", + "l0vF8tvlUlluYBoYndWnyiB1szR3xbA0OZGBmt8dNf9UqOBAS75UWlLDwx2otsNpLvwKqFUQdk0TbZYY", + "fBBKQ1HHpn4Msj0+zWVL5mFXeqnyCuPu5u9tS8O1nMrulQTY667WkfGZcDXfevre+i4Rj0D3jVQsCh6Y", + "lhkVUIUIMsBi8bMNZg46Rfx+GVzaW7bawtSxS8pzSzBZSi5WCM62Rtu+z0G7kCmWv7xYAU2edHAclRX4", + "wiNtCVLNVQpzDRn/g6WuwpdNR+rMSwHsvt/dtq35cWXeGBDcpD5ZgB58U4WlDiEj7FxeETnVTARMCDAq", + "HFzhCmUGc3UAwhziC7CMP8FjULvkbHS08+xsRL6GBN/Z6t7Y/PQQfvq9oLlmuftx51fzIxVYvrSmAD3a", + "edZSZ2DdwXWUVPv8FSTJqv/727c99mXqcj/Zep+jlycHo3ieHewCdrIozJ+JV7ambs4uOYaumPNhhKYp", + "WRSZ5uUotkJbmIvHLWqd4aCS9Scw77a+vw9iHBhiy4bYsvWxZYPX/u0Vlsuo6H+MRxkVx2zKbDmLeDW5", + "jIo4NkEp9hjyeG9aGe6o1rGCbv8cMcin5zl6tH+b2XKq2TkULlONd2mLmsmtHFOLx3m0KkXvgNWjlpEw", + "OELbxPUubKDfti3NPal2r9KaJGcp1+d6zoQLYx/F8xC6QcAJoIX6bJHIeLv2R0WmuVwg62rIkyyU54Rc", + "dvkcnDszw0FCsCJkoHfIekG5CCrNYywlTJGGc0uRrXbRHrnRxDMmWI7+hCJ1y5iQ57JMCVBtFrvkUFwO", + "CgSaEcHWl8jFQor6cXZBxkm16U0i/EJhrzXUz+pMgnC/OjlvxFP8JYPnAsk3iJ9LKh5gjo2KlFOsijmN", + "x71Okt9L0xhXsFeV22mabkkxJjmD0hWYOkIkOdPMy/RwzdS1tXpUqF/RuPhPRvRfa0H5SKqA9euKX9sR", + "zTUHjdpSLiE1Seruozzz5g2sdx7GQT5c5EGc1XKg5qqQ99RMmLM6DLt2xIKZ6wxrpZYbb+UKKyN/KtWQ", + "21bbUh35kuVlyIGl5TuxQ7IN3fHsIXDZakO2xLYKkh9YZZ/NEwuDti3tF7uGpptjDKtikdlL36cCG2HU", + "BryUCBYcsp4MkukgmQ6SaS/J9PeCgiU4Tifd1xrRIHvZFV0pArVUieJilgVUBhupCtDsBJhyu1zdv93s", + "MQ9wN3kMGTyVucXNS8kFelLyBcZk+UUblGDOM7uE0K0GKkC/u0frjZdt0PnvcoWxkBRb9VvFz9aX81ZN", + "ksw1W0C3vsIKEANXZhzjYeJLPvazlkumeU5Bkxmysz1iVD6oErNV6gvXHK+LwBcs44K11xU0X+sgjoUD", + "dZELllrhF8VaJXMn+iZSaC4KWVSB/bcq619x8QxArWTByxYPKi3Kx7nzbtw26IO1gz5sGXS7fdCHret4", + "fVPoPLUHfcJmaMdrv1PXNAKigyRNLd/3e4h8fg8QaXl4tfccoqRe4jOGjfYUop1f+oVMVxFZOC7XnfoX", + "V3q2f9Ji3Lq77MOgD0l6BqbqYzFVmi82yhcY4oRT7BtXMuDAbk8+UdWE7LmIUocgZG5R8JhQItgVYULn", + "K8wUccF8wKANjnHoLLS+uoXEEwxVcSGm70L00wvpeS4qgvY8z2a1gBE0GEF9UPKVpRVORbPFYRtneHgQ", + "1SwToLtBEsZyNdV0Pp4+f+5BbK0OMfZEm8djzi7CNeTBnfYsJO556Si0+6MPwdLz1g3I9POPO6GhF3zW", + "+aie1LklgndwT7sd9O1pDRoGUGDowtbrZMr12sIKV+jX3AuG1uYbrKPqIfPgwNQMTM2HYmq6H3DoPNvm", + "CJsyTXmmbNgtS8sqbs7Bv2rXb75n890AnXpWKA0D93HrfmVL8tMsI4/tCJZvMbDpqKoii0JpAn7Ak7Ny", + "S2TBqECHgKOcJ+wrRR5X7MJBP4CoCwkFB1zGfOHr7rfV1veBEjAnS+3wGDaxgaMMtm8r8xc9YgJJpudU", + "EfQU5jEWT+HmnG8FoPjJeqB4TNNjTMzyJM9l3p7XISiVmaAzsswRSm3qtoQpFauTqeSC6bnPAs7B2pIw", + "jrpVqIJJkoybfTOzBPI1m8wmY7KgmaG6LPUDqpXQ9HpMuLikGS9/tykLyDSn5iWMzcpSlrClOQPfKpeF", + "5mJ2b0J+oTmnPgId9v3kWjMByXqIWrKET3kCa687F9VJl3ksPaJQ2PUyowJhLRwfuHGZWG8Gr0pcYuHS", + "KndyGhzthUxXCNFwfP86efE8qDnSwMDM7+5mqK52RN0Urjyi2lb9vtCcvKBQAtW6T0xCa3bsRF8eH5Lc", + "+bZZUHIyBsKdn63ngRa52LUHugvJge6XMSJbkFZnJ+T8ipx35wJvvpcfT0+PnMcPeBSXnk3Wv1/mfMaF", + "e1hIoXuDxLfb29WMODvfIdFGIvjohx8CkgiNYxRQZ9HzpkTNZa4bcUyqWCyg5O20caXV431MU2JRS3fu", + "QecoRy9koXcvMireNh3kDMQkUmjKhSIUoCEGA+3LqY7efavx7IV4VGP36gNwXcc678+pmEVOGX+vqQPM", + "sqVgPd09I9O8G6/zi1daLmIdX0fX7WjCY5muopw/fEWcBMxaSJcSGCKSAApJ3c3w0RryWVnABZvK3OZc", + "9GupeuNXewBTza5vuLQn10sqUtZG4Q2DZxBC1L2zzKEWWeppU6lTMonQ2pDTZgyxPWe7p7WQKsU040kf", + "ZsDRokQWWUpsdJLP+lZWyU7skE1OsnIQmuYzpkvh5EwMZHog0wOZHsj0hyPTLVbLfZs367bINE5zAzJt", + "O9bJ9JOU6zXxxyzl2lZrj5BiTExcxrdWB3pMdTJ3Eh6GTywWVKQKHsKCCg6OtVAorxAQP1APszSv7C1b", + "2YBJIwO+ub+cU8XU/T/hvz+x1bs3Rm6L/H4f1AD3/zT/gXY3cnQxh/TC6WGw2NP1IQ6yE7w5r/m/E9WQ", + "03LoIETVxkeoOdBRCCwEnTlLJzhOLfDFENUsk1den4fUXwH2pm8ZYWAoIFSTlE8BE2tMojmJcAeVq1/3", + "QKpnGMWlpboXZfsly60UL0XU+Sfl5p8LLqjGoOQFXS7dyafpOYcE9vEzN+upqagh3z2Y7c4BgDboegTt", + "zQEt5CXbaOJj6GLntv03mh4HcCtQOmc6mW82xAl2cmMUwjRMi4ydM8AP/UZ56bsBVikzm7icKnJpfuyH", + "+druZx3q6zjeTbv6e73ZnDfrW7mKTTvXb2Dto6xxfY1nCQ1IyVx6xFGhENAqwjyDqo36idCtpg/yra6r", + "5CUciq2hosY8a/ftJK3mhu2Xqlg3GDDvJL9G3MLQlWtjcxPDkIFjyMAxZOAYMnAMGTiGOKchzmmIc/qg", + "GThAHRFHD/itDTNsrKIAeaE0IDR1EkM2kCEbyJANZMgGMmQDubVsIB7Br1M3xAtpQhhSoguagdkD8oDY", + "2ww7j8kVOt8zzKM8Y1qVv63Ikq6wmsZkcLTus46bCKBuRd4B/0y8Mu/EsC3j6ifMhC0FLoAsizyZ2zKz", + "MXmwjfH5wuXBQRS5S1Ek5SqRhdAbkJ0D3yVObfyQnuZbg380KCUYbTyaMqqLnLXWjrffv4KiReRrPnUO", + "A/duK33LFyurcZFkhdVjb85eQASQG6F57QhkF0whsaEJeOlyRWaUC5aSS04bxMraWeJpeyAtUHm49iU4", + "92ysBlUZyQdEkYQKchH0xjrPc2pwrXcZ2T0TZ2JnQg6nhJKnCFWAjpWSCQc20KuL61PBeIYX9DM4Ja4d", + "yIy8Qw61WwoV5PCgnHuMwXkuT3ctsY9bzNf2DwWjJNaFL8mlUq6LumdmehDORH5iq3AmzEFBMcgBflfu", + "NULCIE2+RmJLZE64wL/vhWui5a7OxIPmiQmpNzo1vzh/auBJb0Z/xYiiK3I2amszIjmb0TzNDHTJKShz", + "KQFJjnCtWDatzgBzJjLL5O8FZuda0LdMEcWEQqdxmG5JV+g3buY3hBgG9GIAhbwdXMzORhNyKMjSoF0O", + "bkdcBQb1lOXgbQ5SiXkHXykzlNClVdpKHCTjgm0Zwf3O0Nagmrk91YwBh80jM18qOmOPqWIpAG+bZgRg", + "bT3TaCmfeaaK5Zcc5eRpzlitRgJdGGo62h3t2HqtUKH9lOULcPU6p3nOaB4EoU4zqqNlFLwKA1Y/Humw", + "ZG2/syir3LbEL5VlbiPiDDF4wx1FIVIw4aRj68dZ7xmcUCiiNxuCMoorqJg+aRSuxdUOQrBL9NaQdPE5", + "9JFjDwOWo3qC7kspzUL9xycCdmcAduzu0ZKapsDKysb9ATKYoQUkg2HbYTLgVfvPbXfSMq8D30rBa67c", + "eoCJLhRrOle5day7kSM648LcdLu/tW/i6+k2U53EY/eBX4MwOlcz1NXpoehfvrGWOqqYprMWKdx8IVyk", + "7LoerNl0cjVtT/gfLSNZh1kiisUFcp64ryXL/WbK8VvcaKWm2T7i4WhOJ/O9PkNl4EexgeuOqOUs9miC", + "vbkTXwsV6PvV6dUJqqsxoYJmciYL4CABiaJOa3NdEqg7LJvkqq7CWMCC25jCD6hRKoTmWbCWoztdy6CM", + "GZQxH0EZY0UQLDbUon/5UpQdLamAIa4jW5EPlw14kMvuTi77S3LoyJQHBLYXgW8LOWmSeZcvoiWIoxNv", + "Ar5posylM2p8evjOW1fiDK2RTVIIMrT2f7sjwa7srs7EgfsGmie8zBLk8Ex9/oILZlVvSpfH0scX0K8+", + "+OnWkJ5fyZ1gvDgiAR9UKKW/DkjA4Aj5TGJypGb5Jc2CkNZK8Cr0RY1nToXiLmKknLGhaMEbsx35YsFS", + "TjXLVt1T1O/x1w1teFAQFadYiyaCA3H4AM64FybY0J0dj2Ng8AcGf2DwBwb/E7JmarZwiQZVR6XhzfVO", + "zixZ1z1FFZgKEkk5c5wDIVQYSUEYTebkLVuNCVpfIdwhyyBMVo2JC8BKXWxl4JzTwORrFW8VQkrQ7Ssv", + "Emenm2bmXoTLhmTuCLTdMl84iniUUUH2jg5tJK1LAob+cWV/miQyh73YflOZZfIKA3MzpnbPxFYZNer0", + "gKhDMj+9gfW+KQO4wadPo4sTv8T9wADu/NyAS883qXVDAYvVOtC0gGPpNxR4LNbNtI2hb6LjbIO1QXwd", + "xNe/iPjqXk0dpa9jZk9aEm2c1HhzbWsfiGJR5iSFbA3+z4SKhGXMrN5j5GD+8sYisfc90iHYHI3Welle", + "p4untw4EQUz95Ewc+nwal9zayQI3dOt2YaOOgiDCii8oFTbT3ZUPZMJyEf1zSjR3/MQc5Ltxfdu/HT/d", + "f/jw4Q+vv55rvVS79+9rKTM14UxPJzKf3Z/rRXY/nyam0T0bTwf5exwkEjxnwgV5ebp/qxz56+jdwU56", + "358TFL1EOA6TEJYkvJIbIRAfvaDJrrVLGblKsl7DWJde07V0NzWdQ8j2c9kcTOe25Tm0jMLzKb1+zOb0", + "kkeDROk1ubBfJ2fC+r+b2ZztHBxoIMvOykA1Zpyg1+i/b+271hpovRxywq7th8B1nyfVjZi+Cp8mNIe/", + "W9ZfOiREg27t+8mD3EPeyB+xW10Ep9HbwcEfYYQ/r5/h4RQfLq7GHGGYoSOXU56x8HhTplm+4IJ5n4dg", + "uMZg9rBr441DTJJ/pbxnhBuqzRfCn4aPYDwE96WN8pXsVzvWHUK6s7ViZ+s1BQynv71qqGVrM1Qg5XyT", + "soUn0H6zlWKflvU1PnpvmpRFQ0KhYcpKTzYAHsAfkFD2je/8BliUN7jFien0Brh1RzjGlbYavN/MTlhq", + "vSAR+3h3O+2mZpgt2cFicxbzymdC5nX24y6LU/qDiQmFsRS0p5zlzv8qwmWZjyUCquKCxUYxWcFEQTRW", + "1UUWA9BtVl3NGZA7iLriilzKrFiwrQsKkcY5meU0LQy8gTR1KMgbbPHGNrH98XE7n4WyshjXcy4IdXFQ", + "Ho/YvFgsN0KEtnt3M/g535TDmxYYXFA6oapqGbNZLq9UCO/PbDyTGUS1KQhZ7kVWHV7EmdjTJGOG+ZTC", + "UQ5/4hUtO7cStunf28cE7shcF4gzXLjkTGGia5bHijSUOcoauwnqlrpdnIkXULRrFyTnMZw3OjXBbkOK", + "h79ESFw889gCA4rwdF93Q72LLIz4uQThfrr2EtzCEORG45GHjDgdLud7xfV8Xy4WXC+YVXO1Pzp0FlZL", + "BqXKfKfIW0T43ls4l5p+j/J5sWA5T1rTeJZOVhlfcO05GpEalgvi+kArAdNWANy+N+tr+c4n1ru7FeL5", + "1NeI76RlkbikcJEDShtQ2ueJ0l7+fHjwAtI85YJmNj6IipWF48+8kFDTFOf3iTGCmZSK5aEO8i1b9VBF", + "1eTg8e0eFLH5vsxSnVLSrut6aya3GoTipaCFnsuc/2EQC+TmDJ1R++Gll4JdL6FEUX2IllJINkvunCpr", + "g2fCR6ZdsIQWihGuSUaTt1D6gKfELNNsM0F9S5Iz2DXNyqxm9UTCMSVk+1LbLRYNU8MesZ3Jgc1ohROQ", + "r4+f7pO/f7/993sGw7x/yt0vJJ9x32O9jQML4i6knrN8T+ucXxQawMD88AvNCoPZmuntfvtzlGBGivLb", + "OejrzLPGUhOj3dEv/iMq81Cb1bQODbmSh1zJX0Ku5CrpgFpeaoLKfosGwyZbfLGUOTDcS2qI3mjG9by4", + "mCRycV8umVgYLpHL8u/7y7ez+zgsrPal4LpFP/CyZCebDjC3yujjaA4wAjZ2Ux4t4MDMKL35L7udKOfl", + "DmitaFeeV2/B7gMe4yBD3ooM+ZGh8ZcqHW2upE4vlVWFognOoB+Wxtx+uFJF7J07gn5r6UADvqMcPJqG", + "J2nX3dBkzoVhmCxpiWwIdl9F5Lag1bmNGDtHY2zD/lunN1POsrQt7ErPvReIaVajHGkqhbq/zOV9Q7uh", + "rP99Ld8ycT/I9NBjCZ4fii0CyOymZ2EkgaksROoD7y5WpNeB1MPv4HTsbZUr7QG8EZmgzkrUyqYhXqWk", + "zk2WWZe/FC6+9VHDO73N/NF1jBJPIB2FiIH9HtjvL69USfkgDs1b63qN0IAkdImJSqhYBajJPlWSs4zq", + "MgmQTYGB5nBsgdwiu2Q51ytyNkpyrnlCs7MRuq4scygOXcmgAf4DFww8RswokQqhcfr5zNJOLuwFAHAA", + "kDvVDgw4JnxK6CXl4Ho26UOlPHaJ1Hbx2t6cGYnF5RvxbMf6wQen8o/uVN7BCcEnV/ve3itq9h30VwGK", + "cIEkEVgom1+8DxzEPLjLtNHJnOYz8LRxfuEfwXO7N/fW4EG6GPMe09yNbyrkqLjWVfQQ5dgdDuu/ghou", + "PXEDtOTxdDiy+2y+ROfSNodScDr15x7i4L68ePXg11E719CC6oVj4YKboQ0ieCfEzonWboDReHRFc2EO", + "L2ak/0XyFN2w2F7SVYbMNjLtsWGw1bm8MnR8TkWaoU/apQT/1AxIqktj0QwWkxsklA5W+jMX1dW2KH4S", + "H9hH3zIXCBOu6d14BOWghbaIqHcZbdenOfOP8oosimTubb6Q1aOc1ZamwhP6B9abJjvb2//LVhGnWWbx", + "NUZYYMN7DdAPFj52hxkF6fgNxzPKfsq3jGERw033v+lDsSx0rGguiuJawpSEClImA7+167vxA41A1bvx", + "SF6yPOdpLBn+EcvL1sQ39JQZp4l62togH2zxxrvEBxlKzSVVAbyf/qB+EAaaX9ilRfOq1XwwckZVWwQ6", + "foP9mcPyUoOVodZSTXurfpJewFTZQJMeVt+ta9iKPmip3iivjlfTIQIXYjc4uSvQvDlWAbA0/2qr31Ju", + "7PDAjOIg84N7ktSu3665Ly5pUNt1l7+Gctzk6rvqNJpvNE97UpQDbL3nnsCSiRQG6tX7CFtXcVujSiGc", + "Zu86hZ0LXFe/r8/6NrzfOGfwl75jF5H5Kd+zR2T97vo0arFrbbqWD+Qhya5ddSiXuJssb2WNWNI8q3Wr", + "rrR+74VXqU67oXMttWieQT/LZ48rjT37dadU6XPLpyTYtXa0VnfkAqE6yL5RDl8mT3YVXwidUV5h4cpQ", + "lmrfMqpxy3cW8uqWc3ncChi0P4DbA4NeyHwAhc8fFF5xkcqreALTvdksZzPUPF1BO6L4HxW0/Ozw+cvT", + "J6Px6McXL49H49HB3q+j8ejZi+enPzYXNR5db5mOW5c0F3RhLvq30TMuCggz/VEWuRmBrswIUuj56LVf", + "IEsfYz2nH7nSMm/J8X9l2/riT3NsHYnNLHLTVLQO98+cCk1cs3CgXnIcdH9c5OKgnOSEzTBTcFNqcwu/", + "2e4gPEFjigmMylYkl1coyWIvZdgmzAeco1a2UHSGkQ3l2KhP8CGzNlSY57ZMDxUp8TG05UcmUj8O6Hot", + "rFgHV7WgWQa5rihCcgBKMKSL8HWjQlAiE+n/x965L7dxKwn/VVD8div2txRJyXHOsapSp2T5Eh1f5Fh2", + "cpIonw3OgCSOhpgJgJE88foZ9v/9ax9jn2dfYF/hK3QDwxlyeJMoWZeuSsUiObhjgF83uhurS831uYEz", + "ZundzdN93p6ZFLPvC2jlo1xLWxy5snEyvUm15cm79ESovdyOms7rlMnHQrMMnmRgtNLxEQIACR8LrqvB", + "ukbWZq0vX8AYYJA2xRwS6pWwaInFWZSkecwUh4AnMLIMbRXVMAR492FYJgn33hzgnfyGFWnulhuphsJY", + "Bhpj02Z/5EIXmA/m2cYbyuCq4VLFD6OUyEh4oxMMldHay3g0Emyn02u1W7lOfJt2u92zs7MOh1/Bld8n", + "Nd2XB/tPXx893drp9DojO04qx/KtWq1b7ZZ3XWjttrY7vU4PYDoTimeytdt6AF+BEDyC8enyTHZPt7to", + "QOS+GYqGPeWlNBb0NjyOt/xNfG7NQHW9EyISaeweZuKy1xw6xzQ4jfiIPuGEMWTptr0QDBu2Igjrv8s+", + "/s37uD/B57+3OhcfYcPJEjh4HvDECDcbWrstGJgQHWO3VU8aZhWvWRX45H529dM0ERyvDbQF9LDbtBp8", + "R57JxPV6v2DQeR0ZT+zMWnOqU6/CnEhDN86rZmbNXrPnTkSxtOvQYmxp3+3BfUXw4ns/GR/tAk1BJg7/", + "3iqkgLtqLjmWzya6R8X+U3BNqhhMzu2xn/xaUO24pfG7GiyAGp3ZKqQUGhQLkR2Gb2fW5ckeXL7z5SU2", + "Q3kqyjAyk7ff7Z0f/4Zff49xZD7uhkzKuFE+9FVShLhWPvta6ljzgW1IDN83puA6GslTETckCj+FdHOG", + "oLzdsGHeLjRsdSMdLpq88PwpL89e9o5Vrl1cs8L1i8FXqHFTZpNdo+vvR5Cp6kC8/fWTALavkAy6+lDH", + "Qj8u4B+php3U/XGx1I/RtCDsaNCDO70emkvBVRzwMmZZ4n3fuv/0hxOTrl86RWZvmgAuWuyaZ/IoEiIW", + "MWjbv11YJ28s92/r1W1iTDvjONhcPW/cGHHlhM8QSMkLonDDWSV2D4tzvFIqHQu4Lapc2+FUD15LPCZ0", + "8CeFsj46E5wWttmYJ24awt0bmKEplOWf2sybbZffe7MGNtB8DA7NqWaxiEQGi0x4Sqe5lWp433fn9sa7", + "c5Ez5wrjfZmumNDiBxtv8bNU92UcC7Xe/MlVLLSxaRrX5ks/d1Ue5EbA+XHZmUxabMH2zsZb8EaLKFW4", + "0z4DX4gVmgJO35qNUw2WrJja+L1RqlqjRoLHQqM1nGHilCd5MP4EoPUGRxjryutJsJugzQ8v4bWHGNGK", + "J0dQTKPl/eLxEwoM6cChnyuWl069k97Ad92b7ojYzWGw2RnkycBHY6r0km/q5ifoEQqO71VpZrheS6Wp", + "QEsO16dPqQWnFjvOrBhnqQa76lOhk5RDqIdJZNMxhyjqvHIbIayiiTwRCWgbeJKIU7w8EENsuxXUiWG8", + "6KDxaHmj+4bXr7l+5LOdtFcbd1y4S7EQtQxoXl5KpSWBWT4EtdkbncZ5ZNk+tzxJh6Aqy1LTZCyMIfg5", + "xJnHjGYlWzSIg/22hWoSYezjNC42u5eHo8W6LsZbGU5hxPZmi16LGlAUgR4rTRndA7DFeONB5u8ANXli", + "iTKIMogyiDKIMogybiRlBEgIWquFpPGlPaVS736Gfw/iL4gfiWi8HigdWK8Q96WwfsFk7GNBRW6X8d9L", + "U2rOpQ2bWV/AslS67NQJBn8IBDOlnAdFEMR0KPVAvsataRCpqoWu1tpuVpPybeNBYLgpO1x3Cju4UPHE", + "b9LP+Das1+4VwCXOhCO53IhBnnQYUQtRC1FL61t80TbagtepfZbmatXxqjtAxzKGURtIEEPCrRda+GBR", + "OEBzBoVhDGaX/izs4yk48CWp8S7jqRJMfJLGGsI2wjbCtpuKbU+qNLVEO9Ro8/Bc2BqLuR49EUXHG/O4", + "t4dleT+RZiTiMmIkIAbe/sDkgMFdPrXA73U0Gwq7WS678AH2v18A1OaFo2z8dp5diO/aqWuAAv0qY4Wb", + "3fht2esqHP0ay22z/chLyPc85iOY8kLWI5d+FEgnf0S3RLdEt0S3RLdEt7eebidwuuzgs8ld3ccDqWka", + "Z9AUg3/ceK3hJR3XvhVZwiOBPbnaqS0RHxEfER8RHxEfER8RHxHfesRXY7bznkF3veMCxPFvNInbwwcm", + "581exTbLhz6r23WsTIxGjEaMRoxGjEaMRoxGjLYeo5XwVEOnc8OaP12eD2tv8IEVYM1nRbBGsEawRrBG", + "sEawRrBGsHaXYa2Ep/U0alm2LExSls2Lj+TSzsDXFYXCuFR8yjIKRUE0RTRFTqIEEwQTdzYUBe7vgSNg", + "u5+Bhy5eFOzj50o17H72oXQP4i9diEbWNYWKRjpVbpmtan+mDuCybB/yOghZPXGpj6qJV1H1lMXfftOt", + "Zf0VbqNcyZ6LXFCJiYiJiImIiYiJiIlmmego74+l9QFWJ0iD6xcGh5rCpV2GGzQrd+h1+Ukak7vvzktQ", + "B5ieGGplhnomFU+InYidiJ2InYidiJ2InTbHTh5nroqeMl6MhbJdH7d+DW5C6/Q3mP4ohL0nbprPTQ09", + "RgRFBEUERQRFBEUERQS1GX85jzSsvIpnXWD6LBeHbn2vpDIW7kaDVbQhkEJ4Yi/LVoMiCr1K5EHkQZbV", + "ZFlN6EXoReh109BrgkRAPFMGUQvirUKkzyaGGgp7S+hpo1bXZGRNYEVgRWBFYEVgRWB1N6J+NiPVwjif", + "8xRTGOHzxnLVJYT2zLKvG9iTkI6QjpCOkI6QjpCOkO4OhfVsorqmo8iuQ6BMuO+3TgSQT4l+mRaR65oA", + "Z40w6AbmCPJge28O4EajY3Ws/uc//+t///s/2IcPT8psPnzYZe+NYL99fPP+HZupycff7/0fy4f4RZbb", + "mQfuh9t65pEnVmPvzcELURCChtey0ikHyo0tmYMRaBJokjkYcRZxFnHWxTirTj7T5mD46xLyOhP9UZqe", + "zI/K+QOODD7O/OO4MDbHhuJZhiX/7LMmFqqykO+Vp+41vmqFXK0GFNqKyInIiVR0pKIjdCR0vO3oKKJc", + "S1s4/nJ8U/HNrIHdKgzZxznjnS8B6hZFEA2PwRBoGQvDchPmnMlEJAduhxnIxAEiqO9wO8L644D4u6sh", + "zUyGbjPKhWFc4SI+Fnro9iw/tzOdDmQSnoICDvDCbZ/rXpLsh7a4WWYEqJYAQuG5BNqRKsulMm5KlHUw", + "HfZuJA0bp7Fg0hwr1DDBQjsU1oZ2hvVYDAYCr/YOtTtL9ckgSc9cqe5xj9ZJwnLj6qPFkOs4EcYcKwnV", + "LtiIn1a7QZcdm2q3iDfHa32MBb7B3ggNPgxp1w7lWs/PDfVMnm/c06bTrz25SszX1fMuB+JnaUdpbt9I", + "peCd2XxRDbPlctpyEF9Ovq+drHUpOb8QxeVk/EZLt049HXOZbLYE8Snj6hwdPZ3foY6FflzAP1INO6n7", + "45KyfVycI2DytYyxvLjx7l1+IiyXiaFIzCSukrhKin6S1khau6uRmGclqIqY5nfSJSJa9/MELhc6gD+B", + "70GDNC1l9YvJlzL2gpo0OAZajNPTefJZEMzKXyBJXzCT9/8pIpS2Rm6gYHiO1ZTo9o2ZSEd8yGXDlWDY", + "nsVYsdJJRAXCyW2dwInAifT8pOcnciRyJHK8UeQ4H+Qa4XGBG/vKLHg1SvvZnPySNnCLarsKkmyWI0Op", + "2lXW5lqJ2Kvw+2LET2WqjxVPkvTM1HT4PNQv1GuilmfpvHrBMiqU2wwbIgDcVlZt+6r+kQtdTOrq9a3V", + "ekkrxuZimsKnQYsbqsG15oX7bGwBTXY8d010maS6JAInAicCJwInAicCvxvxDVbG78aQB+8auTLiyqvq", + "4IXKpGLcv4blwzAoU/h7rGI5GAhYrmBaVlE5VWKi0p0qwb2n8DCarzjineQ0VYgD6YFbIsb8xM/38bGa", + "KgksVcCKZZJPsyGMZ1f82718mZZGVOxvGrzxjND2VmuCN2+bvri79rX4CuEjiKuJq4mriauJq4mriauJ", + "qwNXI40wzpQ4c52R+6ATK6L2ymYSXX+dj+lmQsVSDbcSqYSZ7ypZq5hPw1waJq0Ys3vRyC1a96uYnSRu", + "UgTOjhZnENa+ieZ9wAKOYaJjNeR2BBajzNe+tLXAzFFXvwclzHmCycHusdpyRZX2BOFRqdikBGO5Ff5J", + "P7GjIqjDJ9WOU2HUN5aNuY1GM89yVYTcTUP2M3iPlXyDnYNXHYiXUhHSz67L0De+p1wX4fxcIwzH9qVX", + "5lxWvXBmhC9Juf+7B4D3wiTmhnF/sxghPyE/IT8RLxEvEe9NJt4ZIjSbAlwjx3nC0R64mW2P/BNuvgYY", + "BEfFkkansBbGxCxNxfrcTF7c2RaWpiWTTNFuA9fp1PKE8bF7mwJ4hnKCYckkL3ynAu1665Q4LDg+3axC", + "OTTCMwyBZjPb+Rniem11wuxtuhakCyYwJDAkMCQwJDC8AxerL+WrVQkxoODiWB6loq5GbfODeKDRJ0sz", + "XFDrVgXBPJjHOLN5wqRyGxMuv/f6wkBQiyrU+Zce2M6xn7l/rMp1wfcRe1axG+gXkL9/K7A+34MeN9Sq", + "mj3+MI8QyxJc855PK1p9Op6c8cIwM0rPapE/cthII55EMGJl5w2Sojlex0EYkXUDc5RKUWN9rAO8Llas", + "FK5iNrX4ZIWKRXx0oVykMbmI99xrd5EMHoNxyflyyISWqWuGtheoRyWXi1TG6ykvUBGfw0UqsXoQjIbi", + "1wmC0jCc+HKhm0J8lXEtVq7tuUN7LEr/uLhca/Sgaae4GSQYkWBEghEJRiQY3dG4GXJC0GvJQOGPFS09", + "SsErmFTP1WJLkAvyxC20LFVJAVptsLiAhRR6XQtuUsXOBFMiCEpeo12xcMmtE46Czls5qSkpTbGjIkpQ", + "Svl5FI7EwYuxlBLbcypayj5jrk/wFN2niEuF+jyzkTNpR3O18qGoSXe8brJxMTO5hg0GsZv1hT1zO5ZK", + "z+7dL6ukxCdbb/03hvXFUCr3BZgHgVisCgaIBsuDGNcPF5x46s8WxnlipRMfJ5Ypg3k9xjWYxUwM2b11", + "ixQNxulyxg7C7EUwqa7KCMSXd2lWICs5dZbK+mm/TbICIaYlpiWmJaYlpiWmrTPtwSwGLjGeWBt8P/u/", + "VgwSV+Kk46hDx7MlL8HE9WgEzn+aDyy7l2omuE6k0PcZaqXDqQCWhebJBzO5OAxnA6l4Iv/k5WECIHRf", + "sNNUgtKqOSjcOnYbZfsp+BuREpESuciRixyhIqEioeLNDP5WAtraMd8m9iT9gh08uXyTh6GwNx3UVo98", + "Vk6o31roU/h7ey3F2aphz9quC7IkjUVrFxa/dmMN62fxoCVsrq7PwxfaT9NEcHW10dbIzpeAloCWgJaA", + "loCWgPZOxVJbRrONIdT8VdmLdJVSefXkRDs5pZzEEBNxU7CxmN8SDeOlHT6/FVnCI4EDQW5hhIuEi4SL", + "hIuEi4SLhIuXg4sz0HeRk/Auj09d5803B93DB6rWkd8YjF8VrjYDC0WEyrrVYYiOdez6U4c71AKrttpu", + "IsM5t69F3R9uNvdgqWg1VwbfjLNgcspzm465lVFZBR5VPfO8NSouEDNtyY2Pt/qNT2ZwkQk3Y0OS45av", + "53HLPzULzf4Jj2al/eNtOZ0neCV4JXgleCV4JXgleCV4XRde16PJi5EtIucCsvVMWrEH4Cp2RWvLxCcR", + "wS6J5qe8GFfvcZgOc6uM5TAxjFBxI8WWZq25CZlGqRrIYa4bbobjWTYbSRc3PbeonE38pkL4A4hq+xFU", + "vR93G12ZjDebrNamHZ5Mcp+XcJttOhaGYUwCyHbMVc6TD9ijPPmggMbOU05Z5+lyZkEaR4dAmkCaQJpA", + "mkCaQJpAmkCaQNpHRxNTHutTxHUhdNbC6mI+OL91P3udbZh1JUFD73I2gBefOXwaZ/YydbJQ2QUaWfid", + "MJIwkjCSMJIwkjCSMJIwkjASMfIcKHchsjSKZ2aU2q0/cq6stHLRnWNH/mE2eRjWLPS9wvgATXGoKnc0", + "hBxcu6ZycQ815zR9a8KMJhZsFkp1LGpdO2dcul38wyDVH6I0SQSw5kePsm5CCS284jf86iM/HSsPxOZE", + "ZpmISyWxNHOxNjTtx7JVxLjEuMS4xLjEuMS4xLjEuMS4XlW6FkZeCG8t/yRMV4syLsAiJWr5UMUC4RvD", + "LP/k44sadm9iLcCzjBlhwwse9LzfmGnjgfsQgDS1YpfhpbyGjeVwZGFnK9osFiGYln/fXYGZTk9l7N76", + "WfVpWU+PT+/4J2JMYkxiTGJMYkxiTGJMYkzSo65Acxciy9NUxvNh8qdUxstDlo74qfAbUKIFj73pZTiN", + "95FGXWKXXz2oPo7gmOsTN9G58U+jYWdukBn8bWkFg2hZtUmEj1fVtTOk6R65RTrMzccc+Gm6g+gyWgJc", + "AlwCXAJcAlwCXALcSwTcKcJclWW9TnLJ1bs8Saa1mIaNuY1GYZJdwTW8s2rU9S/f5VlWu3sXPkNl+kVT", + "Icdq6X28jffn+j5/E3p3BpTXiIy6p6ORI5kLRUVdPTzsSqFg6+1bIyLstblmtd6Cc9+2ukI2l33par0K", + "dPcqyQEkB9A9VYTBhMF39e7VaVSdF7J1+fWqMzh4rB5PczDXYkoeNywdVG7KqpgAVOC2w/bLC1VPhdaO", + "c0s707AuwzBPBx+wqc/aLVhVaO2LET+VqUbz2cDkUVmRWVbFqyrrBHFJt4HWC8Fevow7QFevA934SSRF", + "JEUkRSRFJEUkNU1SizhoXe1i97Nc7VLPGdbpF0zikTecl5s8Gs1qIuu3eJYXd0LIJeWdi3z/s1SJ8HUm", + "lfKMpYrpAFBRA5xtoWMRHNP7+0BBIVje9N90A+gMXK1wZE43gBI5ETnRWTSdRRM6EjoSOt7QG0BXwsZF", + "F4EuwME7ebQ8FPam4+S1OIi+uuNYOn0l8iXyJfIl8iXyJfK9G1eFroi9C28MXUK+AJc+2Cbu0ZOLQlks", + "tYhsUrSZHLhZy7OMRSOuhqChi4WRMJ2ZEmfHKuRvRuGiJn+YOe++0Vuhz7zs4+3ataM/Szv62V9McNXO", + "QESjRKNEo0SjRKNEo0Sjd/Qm0nWP78PZ9xKvoPKxZh+Y/TKXGUa8Nl4goY7n9v9YmMHjYpUsQBMa8nEd", + "2/EKYVSjx+fL40Scs3Bg9nOlzLR0E+/pmMvkfDmYvP9PEdlzFp9w9eK8rfb650vVDIcCyUWHsJywnAxL", + "iUqJSu+qi05UgcPAohNgXNE7Z5lfy/7krqXLUPmF7L+OL0vZOPJiIdgg2CDYINgg2CDYaPZiabh1sUob", + "Tbqv7ufw50F8qF+IYjUHltJvpF+wgyedOU4hFTJZfnw6VY+FZ6kLO/nlwZND/fQTvoKgKiHvDiIKIgo6", + "VaRTRUIqQipCqjW8O5Yg1UK3jjokuR49EUWju8O1AaU1D5WeC3s1h0l0dkTwRfBF8EXwRfBF8HUnHAyW", + "ktdiz4JlGio0879eGqrLO7yrWepftXU+QRxBHEEcQRxBHEEcQdxds8vfyKFkl0dup51rqe+A0Y2L63ye", + "JAwfrwcoXqh528P8r99B5eYxzDeVYIxgjGCMYIxgjGCMYOwuadQ8HVWA7Kmy0iZiLPB+4PPwWZat6kcJ", + "kTpibvlih8q9LHvCLb8BR6JX58jZ0D9v3K+mA/E/rgYfQ7nk3kdASUBJQElASUBJQHmn/RtLpGtU8rVb", + "e44OF5zZGqEbMms6tHVPXjdCvMDZ7UrRf6fai84ehxr1qwdWjGdDAW/+gPc8NW2uFyEiISIhIiEiISIh", + "IiHirT4Abua6xZC4hsKx+5ln2cFKd66tAJd1n9VrpH5sKBHaTdenER0SHRIdEh0SHRIdEh3eaAfbzdKh", + "qBxodz8PBLe5FvCLe9fE3JPq/ZFwm8rUSTmOIb7JPi92r1+wE1Hc77C9JGGV8phjI8PMiGucDCNu0OTO", + "AUEmtC38ciA1g9qUXYTQM84TK7NEsNSOhA6JpDDM5aiFzbVyOyE3k8VhuvyFto6V0/6foDeuJ+NORm1h", + "YWP+6aVQQztq7X73bbs1lip83K7jLd/6s7f16Pd/u/e33Q/lh/v/d43r26wci1YzZO/0dh5s9ba3etvv", + "etu78F+n19v+tdVu4W18TsDgVmz5PKZKvMqr22aGn7SyxN3E3cTdxN3E3cTdd8oStMqNp54FN2cU6ugm", + "EwuddvCREv5hgaq47ByrQ5UUHnoNPiIHMNYTB++pO+SkYYlUJ/ha80oJC6H4CB67ViYFl8R/2NKZo3qC", + "QIJAgkCCQIJAgkCCwLsEgVMMdhEbztVwDmPvbB7n6uah15DoNh/gpxHmHnNz5UF+iCqJKokqiSqJKokq", + "iSrJ4HNtsFxLp9jNUm154lq68AY1pJJJjTAZM8IYmapp9eL7ty/Pj6Nw6ViFdI/VezBVdM9pEUstIlvP", + "2qbweU4dbcrGXLn9Hk0FMl6AmtZRRhqb9rGKRlyVP4d68jjWjlDgCrQowIrUjiZSGQk2ksamulh2mxzW", + "6g3U5Qi769YGyYSG1wG21nD0sb/qq+8WVIhuwyMOJw4nDicOJw4nDicOb74OcDH8bobG835ZycXxn4zr", + "ZlZ7flo7vDAc1FGtpOtisTplIGost7mpmYiu5DdfbdwR5jHjOj9tIro8WlRT1x3qWOjHBfwj1bCTuj82", + "mtnjonWFMbMu1VCi0lQKd0VITUhNSE1ITUhNSH3Xw12ZKRhdEtg+Fv182B0Lq2U0n5LfBiNX9zTzT7N7", + "UrHDTKhX/jN6E92HvobRU/m4LzRLB0yqIb6DMGMNM1JFgo2lipUcjix7/24f9NJuclSz3Mc34Z6575ov", + "rEuvCxbzgnHLxrKSvMmC9omrr8+rtRTHrPhku1nC5dSoTrtgEVwRXBFcrQVXxBbEFsQWN9MYEyZC2PQr", + "RAGba50mqr7tNZjItIhctwT1VkMQdl73VfcquCTB9yrv/1NEFs+Ovfe16bB3I2mYUHGWSgX7EwxQLDBo", + "D4/HUkljHROcCpblOkvdCpWqpOgcq3cpGwgbjaa91P3dPCYTkRzIKJTNskRwA1F+IEVoc6ha97P/64Uo", + "DvXBk7qnf1nLzrE6GLDMbXoS3O5PpasvvHSWnwj3nYjcxhAJaK0rKwsqnnKgGMQjQn97IKf/+c//+t//", + "/g/24cOTsrM/fNhl741gv318/vSdr+9OrVYff7/3fywf1mMSDIVtevY+k8pYweNmZeiUS9aUDrQ+3s9k", + "YkEtx/rFJKZAOaxooMCHYpd9/Jv/9nv/79b2cd7r7Xw3/fXOx1a7Ue/pH2hWfM64ui/Va67SkDAj6g3x", + "334fSD20ZOb7uU3xT15lU2aCR9TbVPn5XZGJ72HERYwNm/6xn6aJ4Gpe66YeX19T/XQqg/X74OmnKMlj", + "waTiESwZtTe4xAP/Bt6zo9SIyv7g1pyEu2U/1UxwnUih77faLfEpS9JYtHYBG+a0Hos+8CXXWl/uGj69", + "b5Xvz/Oo36/uWoiXcizt4WBghO2k8M+6qRL39yqJKuN/7qOEZXk8Li5Xr/9yaiV9C2YvJHOSzEkyJ8mc", + "JHOSzHlH9NnT0uC84A+/t1uftqSfot7wdY5A2v1c+eRD864ooIIYXEFhvLj/3GLXdE3WEcOm0y4Qy4ai", + "yhKPCwjLu9w4pZb/tQ7keymBxwi2CLYItsh6gqwniDaJNu/GCcc02s2lzRpbns4cc8wcakzbPZxJt926", + "kZBjwTRXQwEYeYCufTANQTPIgNPCKlQeE0jLfA/DOpxwY9lfdtgozbWZo5c/XUUjv4+b/MGTqmug1Tw6", + "cWUPwW0PTkWgcp0VlZqIDgCRjUFxH3w3HRR3SezZGY3tkeXasjJ6rVvg3j7bZw8ePHjkzVGwe1WU5Eae", + "QvDhppqGcdqzz3Q6rtX3PDFyZzXLKt5oLd+lm6+jW1rwrM/LNnuR4zTjpqJjGPf1igMv60N+/pr4I4/G", + "6oTfVqxT0+nJ+StW2lthpzTO/tLIv/ksYypKzcuDJ+zeeyVPhTY8SQr2Xsk/csFeik8ySoeaZyMZwQ9H", + "qbaw2h8AXQ6k0PexF65QHFv7cGVTr+rgGr+g9hJey9elEZ3fQ8Bp2+ZarTrz8QSl8URpu9druxVZjvNx", + "+CSV/1TW1UHBEA5QNhwLfKVzvQO/6sFORvc2krRO0jodjZCwSsLqHT0amZIpq7LqqZdS23NCz+BWatxc", + "Q4xNNetzG40qeDFIkyQ9C/NqP0lz3HlNaRGHViAz0ibWq5Q3VwuHErn8seQ1O9njwJf2vPy2oGX/dk7q", + "mEcb7QucMhxUegj6ZaWwLXRdIUERQRFBEUERQRFB0SwU4a66gIYqOvtgY75Ya19aojdq1J+FPFaycgdz", + "avfIUZIP56iNqr9fgmk3qK1iwbiORrAvhva51WTSqyuqdjGzPZ8XGSqvb6jsJ9C5jZQXpb8KA+XwApBx", + "MsEmwSbBJsEmwead0sANJgQYYPONTuM8smyfW56kwwU6uLB7wpXJQsJFyt5vDnrXciujDtsrr3OWpvxd", + "DiYsWXMf5RbD5WLk6GfpJMuS9Yo0d7sdy7gxjMc4t3nCBoCpBmc5DF9flOs2vNERT6I84W7HKSuVu12q", + "Xb/pGYr8xrChTvPsceEXis6xegXcAsYv7Oj9qzbbP3z/+l2bvX998OP7px/gE/i6vtx79/ToHePDoRZD", + "jkuR6yaTZ1mqrfexm4/nGDL4WenyeRkhmX3uGMjwQGW5vfLwy6GBFGqZSI1IjUiNSI1IjUitOdLwJP7D", + "fFRrUBB2P/u/vKNYLBJhxSzNeT0Y4yUZTXzDDiGER5XjSg2ctGE/6ws3xP77DjsYNKdow85di0cwySBs", + "324llv7ADxOGKR9yjFOBaz4fDERk0YPBPVTNuXOsILDKWHBl2g46HTuecTxkxMI8SoR8Ae1gFeFjwU5E", + "0Q6xSwJczMZ2cTWF4CZanMo0N/UnRvxU+J0a+z5mA6mNdcsVd5t5GZelz41sYEFMNWHB5Y5v5YgvdHpb", + "7pZGB7ZEZkRm5HNGPmeEpoSmhKYzaPoE0GQlNG03H1M/F3YGOZv8/78G/vS+qp6L9FZER0RHREdER0RH", + "REc31SN/Ta3dUPNzRhzGlPNjDdf0YhuMN+zLrUcarsYhuFC04VqQqEPtOco95cu9NtGIsT7LAmDhU0si", + "ED/HSUCxh29c7OFgoOoVvetZoj4pE5Eh6pqGqPDGnNsMdX7qTRihclUcDlBUXTP4M9SrYRYuzgBSNVyl", + "9zsJnyR8kvBJRhMke5HsdTfMW4cBpJfHQMNHu5/h3yWmEj+lMnaziWMBaF7gphseiyepGgqNK2cbAp2l", + "wqhvUA6BoE/uhR3kGixm+zxx4zKxTU2V6bDpIkpzBy2sTvFqhaTAHAVYQLShGpBGFWjVii+EW+d5ogWP", + "C7/WW6tlP/crQinD4ZTQwk0WPLkf5BML2YqRRj/XUKMzhe9XmYM32PXRm0p7CzCA4MxINUxCWW7XKNJ8", + "Yt1blRjBBoO7ZU1CfCw+dq++EzG3ez20xzBuKdPsu56vXWkA6vNrV9p1L4h71TKkNSIZ3GdnaZ7EoYph", + "LNIB+7YHJiyu/mD7cZpKL01Cpu3y2b6I0rEwrDexdviuNzEFweqVzOJeNRgu0SD7uTKQ+VY55fAzda0z", + "jsY4YBAoilu/MEz6zYygb/oCGg/y8Kvc2NAOv+n4SeL6eOx+7YsQG9D9GpSj2A2Z0DKNXfdODUfnWD2p", + "RAOspsQwVgMo1esXsO+aJClel+smccR2ejsPtnrbW73td73tXfiv0+tt/9pqnyu2FZnKEI8Tj9Nh0Fc4", + "DOo92ngH7KdqkMjIrjlhI9geguVm6lZaxxQllUY+24lNZegdY7kVYRtonKgkdpHYRWLXzRO7nNyC+LiS", + "1CXVIO1it0dyWTALniQV/7lJquZDlP1JrlcR29MXV1BYT6I8ojzSutL2T9v/HdW6Nu3RFRp4maYnecYO", + "FCpeXCGzTBDuauh+llP3m00bD4cnm4yG30x+W65Pk9fHXLisN8EDwQPBA6mIyF6Y6Ino6S7YC1dwZlVg", + "GnN9ImyW8Eh0E/SCX6ZJCaPsNhETFLE8y1glr2a1yqvJAy9DWTN0dUUmiJeJYLPtbDCpIzojOiM6I9UO", + "wQnByd24zL4GDhVG2XMfl1JJ97MtMrFYn8OrDMJ8StYvmEva6Bo+u1WvpO8Bhc4ijc+ibt7Lsncu/Zcr", + "hhBiDmIOYg5iDmIOYo67oRDhWcZiYblMTKCA83JHVypjeZK49sy7Vg4ecJPTlVuaty9Ui1R+3Msyn8Xa", + "SpHKXu+z8FtsB5qMnLH5INBzi33DCzcHV4sI3bvU+pC6hdCH0IfQh9CH0Ofu3AXnSSTLLoo77tETUaxE", + "PVXdiyOgU8nZ3psD9kIUy8Bn783BC1FsAH/2MjnJaGMQlGlXeeutjDmU0eizBe09EUW5M/hgMnravdH9", + "dmS1zMoknSbPMYwa/Rjf4Dc6HchE1EJ7NIX1ORgw+Jpx1vfvfoZJy5tNqrGy/fEdxLsuK+XGr7wGJTEp", + "Mw6nkTd84TOZy0HNUSM8Jg3j7IiruJ9+goJaTaFIULE23aWv+VhUjhjDELk3309QCPFyMGAufTB2KCP4", + "xFN+gQ3awW8MJG3o/Rq6/hZG/ffyuRRjwRDjEuMS4xLjEuMS4xLjfg3GLUHTgepFeTd1S8TO3FPGKSWf", + "K/lwL7ejzrF6C6H/HOy8f/sSNinLNfrlwyNsp9NjgyQ9WwjD8OiOL+a5sO/fvrwtJ5L7sCHvZdmR6xjC", + "FsIWwhbCFsIWwpa7dSqJW3xQYDDc4TdBLd1ynZjLL3vlSuJrEaWx6Byrn4SWAylMBVfcLxj9+VM04moo", + "IEwZhHhmNj1xq7NyG89ACzPCb1YGm7Iaa+v6MJuQHkraT2MBoa+OHCYY88Y9bToQKGQV+/DVs3RdctEc", + "cZHB/GCubDzDD9Uh33jmuZarZPpq2cg3KGcr3PkAV8D65H0rYqlF5NtFHEgcSBxIHEgcSBx449VXuEcu", + "5kDPSIuc8/CZOd53mP5rOdytgAzun3MH4p+f+nGxSnqIBgqZuJ7sTN2rcGHF2EqBoKB4igJFYERgRGBE", + "YERgdEddBccBVQINeXb5/Ut7jhnafriPH5LOAhAaPOH+eknG8C5vrMZqNkHbmy16LUwA1R1nSpxNgsWU", + "YfCDcRg3jLuf88QSVhBWEFYQVhBWEFbcSKzwfDD2ADDDFTN6lu5n+PcgPtRHST5ceKePv8l+LnxgugAf", + "y215aiUvNOoZ808vhRraUWv3u2/brbFU4eO2K8i6t6y12/p/v/GtP3tbj37/t3t/2/1Qfrj/f//l3//f", + "b72tv/z+W2/r0d7WD39/8er1m613P239yrdG/zwZq2zLnm79+fvnnYdf/qXBQpquMiEOIQ4hDiEOIQ4h", + "DlmFQzwqzOWQ9sLgRu4p1i/YwRPoyCQfNgc1uguk0fuK6hNShxCGEIZQuGziMOIw4rCbaoe9AMKyvAHC", + "3mfxwjOmHH6/rfB1SSdm2KlX7kVPyEfIR8hHmiciHiKeu0E8nl7OfwLWHeo0z7b6Rfcz/PW4eCGKL133", + "MolVzJIZpGL9gmGSBVbKzzH/nzDrW8VS7cbqTzp0rXvk2tO9DZ71zA30lpVj4dbBt8/22YMHDx4xvAEG", + "4yWpKMmNPBUd9qQSImnnWzZKc20YH6bwXCVk1S77m1s7vt/p7Tzc6m1v9bbf9Xr/+mDP/6/T6/V+bbWx", + "bWBKPWmcS9eqNsNn2dpt7fR2HoTctnfhv06vt+1ywuq2dltla5oCZBlbQEbu6dZsfzxV8Tq9Mdtmm/oW", + "76zTYpteTXs3ZpQ+Uw4ZoBMnEycTJxMnEyffVQP0aWA9HzUjGszD4x/dr744tyDmbm+YJeOJc9qto+FV", + "3Pqglzq47x7ErfWSAX6ul8SmayY4kypOz9ZydKwmfCfH4tdUrZvY5D4E6Xr9IRMr9H5ubDp2s+Rcyb2E", + "tmZaHp+6pSSuCnnPID+zZk7DUP6lGwZAeW/BCwJWCis+2W5kTuvZTE9sAmYCZgJmsiUgWwKSGEhiuN0S", + "Q4XhF7uszmP6N+53shhYD8gg969iN0BESERIREhESERIREhESES4NhEuVxp7zd4Ss4rwlA/KO8cstbSq", + "OAqZ3jYV8iZtINwU74uhVMq9sumAuTzIGIKMIcgYgkieSJ6MIQhkCWTvojGEmdDjIqBVqZWD0JpoxJUS", + "yRKM5bgTlclYSNbMsq8rj+6HAmaQdvraLojmyzAST9xcnFsAyo5w9PPe7U277OPf6sGAv3cE/LHVbolP", + "WZLGorUL60Ez/UzFEa6SUDkbfPLZS1GXAF3ZKmnc/D53s3zy76Ee6zbMJ75oy65NFOqG6XXumNSr5nXZ", + "hgwN9fC9I2K6h43AlsCWwJbAlsD2joFtIy5V+La6ba4UfFqJs8ZM58WjbtiXLyk6dUNJWOu1DtK3L7M+", + "FMCagIWAhYCFgIWAhYBlTgBr3sgXC5hlmWqu+9n/dRAvjHF9lA6sV581VoH1CyZj0C8dqmheRd1kCDo4", + "acMm2BewnMHX86JnN6PS8nPssnULz7Anh5K97effPfz1Lw8f7j37ee/FD0+3d17/0tv/8dGzH1r102wK", + "m030Q/RDFoVkUUj4R/hH+HclccPXxr+F8cQXcFxTWPHbjWC9a6PbIl0V0RrRGtEa0RrRGtHaTY0uvjao", + "LYo5vtqhIgYgv3WYdl1PQ4kYiRiJGIkYiRiJGIkYiRg3EJ19Y8e7MKnW9bvARMu9Lp5i5kt8Llbyw524", + "m95If9ml1b8q59eZymNYRbeI9As2zhMrs0SwgeA214LJ2LhX7kQUpu4S4h/43v+7tX2c93o7301/vfNx", + "3nDhA7VGr+pYe842ecek+W3yD3zv/w1tmv56bptCmM0rbJPOExikekPct9/3tv/+17/v/OOXX3deP/z5", + "8S8veo+ePvn12eOjX19hsyYPffv2259+/WH7r70Xb1/8+N2D1493ftp7OK+RLllzC6cE0pcHT9i990qe", + "Cm14khTsvZJ/5IK9FJ9klA41z0Yygh+OUm1hOzgA/BxIoe93wLvoCkXIDQ1Iab8yPSb+h9Dj//jhL3/5", + "6z8e9x5+9/ej3l//+mb/l3c4LPXnjrbfbj9/9PSn19/tvH2+82Dv0avv/j5vZCabwF0cnGvpFwYb4Ea8", + "wubndJU+YVAL8ggjFQSpIMjAmiRwksDJI6wUh88tfHc/w7/ernpVMxxIs6IRDmzbK53t+JqsdbnYlcIH", + "sQaxBrEGHXfQcQfBFsHW3TOQER5lLopaXVhoYtew5qj7+PvlUdSts4+B7nkLvbaWdcxOo0tbbYPHzT1y", + "XCLQqc1TEzCL2/0mn0siKIRlrsreW5BIkEiQSJBIkEiQSJBI8OaR4FuxBS7tG6FBnSdiXaMXSLPc5uUt", + "ZH2RMKNQ0C2LMbpim65DgNE1zWO6V2wbs9mD/GO1x05E4dYoznJMikJDSZq5wZ1GYrICQ2UhFLlmvzt8", + "criLUSYgl8naZdIkx3U8ZSbPslRb1k/tiEGtuYrZC1e036/4WDCTiQg2+yiNxVAo97p93WsjNmQWgi8D", + "j+oxTubbiOy9/fXB6ydPX7w7+unbt2+fPfvxu0fPHz7b+6nBRmTnl4f/+Pb16+c/Hj3Y2X/21+2fHz18", + "+uBcNiK3xOjCrcAbsbmYm9FVmly4SpDFBcm+JPuSxQWJfiT6kcVFECc2GoDX5bhK9N23aP582cp0V8y1", + "ibsLbaagu0QoRChEKEQoRChEKCsF3fWuUudSTnc/u3/OG2sX3MIWB9pFz7FNRNn1SLTcLAJbRPF1CXQI", + "dMgMgcwQiPSI9Ij0bkN83SWkt3pw3Qq4LXPquU3Y1bseeivSQxGeEZ4RnhGeEZ4Rnt0Kf6GlZLZyNN3m", + "E8LZULo3nMuu5bkm8SHxIfEh8SHxIfEh8SHx4YbD527koLbr3pyqP/nUULqhmaPtM0LFbh5yePt8aJ8z", + "aUdMcxWnYxZzy2fZ0z18WzWC29ckhBCZshEiEiISIhIiEiISIt4FRARQOyceZglXK/iVw2PNruRvIIc1", + "3cchvxvnMY6eso5/Xf07bre0Vst+bsUc71UZU+T52Y47EcXSnjsRxSpddyFn8E34al9S7yh8RzpuRrg3", + "uuwuM7+/fsJna93GY9wwePJGu3fXSpRXpl2o3aI5BIfjmdr7zyleFVFpTixEdhi+/TyziScF08LmWvm3", + "HcRDt6bjRm4st3nVnfxYbbGPf8Ovv+eRo+uPuyGL1GXnEk/2C3wEMq8ljTUf2IaU8P3s41xHIyctNKQI", + "P2ED5t2hAdk0z9WFaJRwdYRpLzxlsFOi5W9VeHD96u77lPtuAb5Rnvauo8/tXT838WV71LuCyYueBHsS", + "7MlHjeRakmvvqhd9QK8gy77RaZxHlu1zy5N0uKrrPGDSHG95t9Vekoe8yxrrcdXu8NAoOjcgvCC8ILwg", + "vCC8ILyY5wKf4f4/nzCm9eXdz+6fg/hQvxDFl64Sn6bMKDItItdTwUphAZigViqo+WA2AqscqwPrFVLG", + "N0QO3NiiazdPtOBx4WvvXm/MKNUM68biVODqrcVAaKEinBkJB4uNLO8n0oxEHIqehSPXLI9Gyw00Kh2y", + "0Erjq8bGbLc+bQ3TrRl9bdO3vxObEZsRm5FNB9l0EJwSnBKcXi2cvi7R8Nx0unIgJiDIiVFDNQATwuV5", + "Yy6tSY8UZ4mIjYiNiI2IjYiNiI2I7UbGWVqKawtDKwUUk9CfJ6LosHcLlHYMAMPmWrnZN3DPWRzQ3Ijm", + "gEybZLIbo8ybe/eT79jQnSloWNkbVKkaK9y8xu/KHlfB8NBYbpvtll9CrucxW8aUF7JavmyjNLJBI6wl", + "rCWsJawlrCWsvRPxqVZg2kVBqSZQOy8a1Q1XFF6O3eBbkSU8EtiJVx11ikiPSI9Ij0iPSI9Ij0jvbkWa", + "Ov+Jc5fHcbpKPIFyoBmP4y33Wg685eL8IAN7mPdt0F1+WXAbfSVCgu8cxo2RQzV20+CGxUmA+VALlNCh", + "SAnrdF0tVEKHYiU09o8DG/g0Gy2hc23DJVwr/3hYWy/kJD8/h6vwlIfSyV2eBFgSYEmAJQGWBFgSYO9o", + "vIDF0uVFAgkocTYrkC2QWyfBBYBO6Hyjidm+XnAEHBTywiOiJKIkorxcouw92ngH7KdqkMjIrjlhozRP", + "Yj9lmcsWtY0lVkQ+20m0xtA7YO4YrCEbJypxM3EzcfONDYSxmG8vdCCEn4G4lvglhtuK53P2Rr0TbzCZ", + "t+dW0/czuVMSehN6E3qTMpeglKCUoPRGulOeE0gXOVnOzXGejbr3mtwoK35986MLwONXrvyVGBOQ7QDh", + "JuEm4SbhJuEm4eadcHM8N2sucn5cx2Jg4gxJeslbYd3w1V04CWUJZQllCWUJZQllCWXvlh/nxo/y8TbU", + "+k0XtUriA+Fgfu7FEj6j2xQdmAJvELARsBGwEbARsBGwEbCtBWyBm6rUdE5G8xGC5zPaG3xgKaP5jIjR", + "iNGI0YjRiNGI0YjRiNHuLKMFblpLf5Zqy5OuD5LzGf49SvLhly4GI5oXJe1H9yuDx2HpiVJl8rHQDDPs", + "sHcjaZhQcZZKhduxq12UFEx8ylIThjikMx22+SxniBHa9Aaye+XKWQkbyz65XHvD5mPqJVGNoBXQcR2E", + "m4O4tV4yt1ysmcSmayY4kypOz1aN9TST8J0ci19TtW7iAYTh2s+NTcdCr98xkPy5TvPscbFmWh6fuoUn", + "hq98FhgVzKyZ0zCUf5mywqS8txAUANYVKz7ZbmRO69lMT1GSL0i+IPmC5AuSL0i+IPniVsoXIsq1tAXg", + "MbLzu/REqL3cwe1vvzsymcggVYiv/F0VRyCLRinEunyXRGbGZ+ZEYJ7UriEG8yoRhxM5lnOuNtt5CNFl", + "5Tgft3a3ez1gfP+p3RBzdbM3npXBXReugpP2z0Z9JVQjVCNUWw/ViFSIVIhUbmiUzSn9oSeHJhJZElST", + "N2c1N5pmZRe+JN+N6j5/xQ4b00UTUhBSEFIQUhBSEFLcgQCEjSSwjnaj6xd+bhd4KRyUz5g5GMP6BTt4", + "AqOSw30tszQyKWhKL3JeJMnq183Ei+rNeK2+WN1O0+U6vv6LM0uSqea7XYJX2z5zdjp9yc0qnEQR/wiC", + "CIIIggiCCIIIgmYhqLIlL1WqVADIbcqZ6EYjEZ2kue0aYYz0d3Au1LyEFMynmKdyOYIC9v3TR/jwJSlf", + "9ueX6Pfgq74pZGGNvD0P3SBCUENQQ3Y9ZNdDVEdUR1TXpNqagq0K1O1l2S5DwJgiO1TA1G12Mi0i1z3B", + "SL7Biiekg5sy/uc//+t///s/2IcPT8qkHz7ssiP/jIONMVd8CMPrNhMrhWFcC9YXbqa6EjkkazO3I0Xe", + "5NvgBUG+LLhYOoedOFy97F4EqYwVPG42KApVaF2F9Y4vjCx3CMYIxkjDRCxCLHJHLXfMZNsNBFLuxHVr", + "ncWo8T4zQjuAKA+KGLKOcf2MkWxN+ZtDkQO8OjAgQ5wKo76xKOW03cyE/u+LoAjpzCRBgaj2bMa1W3Pd", + "tIAi48nFhZlOT2UsYv/SX2McyqEvA6OcX7W2Dgrh+DUD0WZNngjQCNAI0AjQCNAI0AjQFkdudXtyoIhm", + "QmtQEHU/+78O4kP9QhQzF6wuJjl/01Zgl9L46UQU15iZsH0TZloea6LeSQsDTtD9pYQyhDKEMoQyhDKE", + "Mhe4vnMhyrRXPdZ6LuxNw5OhsF+NTTbnkVZqZUgLQ+hC6EI2S2SzROxG7HYH7sK8sA6qC6iViLGr87om", + "TDxJWDX9lEsae5ZqNKlyE7PyIOOR29cR5Nxwd90LLCqBTT2vLQDH90aw3z4+f/qOYRt3uiURdj9HZcTL", + "hlZ+/P3e/7F8WPuuOxR23Xzur2Q49bTav5fMmO3VIjxJFSV5LJD94+ZQTz65L6Gfpong6ivFdKp0IR08", + "EvIS8pK2joiPiO9uW4bVwKvCfzXeWMdS7DATCqJgwyJqR1oI5rZaw9JBrbBdjGcp4jbzXNAGhznjRNOo", + "w9ywu4TMB0soWOyeH0slcF+DH+uZYipYz5LCTeqB4DbX6HaHm5vraG6lmzml7ViVKSFXk4lIDtyiP7V8", + "+L2Qh7rXkiohYsN4WSg3Jo3kxEzNp7oPPLrFHmOr6+gbi4FUwnfCJCcPuq50dtzad2+5Eezo6HBq+zlu", + "dVzWR5i8lnMiLCvSnGXcGMaTVA0xHNdADnNkTjf9E8GGmiu3M0+X+t7gMiFNWS9o1j/YL8wI65KY4xa7", + "5wqY9ByWcB+q9Wq20wwb8VPBxlwVqI/lRpg2Lk4+U5ZnqIvd6nOXMVbLDaccZ5iLe8oNbCI+wQYsHZwY", + "B4Udxp7iTVS7MDcCijtoggK3e71ej+0dhHAYca7DaogK4ExomcZuok1NFRjGPb/NhNfJZZuqpMBmpcqN", + "HWDPPZWqLTzGju/Xpk3m9iPs0Bei6LCDAYyT1QXcwRAipylxVkuGQtIkIS7xPNGCxwVMeK5C4ZV07dp8", + "hqVuwGUSZui3vUe4ekDrDlUkWH2KwhrsfVddNT18jtNYDgombRubjy11qLBU+HpzeLQh6cutURsUv7CZ", + "VbHhKpT7m/ezrrQAjXYPVJZbc9XO1TX5i9yoST4j+eySjyQebbwF+6kaJDKya45XlOZJ7EfMb9TupS0h", + "PfLZTpAsnFc4EBJh820cJ5JCSQolKfTG+krzJkl0viC69mFE93Plk3viWUnMX7og6pzrvAJTMmlMLtDg", + "s47JKIlWudlJBn3hBbyYCWlHQrO+Y2bDJMyHihRwKUcWK/TFpk41VihqycFHZeCf4zBd/rFHQ4Zzm3HN", + "j1RWLDHVsdCPi1pRPEkOB9DBixYGGJRDn9yJLmUNW945b89+/ZMeqCUd95A4QeIEHfcQaBNo03FPSaTD", + "gFUXPvRBQAuHF5z1xYifylQ7wb08TkB1OqqtG45PgJgLwGTQnYOaQEKhTAucB6CNjplOk8QNL9N5Ikzb", + "zXZ1AqsWjqjXS0/qcyZjwTRXQ1Al+AMEf5WwCapvI9UwHH+4XY6NU2PxQAJyjFP1jcW62dQfC8gIohF4", + "Jb0SZ75TO+wXXwfQhoOYEGQG6AHUyzd0gwnHCu5h3wLDuF/e+Ni9+q4R2JvwnnvJwoc3j8t9aEYcwTyl", + "cY0TgwEY2At75nY9J4TgV65eGCpcxfj1p0z6AyL3fYcdwekYnK/1UztyGY65irlNdQGFV/rBNcbPDug5", + "zjItUy1tUR7vQBvqZ3tSMwBTbKjosJfpmdBM5eO+0D6nkRw6ASpk18Zh7Hk7f3C2c08YWz5SrUw5zXh1", + "coUqwRoR4z7Bc5uOXX+4LMdc5TxhWrgRdU+GCW7QTE3gWVObcRZzmRTVzKVh4o8cIr1WMoDWGz4OoyNO", + "hS5YzAt2Tw5VCodR5XwPx2x4hPh2+usw4c9cniOeZULBW4ErpVv6YMx44pY/eBN8odyi9lzYDnuMP3/Y", + "c4vfh7fuS/Y9e3Xw+t4r/ikUuQfzsM1e7f3jXkjwWAxSLTBFm72Sqv7w/fv17g/awJF7Ld3mG5WxQGpn", + "SLG/rlxCU4QyufbzPjREmnL6SGNlxLQYch0n7iVPB7jFS5j3TviRIr6kM6nzitfnOba6mHyN/Yyy0Q2W", + "qi//vAy6qHJo9hXPzLwkSwdnJOmSpEsHZ3RwRvI8yfN3+OBsrkR/VYdnbkC0jPHyrXw141BMAsaFdauy", + "yEcTbLBzcxO9FuFPgvkSGoumA+vlBOMfEqcyzc2MqVwtB9/mrWDHmHGpwfBubhbSlKZ1Xixx8zC1I6HP", + "pBEY37AMb+iyCd0zsbEDsQNkmYmHkvExYKCOeTbUPBamzeL0TIW/QzleVPJiUMWCEhYHz6QNHejtXj3v", + "wUbxp9AplGHlWKwgDb3fsDAU+qZZHMrtpRS2QB4Kj1yhrd/NlovIjpDEIRKHKLTB3QhtQPIgyYMkD5I8", + "eD3lwcMgaHxFQ0oIvLCGHWVdCjIjWNYwIKa3psQzWgj7gKKeUINUR/40c68eMsJ7GJoR1zhvRtzs+VPe", + "4D2IK4fUDINEhN7E2JzjPLEyS4SXtCb3M0PoMC1srpVDA3BA8+vIdPkgR0GsilSdCiXh0E8LblJl2iE2", + "xVmqT/yJM5yd1voU2vlVjUChkldiAwol3V8YUq0yY3+C+XWzDUCbzC+d/F2zvfQHyK3d1k5v58FWb3ur", + "t/2ut70L/3V6ve1fW20wpeS2tduKuRVbPo/Z68A3ani5okSGA0X2lSRmkZhFYhZFkCMBhASQOxRBrgbF", + "px7aLkkCOc/FBw0nT1qcpicO9MuwEm7cK7E7PJB32J6ZWInOj/cwP7RDGxeD49ZYDh3pquFxK/yMJqbB", + "uNRHT4BjpGQqXgY37EwkSedY7ZWVDnFT8lJi8jahI2lsqmXEE2/7ZtqYeUNHZGmWJzwcpPlTrj3LHF8a", + "y8dZh/3s6u+N6Lwlr/uV9cH0DxaF9oxsJA0z1r0CUaqMjHFZATvTdjWCBLRdC6tTbxxbOe4KkUjwfZKG", + "yTHcmo9ne23Gx6kaetkNYMy0Gc/dUqWGy6WoJ09fPn33dKOCVKMIhV26yWLuL7sx43odaNEtHCSIkCBC", + "gggJIiSIkCBCgsjlXkOy2jnIWteSVLG2XzAZX9fg1Guz6YbV+ysr9m8+lfa+umETadAJXAlcCVwJXAlc", + "CVxvkQb9EnXnXdQMF2vY7LwFKxhT1SkHD2yuYh+QIOaWzw9AEFTHvnDQUpsM4hRHOjVmYocDzugMXg4M", + "IvA41ypOz9QPPqn2tQGbRytVmpsy23TAjBhCu0Hn7o2Cwndg02MEUKnbRgtfjo+m4B3SfYA2W8ZN6Psa", + "TCIY+GZW40RDXX+W7kERT9f1zH/f1Fc+zLRQWro3wZsIBQ93hSYfbt1wfe0SJNLYSfgBrPuZKC86dLW1", + "4OOBC677FYr/ClZFflyuxK7Il7WyAOLH6KbJIe1pTfiR5RrmAxzIYKwTm8IbV1RfxF1WGg25ifH22T57", + "8ODBI4YTrMOe4NpZHoQl3NgQGuK5cN/rXEVhhw5vR55wfCPQvrgSgR961A1Ck/mT2/Guxvxppr+eqnjD", + "vaXg3ToYALKp9Mz1hGLDTfeZTb9Sj+GqZuSfLvEqsQVxvTnCBPOn9qId9+dJFssrCDdGyLH402ExWJIC", + "OkY8ifKE24BUWC3TWasV7+RY/Joq0RyTsfX+3f7XNcELW44PxhJWNVIjkBqB1AikRiA1AqkRSI1wVw3x", + "RqWMc2nqBJAQIBLEiiEjMbDcmOsT3M1NkF/QQ7t291KDPgGjEyppJVisoYQe4uR12J6dztRnhflKAyEQ", + "YpbmmJMXosHZJ03c9IHAelV/H6ln4/B12IFlZ+C8ZIvMB4PsC0cQUZDhoR6+U1nfv5O+NhDJAdyafMWm", + "CjR5v+wzkNvfh+r7qIS+SNSWuG5qiig5nWu1b4NRVNUdiydJegZ7I4Y7LAuQGClQFYDZ3hwwTl2DTFrV", + "YnAVjTD6p22Ogh+ULHIAt6Z9nZB80KiricgHRS3QScDvlZcSxvlGno1uPuzE26a+WSMaH5kNkthEYhOJ", + "TSQ2kdhEYhOJTTNiE4oiFzh/LQs2VQmoKeTyUeXh1uXgUrUIDNN11QG6ao28kRG6qi2YYBgsRXcDwthP", + "XEsQiUGGhZY//WSFMrCV+PuxI6h7df4TvVHM4+aVyAemWukduuRoV8fqQrObMI8wjzDvJsdNriJYALyj", + "GsbNJzzQi5cfG7zQZ3zOIapxTZPLDlVSVAajVsDkolC8/WSOZ+8USa6kKKxUe6Fib2JT0tt+/t3DX//y", + "8OHes5/3XvzwdHvn9S+9/R8fPfsByoQLlFq7rf/3W2/rL7//1tt6tLf1w99fvHr9ZuvdT1u/8q3RP0/G", + "Ktuyp1t//v555+GXf5m1krhFjr6EjYSNpPSj2LDEzcTNxM3EzbfNq3oVbi79qWeM7m8Psc61PGbc+knh", + "rT7KhyoxbsMlhMybipe3klQXYrQ4h9tB4nmW4Nze/NCh1Unx9FPGVSxislqm43cicSJxOn4nviS+vCtW", + "y6vBZcZtNJpVDz52X4d91k2fKB2PuYpx1R9zJbPgAqZzBddg1yXUY+XG9UQU3rXPje3HbjbiRpjuZ/gX", + "Yue40Wr4viutGJvuZ/cPPDerthWxtLdMaXu5xgtPY7mihWfv65sukCkC6ZSJZIlkSadMOmVifmJ+Yv6F", + "zO/YbuOWGF0ex94GtwxpVK3gS2nAuY3hc+gXWDfMOAivqr/wC4LswGCMQcKA8TTCslzJP3LB+gVmdtBg", + "p+HSVtuyh7W7ZbYa67E3iEnr7FXQaW6K+5pwrTmFtSAFMWE1YTUpiAkWCRZvPywCt9UO03lAqQWK4jIO", + "RbVYbwOMPkazWbZD1Ec8kw/T7ESUsR5lHCRZSDBLfbN+XogwpO1dAfS+vr+a582b6LRGPEo8Sjx6t9W8", + "QbW75oS9JOUuUTdRN1H37XGXQ+bdoKq2/v0ealK/zFXgPhd2SmOLNfJ3MTVF+r5lIN5eWl3fibdIZ3x5", + "6E4oTihOKE4oTpBKkEqQehtsh5cS6lwL4vdZzGdDNXi+vOdD4kLY2jDD/si5stIWuyzLdTTiYHcMb65U", + "xrpRMG58IvfXZF6Gtax85v4MtuZQFSLXO6P2xrn3NW2diZ2JnYmdiZ2JnYmdiZ3vBjsjdVyWghext34j", + "SM0SA343M4ESOsfqZ9fxeFju3lsehgn9+vxJlIQjJy3gzo4UjDbqYdQmY+u2e7gIBMcNKByhHNdCuMxi", + "1pADHiGPPTeC2nWNlcigVjqegVRJcjiAjliVM99hWleZ+nRoioVRm5nS+EFzy9Z4LGL3KiYFTmrf1hQi", + "OJPPIPkMks8gUTgZk5DPIPkMkrxC8sotMUgB/Nu81yDeRbdAUnGLLtjvNkQOAetfkC6MNwJ2CzOPolTH", + "ft2Gd9EvSdyLOPsY4xkuqXabQJ4NNY+FacON/eFvl3eWcOWvyzMNQgr8QELKOjsZDvdXFBKwBuG1gIaS", + "2EBiA4kNJDaQ2EBiA4kNJDaQ2LA5sQFoa/Niw1gONbcL5IZX+ED9iENaNz39ZdlB2X0qtFuCwsIVVjOH", + "/p1jdTBgWWqM7CeiDb9jyS4BjF1fsNgt61WtOKRSqZ2XoHY4gnd0x9PF1+8qn5U9fAeQ8DFzQuJ7bg9u", + "QW+8y6bs3PpN6fVgNO+qcwTO6sLwqVSPeeKocFbUDDlHPBYqEuFrJbgG2BU4vpFgfTFwmwiejeGN7lPH", + "MG0/T8WpTHNTF3ynWhCqFgKWbzQaOdcO0N+MuBHN3Qke2tiHEJNzcuY3e5Ckyrdjqp21x6A9mIXfVAdS", + "G+uzD2W5N7TVbo2leinU0I5au9sNDUAS+Qnf8uYGTC0BIPXb1L+5rjmrV3qSBh5I3BpkF64x2AI5zsfV", + "+rudYig0NGBTR35+72iVa1VrZv+Dx4Hx5DDXdeAtF7K2J5fa4uZD7Ft+IpgYDERkJ51m8ixLtdst+sVM", + "v7XZt71eOYND8KdrdrRIWgPSGpDWgLQGpDUgrQFpDUhrQFqDy9QaeOF982oDJ4SlekptkGkRuc4LEnC9", + "3m8xiXGLWDCBmzKZ3FPF1HVTs9aPThCYyGn+elk4Y4TLU2cFCVhHlZUqd2+DisVAKolGd9O6AN+q23wp", + "7W02GCSfGwJwAnDyuSGsJKwkrLxErPQot3mszFXo1y1kRG69rnkF95tyRCpJZxlvUsR+pQSiPHILIU0t", + "gSKBImlqSVNLSE1ITUh9tW7sJZZW8XUVqN7pRrmx6Vho0/0c/jyIDzXc6Op2SJuIsWvF8iulqk/D+u0W", + "d8yxw56lmkUjEZ24mVl5kvHIsVOb5QbHu+veYDDGylLpg0QJPuduqX2f/9NK0T/trATkU41dSOQLB/Xl", + "wZNDWGPdK+9ygkBP4lOWpLFo7cIi1MYa/JELXUyqIFWU5LF4gmroVrXEcgr65J7a+2maCK7QIqgAGcFh", + "YsuV2FTJSTd03/ChVCjWZHwozpHkSP65UrLKYBzqWOjHBfwj1bCTuj82kcfjonWpkkul/J92fD+IeB0w", + "JY01aaxJEKkKIkSXRJdElzf07qmASzXKqxBmlcAWXD51mAn1ym3xsGbakRaCObaBm0irWe8yIAERt5mH", + "nnbwM7YyQsNwl5B5s/OCxe75sVTe2wB+rGeKqWD5Sgo3hweC21zjXUW4l7l+5Va6iVJK3lVahVy9FA0W", + "AbVZ5Lc+HupeS6qEiA3jZaHcmDTCeQJF+VT3O8fqWG2xx9jqOlWD/YHwnTDJySO0K50dt/bdS20EOzo6", + "nNptjlsdl/URJq/lnAjLijRnGTeG8SRVQ6+FmFggn41kIthQc2XB6L1e6nuDq4I0Zb2gWf9gvzAjrEti", + "jlvsnitg0nNYwn2o1qvZTjNsxE8FG3NVQJMiboRp41rkM2V5xnLHD1t9btAZAEgmZXKcYS5oTO0+fYL9", + "VjoWMVaMTYexp6ht34W5Uc7yyPfhdq/X67G9A2bTE6EMi3MdFj8o1HuGBH1MdbK5Ydzzu0ot31QlBbYL", + "/eQBc+6pVG15g5T7tXmTuf0He/SFKMA/wQ2U1YVrZFS9za2aDAWwSUJc0nmiBY8LmPFchcIr6dq1CQ1L", + "24DLJEzRb3uPcLWA5h2qSLD6HIU119/45arpYXOcxnJQMGnb2HxsKaBB8+1xDZLdNRDsLsk3v9ZIvHTk", + "QGW5NVd9DVy9t+kKOJKKSCq67OMZugGNZD+S/Uj2u843oPFG+W+e+NduBXo751lD93Plk3viWYmxX1Cm", + "dEvTrHQJmnR0yK0xqRan6YkwFdkAbi+eCGAekztsD26/kGqYiEXQPp/PvVfmsXcNl2p43Ao/GyBiyMSm", + "AYFdTdJkSurhhp2JJOkcq72y1kH6zQ0epEAwWDfpRtLYVMuIJ+yPXGgJIbTm9ESWZnlSeuR7eWMPXZ+N", + "5eOsw3529ceMYi9FuF+Dq7RbHdozcrE0zFj3LkSpMjLG9QWEi3ZVDIC2a2F16iUPH9UL3j8vT+KLJY2T", + "31JtOcoybcbHTijFMMeAXqbNeO7WLDWclSKwaddTimi+B2TulF9Y9ph/Cm7X33077YVdNRHjW3/2th79", + "/m/3/rb7ofxw///+y79v2Hrs20bnbi3QbIP5ZQ8YWqjY0500YTVuAzG56YXbr2FjXnin+kGedBjJDSQ3", + "kNxAZl0kUpBIQSLFDRQp0NxlLYHi9y/t+bchVzG0X5SHDyei2IDVEQRPqSjRpYHoPo0A7Baz5FTE5SIX", + "1sAJXDddz0yMeuWM2rsGCnNSgBPIEsgSyBLIEsgSyN7Ui5fXo9gNq8K7YIuzgmU+PsekMXnQ6apZw6gq", + "znrVMtobxUxIULv2CyZdPjD2FZuUVW3zn0M9iG43Sbd329fgpRxLezgYGGE7KfyzbqrE/b1KIpi853Zo", + "mJ/6sl0ZoGRyYiBphaQVcmIgWCdYJyeGGup6iF7JlmWeWwOCbTDP56wvRvxUYlD70mAeDcbRoqLBQQAg", + "vADyBjMJsMCTEBOxGrGeq5jpNEncyDKdJ8K03URXJ7Bg4WB6i4tJfc5kLJiGSyDSQTAo8Wxqgm23N3uB", + "+roNjo1T12fceMOVOFXf2NJ8BQ3fZcSTpAhW6Eqc+e7ssF98HcBwBiSPIIZAD6D5R0M3mGA47x72LTCM", + "+5WNj91b7xqBvQmvuBdWolSZfFzRv89IOJinNK5xGB2d9YU9cxuek2vwK1cvuGnA9TR8/SmT3gXCfd9h", + "R+D/AR4k/dSCrcqYq5jbVBdQeKUfXGP87ICe4yzTMtXSFqUDA7Sh7r0iNQM2xIaKDnuZngnNVD7uC+1z", + "Gsmhk8lCdm0cxh7ri7CywRPGlo9UK1NOM16dXKFKsDzEuEXw3KZj7i2VxlzlPGFauBF1T4YJbvCwxccu", + "ajPOYi6Topq5NEz84VLbtJIBtN7wcRgdcSp0wWJesHtyqFJwtyjne3AkQSeZt9Nfhwl/5vIc8SwTqrT2", + "0sKtejBmPHErH7wJvlBu0TBd2A57jD9/2HPr3oe37kv2PXt18PreK/4pFLkH87DNXu39415I8BgMpDBF", + "m72Sqv7w/fv17g+GtmAB5fbdSARD+ZqTROzmrpuz0BShTO6tsMqGSFNOH2msjJgWQ67jxL3k6QB3dwnz", + "3pt1reF04aUHktg3fB51qU4kMGgVP5JwNPVVHEnCDCJvEhJPSTwlbxLyJiEhnITwu+xNMl8M/yoeJV10", + "oCjmnqO9hduwTNXRIqC34xSURGNu+XzJM/hT+KJA/DIZeGBHOjWGjfPEyiwRKIUweF1QenycaxWnZ+oH", + "n1T72nB/M0GamzLbdMCMGEKLwRFFC7+ODL1fiXYfgPzxGjAsx4vRXhLxh322FJj7vgYT0dU3s+oCD3X9", + "WboHRTxd1zP/fVNfeQ96obR07wbuB6Voo/B+vHDNPNzmJo2dyJ1Y9zPXVJR8XW0t3CGPS7D7FYpf1frO", + "V56Eng0fU9ZfqiO4kMPt8nIcdFM2hRelqL4/u6y8GNGN59tn++zBgwePGM6LDnuCi6CZ3PUHNzyCKP9c", + "uO91rqKw1YZJnSccJzJSRiUmCIy2mypNp6hu62o1x2rewBWPU4es9f566m8n3VxvqfRscjmgSs9cTyg2", + "3HSf2fQr9RguRkb+KeAuzuVn5LhMHGGC873FP0+yWF5BiGEjx+LPVOGlociAEU+iPOE2sBFWy3TWasU7", + "ORa/pko0n/S33r/bX96jl3kqHXYKrzzzay6dSZPQT0I/WdCSBS3pA0gfcGctaIM8+3XUAW54tIzxfsK8", + "KYghPtAQXgGPJkxTODY3yW31NnsJEb4wrEM6sP60z9Svm5+O6FbLITRxK/i8ZVxqCBA3Nw9pyhBw4fbD", + "VGNQhTNpBItTYRxwuMUVndxCb0xiwYGkD0eSE3c54/3zoZJ5NtQ8hjAU6ZkKf4dyqjEfakEvYGXw2N3Q", + "gz5Aoz/8AS3Bn0KnUAbc3D8j3oeq334PO4pjR3HsSAghIYSEkFt1zRAdvZKoRaIWiVobELUOA8Z/XY9F", + "OJiZfyUnWluOuT7x13KGQyIkslrI7YazVjTZVdJKkMLw9DIYj3bYnp3O1GeF+UoDAkXM0hxz8geMXAvI", + "xC0ObkJinHFcJ6SeNU7tsAPLzmANtkXmLaT7whFSFCQXWwk2bljfv46+OiAYDVK3D2HNpkqcuvj+WL0P", + "9fe2ur5MPEp2/dRkZz2da7VzQxS2qozHkyQ9g80fjYDLAiTaz6oCDjN8AME4dQ0yafWIl6tohDbxttnd", + "NJxAywFEy28yVIUiGwQ66AI6sr0Bdqrwjk+PHIiJq0mJFGCQBDoS6Eigo1MlEnVI1CFRZ0bUQSHi2gQs", + "x9CCc41L930s71DdSYzy4PMYTnfu9Qt2Ior7HbZXv23V36BlRtzbe4642fM+nuF2LBkwHwMdhr5DGiqN", + "T/GAxieSwss+YMTptsiKwDBT/sqxDV35BOobtq1sNLxDs7krML27qgiLfuqQkRjhPOE84TzhPOE84fyd", + "NRJDrl4X6Wv31y6NnFhTmEPgkiSZUt5zVd4fZHyohqpdVBlKA1LHGKPBUfKpYFmus9St2KlKis6xepey", + "gbDRzLWzBk8r/L2zETN5/58isixLBDdiEsR8TamlrGdzAMdqfzYBe73LnsnEQlQ71i8mAkXZMeUxxS77", + "+Df/7ff+363t47zX2/lu+uudj/PccPCBGtxKK8YwoDOs6r/gWvNiBa+M5oaUfVpvSfj6hSjM96U9nm9P", + "848P5rWq+vg1atpBbL7vbb/49ue9H3t/f/To1197r5785eEP/3i7vb3zw1/rLV347KNlDT+Ir7TdMxJ0", + "vf2Vn98Vmfjen6Fhg6d/9MEy57Vw6vHmVq4oBUEG6/fB008QAJRJNXvpr5lwB67B7J4dOZCabDxu9Uq4", + "209SzQTXiRT6/ooeSQKLPvAlU/DR9YOPVsb/3CFIl+Vx2YFIa0aZFI6UpHqS6ikcKQm1JNTe1XCk0wLm", + "SmZ4C46dvsyVZxvuyTp40nhiUyn4cXEQr3hQU6vGwqOSyRlEb/v5dw9//cvDh3vPft578cPT7Z3Xv/T2", + "f3z07IdW/dCErn4ieiF6oTMJOpMgfCN8I3y7JmcSMzy1Gr6dLj94kGqIb4+Pzobx2eNTDv4Dg1KZyVXs", + "BtOkmmUTDVazLv90nhZ/idJoH/KvKMiwwFX0TTNJJ9quKRMohIWDJ8fqPXqR25RZzaMThyFD7eNYcwx3", + "tWocJESQg/pdRxVLnQffTVvqLA8wtTI4llY0M4+1WxPzKpjwpfJ76eYMA3/w5OknHrlubMkVkxyVDQoz", + "a8+ulvKdHGMgK9jh1i3NH1OtmwxsjtaqHg7cOqV8mbNK4ss18S069edkURqj3/ffjw5fM5whc4PEQR6X", + "q0s98AMJ73XtRSONKskkJJOQRpWQnJD8zmlUp8i5SuSnsyy+5vWp881/atcXbdAEyBdcN/6pyh0XNABa", + "4XLZiY0QhIrNvKNxGYMKXkHLT4T7TkRum/BhscHxNzDJxLIAPDHRoaBZVJl/SezdNDhi9ya37x48ce85", + "OIE02urMNUGa/LCzzApnfeOUBveKtTvhAO+nDVHJVpTx6FZbutWWhB4SekjoIaGHhB4Seu6k0LP4Atvf", + "oQjs9SaMfplGPGm1W7lOWrutkbWZ2e12t3f+0ul1ep1t2MV9xrMXLNgRO6oEIzLt8upZwY1MCoy11Hbf", + "RCJpg1ww5sptKaVLRzWa0fQtoiBmGJkqP63H7kWuyEJZwpWbBNwYOYSHMFum4Z4hrmO4NsHTYq2qDQz6", + "P//5X//73//BPnx4Ipws4+bJhw+7roX/FJE1jBusPExWkJyCizTePBOLTPMIL/B028sE4eEEJ3htnIjC", + "B1vi1mrZz+G1lspYweMOc2BfKVNXisJrevCa23IPwst5z6QZQWwmuIqDvRsJVwGu/F0hsETkRmjT9m+g", + "wdEw+B7DvhAL+BNvLIqF61K4USjUJYiyrr4Q/2kolNAyajPhXmDXBYNEfJKueyovDeN4xdEp1xCPGKoI", + "0aEiodx3rsQQKKvthtd3FPedzlmu5B+5YBL244EUGnpUKtd0zUxhrBj7m5VdI92UCJ3fYa+AVaEn+XCo", + "xRCv1vC6/QHYs0fl8NTnCzS86cgqVQM5zLWoTmmoTKbTOAffHO7eh0zLCCavnHR5ZRqydDCAzjAdNin4", + "jc9jn1uepMPGu018ELF9nA2avUm15cnkBeznMomZVFs8y6BTtgYcahJzM+qn7tXwN0RBtWFuQEI8eKvG", + "BJOKacGTLQzv5XuFmSjNRMwyKJfZ9EQoEwJ5wcTgfuOF/PtixJMBLORJkkJwXaslLHGTiAeuQYeZUDBi", + "bO/NQWUwsH0NXfE6dVMCp1qpmChvLY6Z1XI4hJfQ8UCjGsXfNmUq13nZkRZmlDq0wBgI3O0zbbx/t0Ru", + "aFpdF2R44t4mwcd+yiVnvDD+IisRdxjUt5hKJT05+IT1qlZIyOU4FrYNmxrWylXmLw//tc22e71/xRm2", + "/bD3rz7MmnQ0pewoKdcc1/2utR3221vBY4Ct3++FhT/NhMI1RKbdOI1Md5jLWJiuqnYzxEg/leLsfmWE", + "agPRMFD+PcRmFWyUnsF08K+kqL6QISAeBGNWPCmsjEypKytf6cnF3/gy+uB6pQ6lfN1T5XptlMbGB/ZL", + "8wxfulfh2XE9Sx/pOXA/XFANFQRXoaYVr2FZm/QNVrihU16m6Ume1e45c2Uay62M8KI0GGp/i7YUZpKp", + "T3swSdvk93Na3vwGVwyVR+s4HdJBfdlyZeOW0GGVpF4KhTPQQkUjnao0N46qCrwXHNrX9gH/Coip5gPQ", + "yvFYxA66koKVsAiNBGWOP0j1TfJq2jkLXhVs2jO33IMitho2EZQgps2kgwl40f/IU8u3MI6JX5lrUDJZ", + "ioIekYVNprKhVetbRa3ZWj8R/Xw4DDPZySKw83iVanWCwJNNL80CWmKJHIioiBK/cgENIQp5VfQk/4k3", + "7NwycJ0OoSh1OpAhY6lOUySDSYaP8cFGVZ4VesAjt4hKHbOMYwAal0foiowXMCC4dVc7Yi/LdhnWlh2E", + "NA2lHOWZ23pgIh1ZLTMR6j6dGf46v91u7R1qv38ADnyyQsH1DuVm9I1hg1xFSD7SFtWe2Msy0/ry+5f/", + "HwAA///1pDp/u7gMAA==", +} + +// GetSwagger returns the content of the embedded swagger specification file +// or error if failed to decode +func decodeSpec() ([]byte, error) { + zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) + if err != nil { + return nil, fmt.Errorf("error base64 decoding spec: %w", err) + } + zr, err := gzip.NewReader(bytes.NewReader(zipped)) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %w", err) + } + var buf bytes.Buffer + _, err = buf.ReadFrom(zr) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %w", err) + } + + return buf.Bytes(), nil +} + +var rawSpec = decodeSpecCached() + +// a naive cached of a decoded swagger spec +func decodeSpecCached() func() ([]byte, error) { + data, err := decodeSpec() + return func() ([]byte, error) { + return data, err + } +} + +// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. +func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { + res := make(map[string]func() ([]byte, error)) + if len(pathToFile) > 0 { + res[pathToFile] = rawSpec + } + + return res +} + +// GetSwagger returns the Swagger specification corresponding to the generated code +// in this file. The external references of Swagger specification are resolved. +// The logic of resolving external references is tightly connected to "import-mapping" feature. +// Externally referenced files must be embedded in the corresponding golang packages. +// Urls can be supported but this task was out of the scope. +func GetSwagger() (swagger *openapi3.T, err error) { + resolvePath := PathToRawSpec("") + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { + pathToFile := url.String() + pathToFile = path.Clean(pathToFile) + getSpec, ok := resolvePath[pathToFile] + if !ok { + err1 := fmt.Errorf("path not found: %s", pathToFile) + return nil, err1 + } + return getSpec() + } + var specData []byte + specData, err = rawSpec() + if err != nil { + return + } + swagger, err = loader.LoadFromData(specData) + if err != nil { + return + } + return +} diff --git a/api/api.go b/api/api.go new file mode 100644 index 0000000000000000000000000000000000000000..bb00ea0c9ef17577595dd7003aefaaa6aa2cb9ff --- /dev/null +++ b/api/api.go @@ -0,0 +1,2 @@ +//go:generate go tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=codegen.yaml ./openapi.yaml +package api diff --git a/api/client/go/README.md b/api/client/go/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e43694516025db5df4bef77e3aafc6d5158f4a81 --- /dev/null +++ b/api/client/go/README.md @@ -0,0 +1,65 @@ +# OpenMeter Go SDK + +## Install + +```sh +go get github.com/openmeterio/openmeter/api/client/go@v1.0.0-beta.53 +``` + +## Usage + +Initialize client. + +```go +import ( + cloudevents "github.com/cloudevents/sdk-go/v2/event" + om "github.com/openmeterio/openmeter/api/client/go" +) + +func main() { + // Initialize OpenMeter client + om, err := openmeter.NewClientWithResponses("http://localhost:8888") + if err != nil { + panic(err.Error()) + } + + // Use OpenMeter client + // ... +} +``` + +### Ingest Event + +Report usage to OpenMeter. + +```go +e := cloudevents.New() +e.SetID("00001") +e.SetSource("my-app") +e.SetType("tokens") +e.SetSubject("user-id") +e.SetTime(time.Now()) +e.SetData("application/json", map[string]string{ + "tokens": "15", + "model": "gpt-4", +}) + +_, err := client.IngestEventWithResponse(ctx, e) +``` + +### Query Meter + +Retreive usage from OpenMeter. + +```go +slug := "token-usage" +subject := []string{"user-id"} +from, _ := time.Parse(time.RFC3339, "2023-01-01T00:00:00Z") +to, _ := time.Parse(time.RFC3339, "2023-01-02T00:00:00Z") +resp, _ := client.QueryMeterWithResponse(ctx, slug, &om.QueryMeterParams{ + Subject: &subject, + From: &from, + To: &to, +}) +// resp.JSON200.Data +``` diff --git a/api/client/go/client.gen.go b/api/client/go/client.gen.go new file mode 100644 index 0000000000000000000000000000000000000000..4fa8e6abd672daca96f6b4018dab2d7a58af9a94 --- /dev/null +++ b/api/client/go/client.gen.go @@ -0,0 +1,46786 @@ +// Package openmeter provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.6.1-0.20260403235458-a76544bd16ff DO NOT EDIT. +package openmeter + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/cloudevents/sdk-go/v2/event" + "github.com/getkin/kin-openapi/openapi3" + "github.com/oapi-codegen/runtime" + "github.com/openmeterio/openmeter/pkg/models" +) + +const ( + CloudCookieAuthScopes cloudCookieAuthContextKey = "CloudCookieAuth.Scopes" + CloudPortalTokenAuthScopes cloudPortalTokenAuthContextKey = "CloudPortalTokenAuth.Scopes" + CloudTokenAuthScopes cloudTokenAuthContextKey = "CloudTokenAuth.Scopes" +) + +// Defines values for AddonInstanceType. +const ( + AddonInstanceTypeMultiple AddonInstanceType = "multiple" + AddonInstanceTypeSingle AddonInstanceType = "single" +) + +// Valid indicates whether the value is a known member of the AddonInstanceType enum. +func (e AddonInstanceType) Valid() bool { + switch e { + case AddonInstanceTypeMultiple: + return true + case AddonInstanceTypeSingle: + return true + default: + return false + } +} + +// Defines values for AddonOrderBy. +const ( + AddonOrderByCreatedAt AddonOrderBy = "created_at" + AddonOrderById AddonOrderBy = "id" + AddonOrderByKey AddonOrderBy = "key" + AddonOrderByUpdatedAt AddonOrderBy = "updated_at" + AddonOrderByVersion AddonOrderBy = "version" +) + +// Valid indicates whether the value is a known member of the AddonOrderBy enum. +func (e AddonOrderBy) Valid() bool { + switch e { + case AddonOrderByCreatedAt: + return true + case AddonOrderById: + return true + case AddonOrderByKey: + return true + case AddonOrderByUpdatedAt: + return true + case AddonOrderByVersion: + return true + default: + return false + } +} + +// Defines values for AddonStatus. +const ( + AddonStatusActive AddonStatus = "active" + AddonStatusArchived AddonStatus = "archived" + AddonStatusDraft AddonStatus = "draft" +) + +// Valid indicates whether the value is a known member of the AddonStatus enum. +func (e AddonStatus) Valid() bool { + switch e { + case AddonStatusActive: + return true + case AddonStatusArchived: + return true + case AddonStatusDraft: + return true + default: + return false + } +} + +// Defines values for AppCapabilityType. +const ( + AppCapabilityTypeCalculateTax AppCapabilityType = "calculateTax" + AppCapabilityTypeCollectPayments AppCapabilityType = "collectPayments" + AppCapabilityTypeInvoiceCustomers AppCapabilityType = "invoiceCustomers" + AppCapabilityTypeReportEvents AppCapabilityType = "reportEvents" + AppCapabilityTypeReportUsage AppCapabilityType = "reportUsage" +) + +// Valid indicates whether the value is a known member of the AppCapabilityType enum. +func (e AppCapabilityType) Valid() bool { + switch e { + case AppCapabilityTypeCalculateTax: + return true + case AppCapabilityTypeCollectPayments: + return true + case AppCapabilityTypeInvoiceCustomers: + return true + case AppCapabilityTypeReportEvents: + return true + case AppCapabilityTypeReportUsage: + return true + default: + return false + } +} + +// Defines values for AppStatus. +const ( + AppStatusReady AppStatus = "ready" + AppStatusUnauthorized AppStatus = "unauthorized" +) + +// Valid indicates whether the value is a known member of the AppStatus enum. +func (e AppStatus) Valid() bool { + switch e { + case AppStatusReady: + return true + case AppStatusUnauthorized: + return true + default: + return false + } +} + +// Defines values for AppType. +const ( + AppTypeCustomInvoicing AppType = "custom_invoicing" + AppTypeSandbox AppType = "sandbox" + AppTypeStripe AppType = "stripe" +) + +// Valid indicates whether the value is a known member of the AppType enum. +func (e AppType) Valid() bool { + switch e { + case AppTypeCustomInvoicing: + return true + case AppTypeSandbox: + return true + case AppTypeStripe: + return true + default: + return false + } +} + +// Defines values for BillingProfileCustomerOverrideExpand. +const ( + BillingProfileCustomerOverrideExpandApps BillingProfileCustomerOverrideExpand = "apps" + BillingProfileCustomerOverrideExpandCustomer BillingProfileCustomerOverrideExpand = "customer" +) + +// Valid indicates whether the value is a known member of the BillingProfileCustomerOverrideExpand enum. +func (e BillingProfileCustomerOverrideExpand) Valid() bool { + switch e { + case BillingProfileCustomerOverrideExpandApps: + return true + case BillingProfileCustomerOverrideExpandCustomer: + return true + default: + return false + } +} + +// Defines values for BillingProfileCustomerOverrideOrderBy. +const ( + BillingProfileCustomerOverrideOrderByCustomerCreatedAt BillingProfileCustomerOverrideOrderBy = "customerCreatedAt" + BillingProfileCustomerOverrideOrderByCustomerId BillingProfileCustomerOverrideOrderBy = "customerId" + BillingProfileCustomerOverrideOrderByCustomerKey BillingProfileCustomerOverrideOrderBy = "customerKey" + BillingProfileCustomerOverrideOrderByCustomerName BillingProfileCustomerOverrideOrderBy = "customerName" + BillingProfileCustomerOverrideOrderByCustomerPrimaryEmail BillingProfileCustomerOverrideOrderBy = "customerPrimaryEmail" +) + +// Valid indicates whether the value is a known member of the BillingProfileCustomerOverrideOrderBy enum. +func (e BillingProfileCustomerOverrideOrderBy) Valid() bool { + switch e { + case BillingProfileCustomerOverrideOrderByCustomerCreatedAt: + return true + case BillingProfileCustomerOverrideOrderByCustomerId: + return true + case BillingProfileCustomerOverrideOrderByCustomerKey: + return true + case BillingProfileCustomerOverrideOrderByCustomerName: + return true + case BillingProfileCustomerOverrideOrderByCustomerPrimaryEmail: + return true + default: + return false + } +} + +// Defines values for BillingProfileExpand. +const ( + BillingProfileExpandApps BillingProfileExpand = "apps" +) + +// Valid indicates whether the value is a known member of the BillingProfileExpand enum. +func (e BillingProfileExpand) Valid() bool { + switch e { + case BillingProfileExpandApps: + return true + default: + return false + } +} + +// Defines values for BillingProfileOrderBy. +const ( + BillingProfileOrderByCreatedAt BillingProfileOrderBy = "createdAt" + BillingProfileOrderByDefault BillingProfileOrderBy = "default" + BillingProfileOrderByName BillingProfileOrderBy = "name" + BillingProfileOrderByUpdatedAt BillingProfileOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the BillingProfileOrderBy enum. +func (e BillingProfileOrderBy) Valid() bool { + switch e { + case BillingProfileOrderByCreatedAt: + return true + case BillingProfileOrderByDefault: + return true + case BillingProfileOrderByName: + return true + case BillingProfileOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for BillingSettlementMode. +const ( + BillingSettlementModeCreditOnly BillingSettlementMode = "credit_only" + BillingSettlementModeCreditThenInvoice BillingSettlementMode = "credit_then_invoice" +) + +// Valid indicates whether the value is a known member of the BillingSettlementMode enum. +func (e BillingSettlementMode) Valid() bool { + switch e { + case BillingSettlementModeCreditOnly: + return true + case BillingSettlementModeCreditThenInvoice: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowCollectionAlignmentAnchoredType. +const ( + BillingWorkflowCollectionAlignmentAnchoredTypeAnchored BillingWorkflowCollectionAlignmentAnchoredType = "anchored" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowCollectionAlignmentAnchoredType enum. +func (e BillingWorkflowCollectionAlignmentAnchoredType) Valid() bool { + switch e { + case BillingWorkflowCollectionAlignmentAnchoredTypeAnchored: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowCollectionAlignmentSubscriptionType. +const ( + BillingWorkflowCollectionAlignmentSubscriptionTypeSubscription BillingWorkflowCollectionAlignmentSubscriptionType = "subscription" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowCollectionAlignmentSubscriptionType enum. +func (e BillingWorkflowCollectionAlignmentSubscriptionType) Valid() bool { + switch e { + case BillingWorkflowCollectionAlignmentSubscriptionTypeSubscription: + return true + default: + return false + } +} + +// Defines values for BillingWorkflowInvoicingSubscriptionEndProrationMode. +const ( + BillingWorkflowInvoicingSubscriptionEndProrationModeBillActualPeriod BillingWorkflowInvoicingSubscriptionEndProrationMode = "bill_actual_period" + BillingWorkflowInvoicingSubscriptionEndProrationModeBillFullPeriod BillingWorkflowInvoicingSubscriptionEndProrationMode = "bill_full_period" +) + +// Valid indicates whether the value is a known member of the BillingWorkflowInvoicingSubscriptionEndProrationMode enum. +func (e BillingWorkflowInvoicingSubscriptionEndProrationMode) Valid() bool { + switch e { + case BillingWorkflowInvoicingSubscriptionEndProrationModeBillActualPeriod: + return true + case BillingWorkflowInvoicingSubscriptionEndProrationModeBillFullPeriod: + return true + default: + return false + } +} + +// Defines values for CheckoutSessionUIMode. +const ( + CheckoutSessionUIModeEmbedded CheckoutSessionUIMode = "embedded" + CheckoutSessionUIModeHosted CheckoutSessionUIMode = "hosted" +) + +// Valid indicates whether the value is a known member of the CheckoutSessionUIMode enum. +func (e CheckoutSessionUIMode) Valid() bool { + switch e { + case CheckoutSessionUIModeEmbedded: + return true + case CheckoutSessionUIModeHosted: + return true + default: + return false + } +} + +// Defines values for CollectionMethod. +const ( + CollectionMethodChargeAutomatically CollectionMethod = "charge_automatically" + CollectionMethodSendInvoice CollectionMethod = "send_invoice" +) + +// Valid indicates whether the value is a known member of the CollectionMethod enum. +func (e CollectionMethod) Valid() bool { + switch e { + case CollectionMethodChargeAutomatically: + return true + case CollectionMethodSendInvoice: + return true + default: + return false + } +} + +// Defines values for CreateCheckoutSessionTaxIdCollectionRequired. +const ( + CreateCheckoutSessionTaxIdCollectionRequiredIfSupported CreateCheckoutSessionTaxIdCollectionRequired = "if_supported" + CreateCheckoutSessionTaxIdCollectionRequiredNever CreateCheckoutSessionTaxIdCollectionRequired = "never" +) + +// Valid indicates whether the value is a known member of the CreateCheckoutSessionTaxIdCollectionRequired enum. +func (e CreateCheckoutSessionTaxIdCollectionRequired) Valid() bool { + switch e { + case CreateCheckoutSessionTaxIdCollectionRequiredIfSupported: + return true + case CreateCheckoutSessionTaxIdCollectionRequiredNever: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionBillingAddressCollection. +const ( + CreateStripeCheckoutSessionBillingAddressCollectionAuto CreateStripeCheckoutSessionBillingAddressCollection = "auto" + CreateStripeCheckoutSessionBillingAddressCollectionRequired CreateStripeCheckoutSessionBillingAddressCollection = "required" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionBillingAddressCollection enum. +func (e CreateStripeCheckoutSessionBillingAddressCollection) Valid() bool { + switch e { + case CreateStripeCheckoutSessionBillingAddressCollectionAuto: + return true + case CreateStripeCheckoutSessionBillingAddressCollectionRequired: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition. +const ( + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionAuto CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "auto" + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionHidden CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = "hidden" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition enum. +func (e CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition) Valid() bool { + switch e { + case CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionAuto: + return true + case CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionHidden: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionConsentCollectionPromotions. +const ( + CreateStripeCheckoutSessionConsentCollectionPromotionsAuto CreateStripeCheckoutSessionConsentCollectionPromotions = "auto" + CreateStripeCheckoutSessionConsentCollectionPromotionsNone CreateStripeCheckoutSessionConsentCollectionPromotions = "none" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionConsentCollectionPromotions enum. +func (e CreateStripeCheckoutSessionConsentCollectionPromotions) Valid() bool { + switch e { + case CreateStripeCheckoutSessionConsentCollectionPromotionsAuto: + return true + case CreateStripeCheckoutSessionConsentCollectionPromotionsNone: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionConsentCollectionTermsOfService. +const ( + CreateStripeCheckoutSessionConsentCollectionTermsOfServiceNone CreateStripeCheckoutSessionConsentCollectionTermsOfService = "none" + CreateStripeCheckoutSessionConsentCollectionTermsOfServiceRequired CreateStripeCheckoutSessionConsentCollectionTermsOfService = "required" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionConsentCollectionTermsOfService enum. +func (e CreateStripeCheckoutSessionConsentCollectionTermsOfService) Valid() bool { + switch e { + case CreateStripeCheckoutSessionConsentCollectionTermsOfServiceNone: + return true + case CreateStripeCheckoutSessionConsentCollectionTermsOfServiceRequired: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionCustomerUpdateBehavior. +const ( + CreateStripeCheckoutSessionCustomerUpdateBehaviorAuto CreateStripeCheckoutSessionCustomerUpdateBehavior = "auto" + CreateStripeCheckoutSessionCustomerUpdateBehaviorNever CreateStripeCheckoutSessionCustomerUpdateBehavior = "never" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionCustomerUpdateBehavior enum. +func (e CreateStripeCheckoutSessionCustomerUpdateBehavior) Valid() bool { + switch e { + case CreateStripeCheckoutSessionCustomerUpdateBehaviorAuto: + return true + case CreateStripeCheckoutSessionCustomerUpdateBehaviorNever: + return true + default: + return false + } +} + +// Defines values for CreateStripeCheckoutSessionRedirectOnCompletion. +const ( + CreateStripeCheckoutSessionRedirectOnCompletionAlways CreateStripeCheckoutSessionRedirectOnCompletion = "always" + CreateStripeCheckoutSessionRedirectOnCompletionIfRequired CreateStripeCheckoutSessionRedirectOnCompletion = "if_required" + CreateStripeCheckoutSessionRedirectOnCompletionNever CreateStripeCheckoutSessionRedirectOnCompletion = "never" +) + +// Valid indicates whether the value is a known member of the CreateStripeCheckoutSessionRedirectOnCompletion enum. +func (e CreateStripeCheckoutSessionRedirectOnCompletion) Valid() bool { + switch e { + case CreateStripeCheckoutSessionRedirectOnCompletionAlways: + return true + case CreateStripeCheckoutSessionRedirectOnCompletionIfRequired: + return true + case CreateStripeCheckoutSessionRedirectOnCompletionNever: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingAppType. +const ( + CustomInvoicingAppTypeCustomInvoicing CustomInvoicingAppType = "custom_invoicing" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingAppType enum. +func (e CustomInvoicingAppType) Valid() bool { + switch e { + case CustomInvoicingAppTypeCustomInvoicing: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingAppReplaceUpdateType. +const ( + CustomInvoicingAppReplaceUpdateTypeCustomInvoicing CustomInvoicingAppReplaceUpdateType = "custom_invoicing" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingAppReplaceUpdateType enum. +func (e CustomInvoicingAppReplaceUpdateType) Valid() bool { + switch e { + case CustomInvoicingAppReplaceUpdateTypeCustomInvoicing: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingCustomerAppDataType. +const ( + CustomInvoicingCustomerAppDataTypeCustomInvoicing CustomInvoicingCustomerAppDataType = "custom_invoicing" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingCustomerAppDataType enum. +func (e CustomInvoicingCustomerAppDataType) Valid() bool { + switch e { + case CustomInvoicingCustomerAppDataTypeCustomInvoicing: + return true + default: + return false + } +} + +// Defines values for CustomInvoicingPaymentTrigger. +const ( + CustomInvoicingPaymentTriggerActionRequired CustomInvoicingPaymentTrigger = "action_required" + CustomInvoicingPaymentTriggerPaid CustomInvoicingPaymentTrigger = "paid" + CustomInvoicingPaymentTriggerPaymentFailed CustomInvoicingPaymentTrigger = "payment_failed" + CustomInvoicingPaymentTriggerPaymentOverdue CustomInvoicingPaymentTrigger = "payment_overdue" + CustomInvoicingPaymentTriggerPaymentUncollectible CustomInvoicingPaymentTrigger = "payment_uncollectible" + CustomInvoicingPaymentTriggerVoid CustomInvoicingPaymentTrigger = "void" +) + +// Valid indicates whether the value is a known member of the CustomInvoicingPaymentTrigger enum. +func (e CustomInvoicingPaymentTrigger) Valid() bool { + switch e { + case CustomInvoicingPaymentTriggerActionRequired: + return true + case CustomInvoicingPaymentTriggerPaid: + return true + case CustomInvoicingPaymentTriggerPaymentFailed: + return true + case CustomInvoicingPaymentTriggerPaymentOverdue: + return true + case CustomInvoicingPaymentTriggerPaymentUncollectible: + return true + case CustomInvoicingPaymentTriggerVoid: + return true + default: + return false + } +} + +// Defines values for CustomerExpand. +const ( + CustomerExpandSubscriptions CustomerExpand = "subscriptions" +) + +// Valid indicates whether the value is a known member of the CustomerExpand enum. +func (e CustomerExpand) Valid() bool { + switch e { + case CustomerExpandSubscriptions: + return true + default: + return false + } +} + +// Defines values for CustomerOrderBy. +const ( + CustomerOrderByCreatedAt CustomerOrderBy = "createdAt" + CustomerOrderById CustomerOrderBy = "id" + CustomerOrderByName CustomerOrderBy = "name" +) + +// Valid indicates whether the value is a known member of the CustomerOrderBy enum. +func (e CustomerOrderBy) Valid() bool { + switch e { + case CustomerOrderByCreatedAt: + return true + case CustomerOrderById: + return true + case CustomerOrderByName: + return true + default: + return false + } +} + +// Defines values for CustomerSubscriptionOrderBy. +const ( + CustomerSubscriptionOrderByActiveFrom CustomerSubscriptionOrderBy = "activeFrom" + CustomerSubscriptionOrderByActiveTo CustomerSubscriptionOrderBy = "activeTo" +) + +// Valid indicates whether the value is a known member of the CustomerSubscriptionOrderBy enum. +func (e CustomerSubscriptionOrderBy) Valid() bool { + switch e { + case CustomerSubscriptionOrderByActiveFrom: + return true + case CustomerSubscriptionOrderByActiveTo: + return true + default: + return false + } +} + +// Defines values for DiscountReasonMaximumSpendType. +const ( + DiscountReasonMaximumSpendTypeMaximumSpend DiscountReasonMaximumSpendType = "maximum_spend" +) + +// Valid indicates whether the value is a known member of the DiscountReasonMaximumSpendType enum. +func (e DiscountReasonMaximumSpendType) Valid() bool { + switch e { + case DiscountReasonMaximumSpendTypeMaximumSpend: + return true + default: + return false + } +} + +// Defines values for DiscountReasonRatecardPercentageType. +const ( + DiscountReasonRatecardPercentageTypeRatecardPercentage DiscountReasonRatecardPercentageType = "ratecard_percentage" +) + +// Valid indicates whether the value is a known member of the DiscountReasonRatecardPercentageType enum. +func (e DiscountReasonRatecardPercentageType) Valid() bool { + switch e { + case DiscountReasonRatecardPercentageTypeRatecardPercentage: + return true + default: + return false + } +} + +// Defines values for DiscountReasonRatecardUsageType. +const ( + DiscountReasonRatecardUsageTypeRatecardUsage DiscountReasonRatecardUsageType = "ratecard_usage" +) + +// Valid indicates whether the value is a known member of the DiscountReasonRatecardUsageType enum. +func (e DiscountReasonRatecardUsageType) Valid() bool { + switch e { + case DiscountReasonRatecardUsageTypeRatecardUsage: + return true + default: + return false + } +} + +// Defines values for DynamicPriceWithCommitmentsType. +const ( + DynamicPriceWithCommitmentsTypeDynamic DynamicPriceWithCommitmentsType = "dynamic" +) + +// Valid indicates whether the value is a known member of the DynamicPriceWithCommitmentsType enum. +func (e DynamicPriceWithCommitmentsType) Valid() bool { + switch e { + case DynamicPriceWithCommitmentsTypeDynamic: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionAddItemOp. +const ( + EditSubscriptionAddItemOpAddItem EditSubscriptionAddItemOp = "add_item" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionAddItemOp enum. +func (e EditSubscriptionAddItemOp) Valid() bool { + switch e { + case EditSubscriptionAddItemOpAddItem: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionAddPhaseOp. +const ( + EditSubscriptionAddPhaseOpAddPhase EditSubscriptionAddPhaseOp = "add_phase" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionAddPhaseOp enum. +func (e EditSubscriptionAddPhaseOp) Valid() bool { + switch e { + case EditSubscriptionAddPhaseOpAddPhase: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionRemoveItemOp. +const ( + EditSubscriptionRemoveItemOpRemoveItem EditSubscriptionRemoveItemOp = "remove_item" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionRemoveItemOp enum. +func (e EditSubscriptionRemoveItemOp) Valid() bool { + switch e { + case EditSubscriptionRemoveItemOpRemoveItem: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionRemovePhaseOp. +const ( + EditSubscriptionRemovePhaseOpRemovePhase EditSubscriptionRemovePhaseOp = "remove_phase" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionRemovePhaseOp enum. +func (e EditSubscriptionRemovePhaseOp) Valid() bool { + switch e { + case EditSubscriptionRemovePhaseOpRemovePhase: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionStretchPhaseOp. +const ( + EditSubscriptionStretchPhaseOpStretchPhase EditSubscriptionStretchPhaseOp = "stretch_phase" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionStretchPhaseOp enum. +func (e EditSubscriptionStretchPhaseOp) Valid() bool { + switch e { + case EditSubscriptionStretchPhaseOpStretchPhase: + return true + default: + return false + } +} + +// Defines values for EditSubscriptionUnscheduleEditOp. +const ( + EditSubscriptionUnscheduleEditOpUnscheduleEdit EditSubscriptionUnscheduleEditOp = "unschedule_edit" +) + +// Valid indicates whether the value is a known member of the EditSubscriptionUnscheduleEditOp enum. +func (e EditSubscriptionUnscheduleEditOp) Valid() bool { + switch e { + case EditSubscriptionUnscheduleEditOpUnscheduleEdit: + return true + default: + return false + } +} + +// Defines values for EntitlementBooleanType. +const ( + EntitlementBooleanTypeBoolean EntitlementBooleanType = "boolean" +) + +// Valid indicates whether the value is a known member of the EntitlementBooleanType enum. +func (e EntitlementBooleanType) Valid() bool { + switch e { + case EntitlementBooleanTypeBoolean: + return true + default: + return false + } +} + +// Defines values for EntitlementBooleanCreateInputsType. +const ( + EntitlementBooleanCreateInputsTypeBoolean EntitlementBooleanCreateInputsType = "boolean" +) + +// Valid indicates whether the value is a known member of the EntitlementBooleanCreateInputsType enum. +func (e EntitlementBooleanCreateInputsType) Valid() bool { + switch e { + case EntitlementBooleanCreateInputsTypeBoolean: + return true + default: + return false + } +} + +// Defines values for EntitlementBooleanV2Type. +const ( + EntitlementBooleanV2TypeBoolean EntitlementBooleanV2Type = "boolean" +) + +// Valid indicates whether the value is a known member of the EntitlementBooleanV2Type enum. +func (e EntitlementBooleanV2Type) Valid() bool { + switch e { + case EntitlementBooleanV2TypeBoolean: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredType. +const ( + EntitlementMeteredTypeMetered EntitlementMeteredType = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredType enum. +func (e EntitlementMeteredType) Valid() bool { + switch e { + case EntitlementMeteredTypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredCreateInputsType. +const ( + EntitlementMeteredCreateInputsTypeMetered EntitlementMeteredCreateInputsType = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredCreateInputsType enum. +func (e EntitlementMeteredCreateInputsType) Valid() bool { + switch e { + case EntitlementMeteredCreateInputsTypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredV2Type. +const ( + EntitlementMeteredV2TypeMetered EntitlementMeteredV2Type = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredV2Type enum. +func (e EntitlementMeteredV2Type) Valid() bool { + switch e { + case EntitlementMeteredV2TypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementMeteredV2CreateInputsType. +const ( + EntitlementMeteredV2CreateInputsTypeMetered EntitlementMeteredV2CreateInputsType = "metered" +) + +// Valid indicates whether the value is a known member of the EntitlementMeteredV2CreateInputsType enum. +func (e EntitlementMeteredV2CreateInputsType) Valid() bool { + switch e { + case EntitlementMeteredV2CreateInputsTypeMetered: + return true + default: + return false + } +} + +// Defines values for EntitlementOrderBy. +const ( + EntitlementOrderByCreatedAt EntitlementOrderBy = "createdAt" + EntitlementOrderByUpdatedAt EntitlementOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the EntitlementOrderBy enum. +func (e EntitlementOrderBy) Valid() bool { + switch e { + case EntitlementOrderByCreatedAt: + return true + case EntitlementOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for EntitlementStaticType. +const ( + EntitlementStaticTypeStatic EntitlementStaticType = "static" +) + +// Valid indicates whether the value is a known member of the EntitlementStaticType enum. +func (e EntitlementStaticType) Valid() bool { + switch e { + case EntitlementStaticTypeStatic: + return true + default: + return false + } +} + +// Defines values for EntitlementStaticCreateInputsType. +const ( + EntitlementStaticCreateInputsTypeStatic EntitlementStaticCreateInputsType = "static" +) + +// Valid indicates whether the value is a known member of the EntitlementStaticCreateInputsType enum. +func (e EntitlementStaticCreateInputsType) Valid() bool { + switch e { + case EntitlementStaticCreateInputsTypeStatic: + return true + default: + return false + } +} + +// Defines values for EntitlementStaticV2Type. +const ( + EntitlementStaticV2TypeStatic EntitlementStaticV2Type = "static" +) + +// Valid indicates whether the value is a known member of the EntitlementStaticV2Type enum. +func (e EntitlementStaticV2Type) Valid() bool { + switch e { + case EntitlementStaticV2TypeStatic: + return true + default: + return false + } +} + +// Defines values for ExpirationDuration. +const ( + ExpirationDurationDAY ExpirationDuration = "DAY" + ExpirationDurationHOUR ExpirationDuration = "HOUR" + ExpirationDurationMONTH ExpirationDuration = "MONTH" + ExpirationDurationWEEK ExpirationDuration = "WEEK" + ExpirationDurationYEAR ExpirationDuration = "YEAR" +) + +// Valid indicates whether the value is a known member of the ExpirationDuration enum. +func (e ExpirationDuration) Valid() bool { + switch e { + case ExpirationDurationDAY: + return true + case ExpirationDurationHOUR: + return true + case ExpirationDurationMONTH: + return true + case ExpirationDurationWEEK: + return true + case ExpirationDurationYEAR: + return true + default: + return false + } +} + +// Defines values for FeatureLLMUnitCostType. +const ( + FeatureLLMUnitCostTypeLlm FeatureLLMUnitCostType = "llm" +) + +// Valid indicates whether the value is a known member of the FeatureLLMUnitCostType enum. +func (e FeatureLLMUnitCostType) Valid() bool { + switch e { + case FeatureLLMUnitCostTypeLlm: + return true + default: + return false + } +} + +// Defines values for FeatureManualUnitCostType. +const ( + FeatureManualUnitCostTypeManual FeatureManualUnitCostType = "manual" +) + +// Valid indicates whether the value is a known member of the FeatureManualUnitCostType enum. +func (e FeatureManualUnitCostType) Valid() bool { + switch e { + case FeatureManualUnitCostTypeManual: + return true + default: + return false + } +} + +// Defines values for FeatureOrderBy. +const ( + FeatureOrderByCreatedAt FeatureOrderBy = "createdAt" + FeatureOrderById FeatureOrderBy = "id" + FeatureOrderByKey FeatureOrderBy = "key" + FeatureOrderByName FeatureOrderBy = "name" + FeatureOrderByUpdatedAt FeatureOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the FeatureOrderBy enum. +func (e FeatureOrderBy) Valid() bool { + switch e { + case FeatureOrderByCreatedAt: + return true + case FeatureOrderById: + return true + case FeatureOrderByKey: + return true + case FeatureOrderByName: + return true + case FeatureOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for FlatPriceType. +const ( + FlatPriceTypeFlat FlatPriceType = "flat" +) + +// Valid indicates whether the value is a known member of the FlatPriceType enum. +func (e FlatPriceType) Valid() bool { + switch e { + case FlatPriceTypeFlat: + return true + default: + return false + } +} + +// Defines values for FlatPriceWithPaymentTermType. +const ( + FlatPriceWithPaymentTermTypeFlat FlatPriceWithPaymentTermType = "flat" +) + +// Valid indicates whether the value is a known member of the FlatPriceWithPaymentTermType enum. +func (e FlatPriceWithPaymentTermType) Valid() bool { + switch e { + case FlatPriceWithPaymentTermTypeFlat: + return true + default: + return false + } +} + +// Defines values for GrantOrderBy. +const ( + GrantOrderByCreatedAt GrantOrderBy = "createdAt" + GrantOrderById GrantOrderBy = "id" + GrantOrderByUpdatedAt GrantOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the GrantOrderBy enum. +func (e GrantOrderBy) Valid() bool { + switch e { + case GrantOrderByCreatedAt: + return true + case GrantOrderById: + return true + case GrantOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for InstallMethod. +const ( + InstallMethodNoCredentialsRequired InstallMethod = "no_credentials_required" + InstallMethodWithApiKey InstallMethod = "with_api_key" + InstallMethodWithOauth2 InstallMethod = "with_oauth2" +) + +// Valid indicates whether the value is a known member of the InstallMethod enum. +func (e InstallMethod) Valid() bool { + switch e { + case InstallMethodNoCredentialsRequired: + return true + case InstallMethodWithApiKey: + return true + case InstallMethodWithOauth2: + return true + default: + return false + } +} + +// Defines values for InvoiceDetailedLineType. +const ( + InvoiceDetailedLineTypeFlatFee InvoiceDetailedLineType = "flat_fee" +) + +// Valid indicates whether the value is a known member of the InvoiceDetailedLineType enum. +func (e InvoiceDetailedLineType) Valid() bool { + switch e { + case InvoiceDetailedLineTypeFlatFee: + return true + default: + return false + } +} + +// Defines values for InvoiceDetailedLineCostCategory. +const ( + InvoiceDetailedLineCostCategoryCommitment InvoiceDetailedLineCostCategory = "commitment" + InvoiceDetailedLineCostCategoryRegular InvoiceDetailedLineCostCategory = "regular" +) + +// Valid indicates whether the value is a known member of the InvoiceDetailedLineCostCategory enum. +func (e InvoiceDetailedLineCostCategory) Valid() bool { + switch e { + case InvoiceDetailedLineCostCategoryCommitment: + return true + case InvoiceDetailedLineCostCategoryRegular: + return true + default: + return false + } +} + +// Defines values for InvoiceDocumentRefType. +const ( + InvoiceDocumentRefTypeCreditNoteOriginalInvoice InvoiceDocumentRefType = "credit_note_original_invoice" +) + +// Valid indicates whether the value is a known member of the InvoiceDocumentRefType enum. +func (e InvoiceDocumentRefType) Valid() bool { + switch e { + case InvoiceDocumentRefTypeCreditNoteOriginalInvoice: + return true + default: + return false + } +} + +// Defines values for InvoiceExpand. +const ( + InvoiceExpandLines InvoiceExpand = "lines" + InvoiceExpandPreceding InvoiceExpand = "preceding" + InvoiceExpandWorkflowApps InvoiceExpand = "workflow.apps" +) + +// Valid indicates whether the value is a known member of the InvoiceExpand enum. +func (e InvoiceExpand) Valid() bool { + switch e { + case InvoiceExpandLines: + return true + case InvoiceExpandPreceding: + return true + case InvoiceExpandWorkflowApps: + return true + default: + return false + } +} + +// Defines values for InvoiceLineType. +const ( + InvoiceLineTypeUsageBased InvoiceLineType = "usage_based" +) + +// Valid indicates whether the value is a known member of the InvoiceLineType enum. +func (e InvoiceLineType) Valid() bool { + switch e { + case InvoiceLineTypeUsageBased: + return true + default: + return false + } +} + +// Defines values for InvoiceLineManagedBy. +const ( + InvoiceLineManagedByManual InvoiceLineManagedBy = "manual" + InvoiceLineManagedBySubscription InvoiceLineManagedBy = "subscription" + InvoiceLineManagedBySystem InvoiceLineManagedBy = "system" +) + +// Valid indicates whether the value is a known member of the InvoiceLineManagedBy enum. +func (e InvoiceLineManagedBy) Valid() bool { + switch e { + case InvoiceLineManagedByManual: + return true + case InvoiceLineManagedBySubscription: + return true + case InvoiceLineManagedBySystem: + return true + default: + return false + } +} + +// Defines values for InvoiceLineStatus. +const ( + InvoiceLineStatusDetailed InvoiceLineStatus = "detailed" + InvoiceLineStatusSplit InvoiceLineStatus = "split" + InvoiceLineStatusValid InvoiceLineStatus = "valid" +) + +// Valid indicates whether the value is a known member of the InvoiceLineStatus enum. +func (e InvoiceLineStatus) Valid() bool { + switch e { + case InvoiceLineStatusDetailed: + return true + case InvoiceLineStatusSplit: + return true + case InvoiceLineStatusValid: + return true + default: + return false + } +} + +// Defines values for InvoiceLineTaxBehavior. +const ( + InvoiceLineTaxBehaviorExclusive InvoiceLineTaxBehavior = "exclusive" + InvoiceLineTaxBehaviorInclusive InvoiceLineTaxBehavior = "inclusive" +) + +// Valid indicates whether the value is a known member of the InvoiceLineTaxBehavior enum. +func (e InvoiceLineTaxBehavior) Valid() bool { + switch e { + case InvoiceLineTaxBehaviorExclusive: + return true + case InvoiceLineTaxBehaviorInclusive: + return true + default: + return false + } +} + +// Defines values for InvoiceOrderBy. +const ( + InvoiceOrderByCreatedAt InvoiceOrderBy = "createdAt" + InvoiceOrderByCustomerName InvoiceOrderBy = "customer.name" + InvoiceOrderByIssuedAt InvoiceOrderBy = "issuedAt" + InvoiceOrderByPeriodStart InvoiceOrderBy = "periodStart" + InvoiceOrderByStatus InvoiceOrderBy = "status" + InvoiceOrderByUpdatedAt InvoiceOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the InvoiceOrderBy enum. +func (e InvoiceOrderBy) Valid() bool { + switch e { + case InvoiceOrderByCreatedAt: + return true + case InvoiceOrderByCustomerName: + return true + case InvoiceOrderByIssuedAt: + return true + case InvoiceOrderByPeriodStart: + return true + case InvoiceOrderByStatus: + return true + case InvoiceOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for InvoiceStatus. +const ( + InvoiceStatusDraft InvoiceStatus = "draft" + InvoiceStatusGathering InvoiceStatus = "gathering" + InvoiceStatusIssued InvoiceStatus = "issued" + InvoiceStatusIssuing InvoiceStatus = "issuing" + InvoiceStatusOverdue InvoiceStatus = "overdue" + InvoiceStatusPaid InvoiceStatus = "paid" + InvoiceStatusPaymentProcessing InvoiceStatus = "payment_processing" + InvoiceStatusUncollectible InvoiceStatus = "uncollectible" + InvoiceStatusVoided InvoiceStatus = "voided" +) + +// Valid indicates whether the value is a known member of the InvoiceStatus enum. +func (e InvoiceStatus) Valid() bool { + switch e { + case InvoiceStatusDraft: + return true + case InvoiceStatusGathering: + return true + case InvoiceStatusIssued: + return true + case InvoiceStatusIssuing: + return true + case InvoiceStatusOverdue: + return true + case InvoiceStatusPaid: + return true + case InvoiceStatusPaymentProcessing: + return true + case InvoiceStatusUncollectible: + return true + case InvoiceStatusVoided: + return true + default: + return false + } +} + +// Defines values for InvoiceType. +const ( + InvoiceTypeCreditNote InvoiceType = "credit_note" + InvoiceTypeStandard InvoiceType = "standard" +) + +// Valid indicates whether the value is a known member of the InvoiceType enum. +func (e InvoiceType) Valid() bool { + switch e { + case InvoiceTypeCreditNote: + return true + case InvoiceTypeStandard: + return true + default: + return false + } +} + +// Defines values for MeasureUsageFromPreset. +const ( + MeasureUsageFromPresetCurrentPeriodStart MeasureUsageFromPreset = "CURRENT_PERIOD_START" + MeasureUsageFromPresetNow MeasureUsageFromPreset = "NOW" +) + +// Valid indicates whether the value is a known member of the MeasureUsageFromPreset enum. +func (e MeasureUsageFromPreset) Valid() bool { + switch e { + case MeasureUsageFromPresetCurrentPeriodStart: + return true + case MeasureUsageFromPresetNow: + return true + default: + return false + } +} + +// Defines values for MeterAggregation. +const ( + MeterAggregationAvg MeterAggregation = "AVG" + MeterAggregationCount MeterAggregation = "COUNT" + MeterAggregationLatest MeterAggregation = "LATEST" + MeterAggregationMax MeterAggregation = "MAX" + MeterAggregationMin MeterAggregation = "MIN" + MeterAggregationSum MeterAggregation = "SUM" + MeterAggregationUniqueCount MeterAggregation = "UNIQUE_COUNT" +) + +// Valid indicates whether the value is a known member of the MeterAggregation enum. +func (e MeterAggregation) Valid() bool { + switch e { + case MeterAggregationAvg: + return true + case MeterAggregationCount: + return true + case MeterAggregationLatest: + return true + case MeterAggregationMax: + return true + case MeterAggregationMin: + return true + case MeterAggregationSum: + return true + case MeterAggregationUniqueCount: + return true + default: + return false + } +} + +// Defines values for MeterOrderBy. +const ( + MeterOrderByAggregation MeterOrderBy = "aggregation" + MeterOrderByCreatedAt MeterOrderBy = "createdAt" + MeterOrderByKey MeterOrderBy = "key" + MeterOrderByName MeterOrderBy = "name" + MeterOrderByUpdatedAt MeterOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the MeterOrderBy enum. +func (e MeterOrderBy) Valid() bool { + switch e { + case MeterOrderByAggregation: + return true + case MeterOrderByCreatedAt: + return true + case MeterOrderByKey: + return true + case MeterOrderByName: + return true + case MeterOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for NotificationChannelOrderBy. +const ( + NotificationChannelOrderByCreatedAt NotificationChannelOrderBy = "createdAt" + NotificationChannelOrderById NotificationChannelOrderBy = "id" + NotificationChannelOrderByType NotificationChannelOrderBy = "type" + NotificationChannelOrderByUpdatedAt NotificationChannelOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the NotificationChannelOrderBy enum. +func (e NotificationChannelOrderBy) Valid() bool { + switch e { + case NotificationChannelOrderByCreatedAt: + return true + case NotificationChannelOrderById: + return true + case NotificationChannelOrderByType: + return true + case NotificationChannelOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for NotificationChannelType. +const ( + NotificationChannelTypeWebhook NotificationChannelType = "WEBHOOK" +) + +// Valid indicates whether the value is a known member of the NotificationChannelType enum. +func (e NotificationChannelType) Valid() bool { + switch e { + case NotificationChannelTypeWebhook: + return true + default: + return false + } +} + +// Defines values for NotificationChannelWebhookType. +const ( + NotificationChannelWebhookTypeWEBHOOK NotificationChannelWebhookType = "WEBHOOK" +) + +// Valid indicates whether the value is a known member of the NotificationChannelWebhookType enum. +func (e NotificationChannelWebhookType) Valid() bool { + switch e { + case NotificationChannelWebhookTypeWEBHOOK: + return true + default: + return false + } +} + +// Defines values for NotificationChannelWebhookCreateRequestType. +const ( + NotificationChannelWebhookCreateRequestTypeWEBHOOK NotificationChannelWebhookCreateRequestType = "WEBHOOK" +) + +// Valid indicates whether the value is a known member of the NotificationChannelWebhookCreateRequestType enum. +func (e NotificationChannelWebhookCreateRequestType) Valid() bool { + switch e { + case NotificationChannelWebhookCreateRequestTypeWEBHOOK: + return true + default: + return false + } +} + +// Defines values for NotificationEventBalanceThresholdPayloadType. +const ( + NotificationEventBalanceThresholdPayloadTypeEntitlementsBalanceThreshold NotificationEventBalanceThresholdPayloadType = "entitlements.balance.threshold" +) + +// Valid indicates whether the value is a known member of the NotificationEventBalanceThresholdPayloadType enum. +func (e NotificationEventBalanceThresholdPayloadType) Valid() bool { + switch e { + case NotificationEventBalanceThresholdPayloadTypeEntitlementsBalanceThreshold: + return true + default: + return false + } +} + +// Defines values for NotificationEventDeliveryStatusState. +const ( + NotificationEventDeliveryStatusStateFailed NotificationEventDeliveryStatusState = "FAILED" + NotificationEventDeliveryStatusStatePending NotificationEventDeliveryStatusState = "PENDING" + NotificationEventDeliveryStatusStateResending NotificationEventDeliveryStatusState = "RESENDING" + NotificationEventDeliveryStatusStateSending NotificationEventDeliveryStatusState = "SENDING" + NotificationEventDeliveryStatusStateSuccess NotificationEventDeliveryStatusState = "SUCCESS" +) + +// Valid indicates whether the value is a known member of the NotificationEventDeliveryStatusState enum. +func (e NotificationEventDeliveryStatusState) Valid() bool { + switch e { + case NotificationEventDeliveryStatusStateFailed: + return true + case NotificationEventDeliveryStatusStatePending: + return true + case NotificationEventDeliveryStatusStateResending: + return true + case NotificationEventDeliveryStatusStateSending: + return true + case NotificationEventDeliveryStatusStateSuccess: + return true + default: + return false + } +} + +// Defines values for NotificationEventInvoiceCreatedPayloadType. +const ( + NotificationEventInvoiceCreatedPayloadTypeInvoiceCreated NotificationEventInvoiceCreatedPayloadType = "invoice.created" +) + +// Valid indicates whether the value is a known member of the NotificationEventInvoiceCreatedPayloadType enum. +func (e NotificationEventInvoiceCreatedPayloadType) Valid() bool { + switch e { + case NotificationEventInvoiceCreatedPayloadTypeInvoiceCreated: + return true + default: + return false + } +} + +// Defines values for NotificationEventInvoiceUpdatedPayloadType. +const ( + NotificationEventInvoiceUpdatedPayloadTypeInvoiceUpdated NotificationEventInvoiceUpdatedPayloadType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationEventInvoiceUpdatedPayloadType enum. +func (e NotificationEventInvoiceUpdatedPayloadType) Valid() bool { + switch e { + case NotificationEventInvoiceUpdatedPayloadTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationEventOrderBy. +const ( + NotificationEventOrderByCreatedAt NotificationEventOrderBy = "createdAt" + NotificationEventOrderById NotificationEventOrderBy = "id" +) + +// Valid indicates whether the value is a known member of the NotificationEventOrderBy enum. +func (e NotificationEventOrderBy) Valid() bool { + switch e { + case NotificationEventOrderByCreatedAt: + return true + case NotificationEventOrderById: + return true + default: + return false + } +} + +// Defines values for NotificationEventResetPayloadType. +const ( + NotificationEventResetPayloadTypeEntitlementsReset NotificationEventResetPayloadType = "entitlements.reset" +) + +// Valid indicates whether the value is a known member of the NotificationEventResetPayloadType enum. +func (e NotificationEventResetPayloadType) Valid() bool { + switch e { + case NotificationEventResetPayloadTypeEntitlementsReset: + return true + default: + return false + } +} + +// Defines values for NotificationEventType. +const ( + NotificationEventTypeEntitlementsBalanceThreshold NotificationEventType = "entitlements.balance.threshold" + NotificationEventTypeEntitlementsReset NotificationEventType = "entitlements.reset" + NotificationEventTypeInvoiceCreated NotificationEventType = "invoice.created" + NotificationEventTypeInvoiceUpdated NotificationEventType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationEventType enum. +func (e NotificationEventType) Valid() bool { + switch e { + case NotificationEventTypeEntitlementsBalanceThreshold: + return true + case NotificationEventTypeEntitlementsReset: + return true + case NotificationEventTypeInvoiceCreated: + return true + case NotificationEventTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleBalanceThresholdType. +const ( + NotificationRuleBalanceThresholdTypeEntitlementsBalanceThreshold NotificationRuleBalanceThresholdType = "entitlements.balance.threshold" +) + +// Valid indicates whether the value is a known member of the NotificationRuleBalanceThresholdType enum. +func (e NotificationRuleBalanceThresholdType) Valid() bool { + switch e { + case NotificationRuleBalanceThresholdTypeEntitlementsBalanceThreshold: + return true + default: + return false + } +} + +// Defines values for NotificationRuleBalanceThresholdCreateRequestType. +const ( + NotificationRuleBalanceThresholdCreateRequestTypeEntitlementsBalanceThreshold NotificationRuleBalanceThresholdCreateRequestType = "entitlements.balance.threshold" +) + +// Valid indicates whether the value is a known member of the NotificationRuleBalanceThresholdCreateRequestType enum. +func (e NotificationRuleBalanceThresholdCreateRequestType) Valid() bool { + switch e { + case NotificationRuleBalanceThresholdCreateRequestTypeEntitlementsBalanceThreshold: + return true + default: + return false + } +} + +// Defines values for NotificationRuleBalanceThresholdValueType. +const ( + NotificationRuleBalanceThresholdValueTypeBalanceValue NotificationRuleBalanceThresholdValueType = "balance_value" + NotificationRuleBalanceThresholdValueTypeNumber NotificationRuleBalanceThresholdValueType = "NUMBER" + NotificationRuleBalanceThresholdValueTypePercent NotificationRuleBalanceThresholdValueType = "PERCENT" + NotificationRuleBalanceThresholdValueTypeUsagePercentage NotificationRuleBalanceThresholdValueType = "usage_percentage" + NotificationRuleBalanceThresholdValueTypeUsageValue NotificationRuleBalanceThresholdValueType = "usage_value" +) + +// Valid indicates whether the value is a known member of the NotificationRuleBalanceThresholdValueType enum. +func (e NotificationRuleBalanceThresholdValueType) Valid() bool { + switch e { + case NotificationRuleBalanceThresholdValueTypeBalanceValue: + return true + case NotificationRuleBalanceThresholdValueTypeNumber: + return true + case NotificationRuleBalanceThresholdValueTypePercent: + return true + case NotificationRuleBalanceThresholdValueTypeUsagePercentage: + return true + case NotificationRuleBalanceThresholdValueTypeUsageValue: + return true + default: + return false + } +} + +// Defines values for NotificationRuleEntitlementResetType. +const ( + NotificationRuleEntitlementResetTypeEntitlementsReset NotificationRuleEntitlementResetType = "entitlements.reset" +) + +// Valid indicates whether the value is a known member of the NotificationRuleEntitlementResetType enum. +func (e NotificationRuleEntitlementResetType) Valid() bool { + switch e { + case NotificationRuleEntitlementResetTypeEntitlementsReset: + return true + default: + return false + } +} + +// Defines values for NotificationRuleEntitlementResetCreateRequestType. +const ( + NotificationRuleEntitlementResetCreateRequestTypeEntitlementsReset NotificationRuleEntitlementResetCreateRequestType = "entitlements.reset" +) + +// Valid indicates whether the value is a known member of the NotificationRuleEntitlementResetCreateRequestType enum. +func (e NotificationRuleEntitlementResetCreateRequestType) Valid() bool { + switch e { + case NotificationRuleEntitlementResetCreateRequestTypeEntitlementsReset: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceCreatedType. +const ( + NotificationRuleInvoiceCreatedTypeInvoiceCreated NotificationRuleInvoiceCreatedType = "invoice.created" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceCreatedType enum. +func (e NotificationRuleInvoiceCreatedType) Valid() bool { + switch e { + case NotificationRuleInvoiceCreatedTypeInvoiceCreated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceCreatedCreateRequestType. +const ( + NotificationRuleInvoiceCreatedCreateRequestTypeInvoiceCreated NotificationRuleInvoiceCreatedCreateRequestType = "invoice.created" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceCreatedCreateRequestType enum. +func (e NotificationRuleInvoiceCreatedCreateRequestType) Valid() bool { + switch e { + case NotificationRuleInvoiceCreatedCreateRequestTypeInvoiceCreated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceUpdatedType. +const ( + NotificationRuleInvoiceUpdatedTypeInvoiceUpdated NotificationRuleInvoiceUpdatedType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceUpdatedType enum. +func (e NotificationRuleInvoiceUpdatedType) Valid() bool { + switch e { + case NotificationRuleInvoiceUpdatedTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleInvoiceUpdatedCreateRequestType. +const ( + NotificationRuleInvoiceUpdatedCreateRequestTypeInvoiceUpdated NotificationRuleInvoiceUpdatedCreateRequestType = "invoice.updated" +) + +// Valid indicates whether the value is a known member of the NotificationRuleInvoiceUpdatedCreateRequestType enum. +func (e NotificationRuleInvoiceUpdatedCreateRequestType) Valid() bool { + switch e { + case NotificationRuleInvoiceUpdatedCreateRequestTypeInvoiceUpdated: + return true + default: + return false + } +} + +// Defines values for NotificationRuleOrderBy. +const ( + NotificationRuleOrderByCreatedAt NotificationRuleOrderBy = "createdAt" + NotificationRuleOrderById NotificationRuleOrderBy = "id" + NotificationRuleOrderByType NotificationRuleOrderBy = "type" + NotificationRuleOrderByUpdatedAt NotificationRuleOrderBy = "updatedAt" +) + +// Valid indicates whether the value is a known member of the NotificationRuleOrderBy enum. +func (e NotificationRuleOrderBy) Valid() bool { + switch e { + case NotificationRuleOrderByCreatedAt: + return true + case NotificationRuleOrderById: + return true + case NotificationRuleOrderByType: + return true + case NotificationRuleOrderByUpdatedAt: + return true + default: + return false + } +} + +// Defines values for OAuth2AuthorizationCodeGrantErrorType. +const ( + OAuth2AuthorizationCodeGrantErrorTypeAccessDenied OAuth2AuthorizationCodeGrantErrorType = "access_denied" + OAuth2AuthorizationCodeGrantErrorTypeInvalidRequest OAuth2AuthorizationCodeGrantErrorType = "invalid_request" + OAuth2AuthorizationCodeGrantErrorTypeInvalidScope OAuth2AuthorizationCodeGrantErrorType = "invalid_scope" + OAuth2AuthorizationCodeGrantErrorTypeServerError OAuth2AuthorizationCodeGrantErrorType = "server_error" + OAuth2AuthorizationCodeGrantErrorTypeTemporarilyUnavailable OAuth2AuthorizationCodeGrantErrorType = "temporarily_unavailable" + OAuth2AuthorizationCodeGrantErrorTypeUnauthorizedClient OAuth2AuthorizationCodeGrantErrorType = "unauthorized_client" + OAuth2AuthorizationCodeGrantErrorTypeUnsupportedResponseType OAuth2AuthorizationCodeGrantErrorType = "unsupported_response_type" +) + +// Valid indicates whether the value is a known member of the OAuth2AuthorizationCodeGrantErrorType enum. +func (e OAuth2AuthorizationCodeGrantErrorType) Valid() bool { + switch e { + case OAuth2AuthorizationCodeGrantErrorTypeAccessDenied: + return true + case OAuth2AuthorizationCodeGrantErrorTypeInvalidRequest: + return true + case OAuth2AuthorizationCodeGrantErrorTypeInvalidScope: + return true + case OAuth2AuthorizationCodeGrantErrorTypeServerError: + return true + case OAuth2AuthorizationCodeGrantErrorTypeTemporarilyUnavailable: + return true + case OAuth2AuthorizationCodeGrantErrorTypeUnauthorizedClient: + return true + case OAuth2AuthorizationCodeGrantErrorTypeUnsupportedResponseType: + return true + default: + return false + } +} + +// Defines values for PackagePriceWithCommitmentsType. +const ( + PackagePriceWithCommitmentsTypePackage PackagePriceWithCommitmentsType = "package" +) + +// Valid indicates whether the value is a known member of the PackagePriceWithCommitmentsType enum. +func (e PackagePriceWithCommitmentsType) Valid() bool { + switch e { + case PackagePriceWithCommitmentsTypePackage: + return true + default: + return false + } +} + +// Defines values for PaymentTermDueDateType. +const ( + PaymentTermDueDateTypeDueDate PaymentTermDueDateType = "due_date" +) + +// Valid indicates whether the value is a known member of the PaymentTermDueDateType enum. +func (e PaymentTermDueDateType) Valid() bool { + switch e { + case PaymentTermDueDateTypeDueDate: + return true + default: + return false + } +} + +// Defines values for PaymentTermInstantType. +const ( + PaymentTermInstantTypeInstant PaymentTermInstantType = "instant" +) + +// Valid indicates whether the value is a known member of the PaymentTermInstantType enum. +func (e PaymentTermInstantType) Valid() bool { + switch e { + case PaymentTermInstantTypeInstant: + return true + default: + return false + } +} + +// Defines values for PlanAddonOrderBy. +const ( + PlanAddonOrderByCreatedAt PlanAddonOrderBy = "created_at" + PlanAddonOrderById PlanAddonOrderBy = "id" + PlanAddonOrderByKey PlanAddonOrderBy = "key" + PlanAddonOrderByUpdatedAt PlanAddonOrderBy = "updated_at" + PlanAddonOrderByVersion PlanAddonOrderBy = "version" +) + +// Valid indicates whether the value is a known member of the PlanAddonOrderBy enum. +func (e PlanAddonOrderBy) Valid() bool { + switch e { + case PlanAddonOrderByCreatedAt: + return true + case PlanAddonOrderById: + return true + case PlanAddonOrderByKey: + return true + case PlanAddonOrderByUpdatedAt: + return true + case PlanAddonOrderByVersion: + return true + default: + return false + } +} + +// Defines values for PlanOrderBy. +const ( + PlanOrderByCreatedAt PlanOrderBy = "created_at" + PlanOrderById PlanOrderBy = "id" + PlanOrderByKey PlanOrderBy = "key" + PlanOrderByUpdatedAt PlanOrderBy = "updated_at" + PlanOrderByVersion PlanOrderBy = "version" +) + +// Valid indicates whether the value is a known member of the PlanOrderBy enum. +func (e PlanOrderBy) Valid() bool { + switch e { + case PlanOrderByCreatedAt: + return true + case PlanOrderById: + return true + case PlanOrderByKey: + return true + case PlanOrderByUpdatedAt: + return true + case PlanOrderByVersion: + return true + default: + return false + } +} + +// Defines values for PlanStatus. +const ( + PlanStatusActive PlanStatus = "active" + PlanStatusArchived PlanStatus = "archived" + PlanStatusDraft PlanStatus = "draft" + PlanStatusScheduled PlanStatus = "scheduled" +) + +// Valid indicates whether the value is a known member of the PlanStatus enum. +func (e PlanStatus) Valid() bool { + switch e { + case PlanStatusActive: + return true + case PlanStatusArchived: + return true + case PlanStatusDraft: + return true + case PlanStatusScheduled: + return true + default: + return false + } +} + +// Defines values for PricePaymentTerm. +const ( + PricePaymentTermInAdvance PricePaymentTerm = "in_advance" + PricePaymentTermInArrears PricePaymentTerm = "in_arrears" +) + +// Valid indicates whether the value is a known member of the PricePaymentTerm enum. +func (e PricePaymentTerm) Valid() bool { + switch e { + case PricePaymentTermInAdvance: + return true + case PricePaymentTermInArrears: + return true + default: + return false + } +} + +// Defines values for ProRatingMode. +const ( + ProRatingModeProratePrices ProRatingMode = "prorate_prices" +) + +// Valid indicates whether the value is a known member of the ProRatingMode enum. +func (e ProRatingMode) Valid() bool { + switch e { + case ProRatingModeProratePrices: + return true + default: + return false + } +} + +// Defines values for RateCardBooleanEntitlementType. +const ( + RateCardBooleanEntitlementTypeBoolean RateCardBooleanEntitlementType = "boolean" +) + +// Valid indicates whether the value is a known member of the RateCardBooleanEntitlementType enum. +func (e RateCardBooleanEntitlementType) Valid() bool { + switch e { + case RateCardBooleanEntitlementTypeBoolean: + return true + default: + return false + } +} + +// Defines values for RateCardFlatFeeType. +const ( + RateCardFlatFeeTypeFlatFee RateCardFlatFeeType = "flat_fee" +) + +// Valid indicates whether the value is a known member of the RateCardFlatFeeType enum. +func (e RateCardFlatFeeType) Valid() bool { + switch e { + case RateCardFlatFeeTypeFlatFee: + return true + default: + return false + } +} + +// Defines values for RateCardMeteredEntitlementType. +const ( + RateCardMeteredEntitlementTypeMetered RateCardMeteredEntitlementType = "metered" +) + +// Valid indicates whether the value is a known member of the RateCardMeteredEntitlementType enum. +func (e RateCardMeteredEntitlementType) Valid() bool { + switch e { + case RateCardMeteredEntitlementTypeMetered: + return true + default: + return false + } +} + +// Defines values for RateCardStaticEntitlementType. +const ( + RateCardStaticEntitlementTypeStatic RateCardStaticEntitlementType = "static" +) + +// Valid indicates whether the value is a known member of the RateCardStaticEntitlementType enum. +func (e RateCardStaticEntitlementType) Valid() bool { + switch e { + case RateCardStaticEntitlementTypeStatic: + return true + default: + return false + } +} + +// Defines values for RateCardUsageBasedType. +const ( + RateCardUsageBasedTypeUsageBased RateCardUsageBasedType = "usage_based" +) + +// Valid indicates whether the value is a known member of the RateCardUsageBasedType enum. +func (e RateCardUsageBasedType) Valid() bool { + switch e { + case RateCardUsageBasedTypeUsageBased: + return true + default: + return false + } +} + +// Defines values for RecurringPeriodIntervalEnum. +const ( + RecurringPeriodIntervalEnumDAY RecurringPeriodIntervalEnum = "DAY" + RecurringPeriodIntervalEnumMONTH RecurringPeriodIntervalEnum = "MONTH" + RecurringPeriodIntervalEnumWEEK RecurringPeriodIntervalEnum = "WEEK" + RecurringPeriodIntervalEnumYEAR RecurringPeriodIntervalEnum = "YEAR" +) + +// Valid indicates whether the value is a known member of the RecurringPeriodIntervalEnum enum. +func (e RecurringPeriodIntervalEnum) Valid() bool { + switch e { + case RecurringPeriodIntervalEnumDAY: + return true + case RecurringPeriodIntervalEnumMONTH: + return true + case RecurringPeriodIntervalEnumWEEK: + return true + case RecurringPeriodIntervalEnumYEAR: + return true + default: + return false + } +} + +// Defines values for RemovePhaseShifting. +const ( + RemovePhaseShiftingNext RemovePhaseShifting = "next" + RemovePhaseShiftingPrev RemovePhaseShifting = "prev" +) + +// Valid indicates whether the value is a known member of the RemovePhaseShifting enum. +func (e RemovePhaseShifting) Valid() bool { + switch e { + case RemovePhaseShiftingNext: + return true + case RemovePhaseShiftingPrev: + return true + default: + return false + } +} + +// Defines values for SandboxAppType. +const ( + SandboxAppTypeSandbox SandboxAppType = "sandbox" +) + +// Valid indicates whether the value is a known member of the SandboxAppType enum. +func (e SandboxAppType) Valid() bool { + switch e { + case SandboxAppTypeSandbox: + return true + default: + return false + } +} + +// Defines values for SandboxAppReplaceUpdateType. +const ( + SandboxAppReplaceUpdateTypeSandbox SandboxAppReplaceUpdateType = "sandbox" +) + +// Valid indicates whether the value is a known member of the SandboxAppReplaceUpdateType enum. +func (e SandboxAppReplaceUpdateType) Valid() bool { + switch e { + case SandboxAppReplaceUpdateTypeSandbox: + return true + default: + return false + } +} + +// Defines values for SandboxCustomerAppDataType. +const ( + SandboxCustomerAppDataTypeSandbox SandboxCustomerAppDataType = "sandbox" +) + +// Valid indicates whether the value is a known member of the SandboxCustomerAppDataType enum. +func (e SandboxCustomerAppDataType) Valid() bool { + switch e { + case SandboxCustomerAppDataTypeSandbox: + return true + default: + return false + } +} + +// Defines values for SortOrder. +const ( + SortOrderASC SortOrder = "ASC" + SortOrderDESC SortOrder = "DESC" +) + +// Valid indicates whether the value is a known member of the SortOrder enum. +func (e SortOrder) Valid() bool { + switch e { + case SortOrderASC: + return true + case SortOrderDESC: + return true + default: + return false + } +} + +// Defines values for StripeAppType. +const ( + StripeAppTypeStripe StripeAppType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeAppType enum. +func (e StripeAppType) Valid() bool { + switch e { + case StripeAppTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeAppReplaceUpdateType. +const ( + StripeAppReplaceUpdateTypeStripe StripeAppReplaceUpdateType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeAppReplaceUpdateType enum. +func (e StripeAppReplaceUpdateType) Valid() bool { + switch e { + case StripeAppReplaceUpdateTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeCheckoutSessionMode. +const ( + StripeCheckoutSessionModeSetup StripeCheckoutSessionMode = "setup" +) + +// Valid indicates whether the value is a known member of the StripeCheckoutSessionMode enum. +func (e StripeCheckoutSessionMode) Valid() bool { + switch e { + case StripeCheckoutSessionModeSetup: + return true + default: + return false + } +} + +// Defines values for StripeCustomerAppDataType. +const ( + StripeCustomerAppDataTypeStripe StripeCustomerAppDataType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeCustomerAppDataType enum. +func (e StripeCustomerAppDataType) Valid() bool { + switch e { + case StripeCustomerAppDataTypeStripe: + return true + default: + return false + } +} + +// Defines values for StripeCustomerAppDataCreateOrUpdateItemType. +const ( + StripeCustomerAppDataCreateOrUpdateItemTypeStripe StripeCustomerAppDataCreateOrUpdateItemType = "stripe" +) + +// Valid indicates whether the value is a known member of the StripeCustomerAppDataCreateOrUpdateItemType enum. +func (e StripeCustomerAppDataCreateOrUpdateItemType) Valid() bool { + switch e { + case StripeCustomerAppDataCreateOrUpdateItemTypeStripe: + return true + default: + return false + } +} + +// Defines values for SubscriptionStatus. +const ( + SubscriptionStatusActive SubscriptionStatus = "active" + SubscriptionStatusCanceled SubscriptionStatus = "canceled" + SubscriptionStatusInactive SubscriptionStatus = "inactive" + SubscriptionStatusScheduled SubscriptionStatus = "scheduled" +) + +// Valid indicates whether the value is a known member of the SubscriptionStatus enum. +func (e SubscriptionStatus) Valid() bool { + switch e { + case SubscriptionStatusActive: + return true + case SubscriptionStatusCanceled: + return true + case SubscriptionStatusInactive: + return true + case SubscriptionStatusScheduled: + return true + default: + return false + } +} + +// Defines values for SubscriptionTimingEnum. +const ( + SubscriptionTimingEnumImmediate SubscriptionTimingEnum = "immediate" + SubscriptionTimingEnumNextBillingCycle SubscriptionTimingEnum = "next_billing_cycle" +) + +// Valid indicates whether the value is a known member of the SubscriptionTimingEnum enum. +func (e SubscriptionTimingEnum) Valid() bool { + switch e { + case SubscriptionTimingEnumImmediate: + return true + case SubscriptionTimingEnumNextBillingCycle: + return true + default: + return false + } +} + +// Defines values for TaxBehavior. +const ( + TaxBehaviorExclusive TaxBehavior = "exclusive" + TaxBehaviorInclusive TaxBehavior = "inclusive" +) + +// Valid indicates whether the value is a known member of the TaxBehavior enum. +func (e TaxBehavior) Valid() bool { + switch e { + case TaxBehaviorExclusive: + return true + case TaxBehaviorInclusive: + return true + default: + return false + } +} + +// Defines values for TieredPriceMode. +const ( + TieredPriceModeGraduated TieredPriceMode = "graduated" + TieredPriceModeVolume TieredPriceMode = "volume" +) + +// Valid indicates whether the value is a known member of the TieredPriceMode enum. +func (e TieredPriceMode) Valid() bool { + switch e { + case TieredPriceModeGraduated: + return true + case TieredPriceModeVolume: + return true + default: + return false + } +} + +// Defines values for TieredPriceWithCommitmentsType. +const ( + TieredPriceWithCommitmentsTypeTiered TieredPriceWithCommitmentsType = "tiered" +) + +// Valid indicates whether the value is a known member of the TieredPriceWithCommitmentsType enum. +func (e TieredPriceWithCommitmentsType) Valid() bool { + switch e { + case TieredPriceWithCommitmentsTypeTiered: + return true + default: + return false + } +} + +// Defines values for UnitPriceType. +const ( + UnitPriceTypeUnit UnitPriceType = "unit" +) + +// Valid indicates whether the value is a known member of the UnitPriceType enum. +func (e UnitPriceType) Valid() bool { + switch e { + case UnitPriceTypeUnit: + return true + default: + return false + } +} + +// Defines values for UnitPriceWithCommitmentsType. +const ( + UnitPriceWithCommitmentsTypeUnit UnitPriceWithCommitmentsType = "unit" +) + +// Valid indicates whether the value is a known member of the UnitPriceWithCommitmentsType enum. +func (e UnitPriceWithCommitmentsType) Valid() bool { + switch e { + case UnitPriceWithCommitmentsTypeUnit: + return true + default: + return false + } +} + +// Defines values for ValidationIssueSeverity. +const ( + ValidationIssueSeverityCritical ValidationIssueSeverity = "critical" + ValidationIssueSeverityWarning ValidationIssueSeverity = "warning" +) + +// Valid indicates whether the value is a known member of the ValidationIssueSeverity enum. +func (e ValidationIssueSeverity) Valid() bool { + switch e { + case ValidationIssueSeverityCritical: + return true + case ValidationIssueSeverityWarning: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLineDiscardActionType. +const ( + VoidInvoiceLineDiscardActionTypeDiscard VoidInvoiceLineDiscardActionType = "discard" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLineDiscardActionType enum. +func (e VoidInvoiceLineDiscardActionType) Valid() bool { + switch e { + case VoidInvoiceLineDiscardActionTypeDiscard: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLinePendingActionCreateType. +const ( + VoidInvoiceLinePendingActionCreateTypePending VoidInvoiceLinePendingActionCreateType = "pending" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLinePendingActionCreateType enum. +func (e VoidInvoiceLinePendingActionCreateType) Valid() bool { + switch e { + case VoidInvoiceLinePendingActionCreateTypePending: + return true + default: + return false + } +} + +// Defines values for VoidInvoiceLinePendingActionCreateItemType. +const ( + VoidInvoiceLinePendingActionCreateItemTypePending VoidInvoiceLinePendingActionCreateItemType = "pending" +) + +// Valid indicates whether the value is a known member of the VoidInvoiceLinePendingActionCreateItemType enum. +func (e VoidInvoiceLinePendingActionCreateItemType) Valid() bool { + switch e { + case VoidInvoiceLinePendingActionCreateItemTypePending: + return true + default: + return false + } +} + +// Defines values for WindowSize. +const ( + WindowSizeDay WindowSize = "DAY" + WindowSizeHour WindowSize = "HOUR" + WindowSizeMinute WindowSize = "MINUTE" + WindowSizeMonth WindowSize = "MONTH" +) + +// Valid indicates whether the value is a known member of the WindowSize enum. +func (e WindowSize) Valid() bool { + switch e { + case WindowSizeDay: + return true + case WindowSizeHour: + return true + case WindowSizeMinute: + return true + case WindowSizeMonth: + return true + default: + return false + } +} + +// Addon Add-on allows extending subscriptions with compatible plans with additional ratecards. +type Addon struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the add-on. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EffectiveFrom The date and time when the add-on becomes effective. When not specified, the add-on is a draft. + EffectiveFrom *time.Time `json:"effectiveFrom,omitempty"` + + // EffectiveTo The date and time when the add-on is no longer effective. When not specified, the add-on is effective indefinitely. + EffectiveTo *time.Time `json:"effectiveTo,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // InstanceType The instanceType of the add-ons. Can be "single" or "multiple". + InstanceType AddonInstanceType `json:"instanceType"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the add-on. + RateCards []RateCard `json:"rateCards"` + + // Status The status of the add-on. + // Computed based on the effective start and end dates: + // - draft = no effectiveFrom + // - active = effectiveFrom <= now < effectiveTo + // - archived = effectiveTo <= now + Status AddonStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationErrors List of validation errors. + ValidationErrors *[]ValidationError `json:"validationErrors"` + + // Version Version of the add-on. Incremented when the add-on is updated. + Version int `json:"version"` +} + +// AddonCreate Resource create operation model. +type AddonCreate struct { + // Currency The currency code of the add-on. + Currency CurrencyCode `json:"currency"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // InstanceType The instanceType of the add-ons. Can be "single" or "multiple". + InstanceType AddonInstanceType `json:"instanceType"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the add-on. + RateCards []RateCard `json:"rateCards"` +} + +// AddonInstanceType The instanceType of the add-on. +// Single instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once. +type AddonInstanceType string + +// AddonOrderBy Order by options for add-ons. +type AddonOrderBy string + +// AddonPaginatedResponse Paginated response +type AddonPaginatedResponse struct { + // Items The items in the current page. + Items []Addon `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// AddonReplaceUpdate Resource update operation model. +type AddonReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // InstanceType The instanceType of the add-ons. Can be "single" or "multiple". + InstanceType AddonInstanceType `json:"instanceType"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the add-on. + RateCards []RateCard `json:"rateCards"` +} + +// AddonStatus The status of the add-on defined by the effectiveFrom and effectiveTo properties. +type AddonStatus string + +// Address Address +type Address struct { + // City City. + City *string `json:"city,omitempty"` + + // Country Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format. + Country *CountryCode `json:"country,omitempty"` + + // Line1 First line of the address. + Line1 *string `json:"line1,omitempty"` + + // Line2 Second line of the address. + Line2 *string `json:"line2,omitempty"` + + // PhoneNumber Phone number. + PhoneNumber *string `json:"phoneNumber,omitempty"` + + // PostalCode Postal code. + PostalCode *string `json:"postalCode,omitempty"` + + // State State or province. + State *string `json:"state,omitempty"` +} + +// Alignment Alignment configuration for a plan or subscription. +type Alignment struct { + // BillablesMustAlign Whether all Billable items and RateCards must align. + // Alignment means the Price's BillingCadence must align for both duration and anchor time. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + BillablesMustAlign *bool `json:"billablesMustAlign,omitempty"` +} + +// Annotations Set of key-value pairs managed by the system. Cannot be modified by user. +type Annotations map[string]interface{} + +// App App. +// One of: stripe +type App struct { + union json.RawMessage +} + +// AppCapability App capability. +// +// Capabilities only exist in config so they don't extend the Resource model. +type AppCapability struct { + // Description The capability description. + Description string `json:"description"` + + // Key Key + Key string `json:"key"` + + // Name The capability name. + Name string `json:"name"` + + // Type The capability type. + Type AppCapabilityType `json:"type"` +} + +// AppCapabilityType App capability type. +type AppCapabilityType string + +// AppPaginatedResponse Paginated response +type AppPaginatedResponse struct { + // Items The items in the current page. + Items []App `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// AppReference App reference +// +// Can be used as a short reference to an app if the full app object is not needed. +type AppReference struct { + // Id The ID of the app. + Id string `json:"id"` +} + +// AppReplaceUpdate App ReplaceUpdate Model +type AppReplaceUpdate struct { + union json.RawMessage +} + +// AppStatus App installed status. +type AppStatus string + +// AppType Type of the app. +type AppType string + +// BadRequestProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type BadRequestProblemResponse = UnexpectedProblemResponse + +// BalanceHistoryWindow The balance history window. +type BalanceHistoryWindow struct { + // BalanceAtStart The entitlement balance at the start of the period. + BalanceAtStart float64 `json:"balanceAtStart"` + + // Period A period with a start and end time. + Period Period `json:"period"` + + // Usage The total usage of the feature in the period. + Usage float64 `json:"usage"` +} + +// BillingCustomerProfile Customer specific merged profile. +// +// This profile is calculated from the customer override and the billing profile it references or the default. +// +// Thus this does not have any kind of resource fields, only the calculated values. +type BillingCustomerProfile struct { + // Apps The applications used by this billing profile. + // + // Expand settings govern if this includes the whole app object or just the ID references. + Apps BillingProfileAppsOrReference `json:"apps"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // Workflow The billing workflow settings for this profile + Workflow BillingWorkflow `json:"workflow"` +} + +// BillingDiscountPercentage A percentage discount. +type BillingDiscountPercentage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Percentage The percentage of the discount. + Percentage Percentage `json:"percentage"` +} + +// BillingDiscountReason The reason for the discount. +type BillingDiscountReason struct { + union json.RawMessage +} + +// BillingDiscountUsage A usage discount. +type BillingDiscountUsage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Quantity The quantity of the usage discount. + // + // Must be positive. + Quantity Numeric `json:"quantity"` +} + +// BillingDiscounts A discount by type. +type BillingDiscounts struct { + // Percentage The percentage discount. + Percentage *BillingDiscountPercentage `json:"percentage,omitempty"` + + // Usage The usage discount. + Usage *BillingDiscountUsage `json:"usage,omitempty"` +} + +// BillingInvoiceCustomerExtendedDetails BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the billing party details for invoices. +// +// These fields contain the OpenMeter specific details for the customer, that are not strictly required for the invoice itself. +type BillingInvoiceCustomerExtendedDetails struct { + // Addresses Regular post addresses for where information should be sent if needed. + Addresses *[]Address `json:"addresses,omitempty"` + + // Id Unique identifier for the party (if available) + Id *string `json:"id,omitempty"` + + // Key An optional unique key of the party (if available) + Key *string `json:"key,omitempty"` + + // Name Legal name or representation of the organization. + Name *string `json:"name,omitempty"` + + // TaxId The entity's legal ID code used for tax purposes. They may have + // other numbers, but we're only interested in those valid for tax purposes. + TaxId *BillingPartyTaxIdentity `json:"taxId,omitempty"` + + // UsageAttribution Mapping to attribute metered usage to the customer + UsageAttribution CustomerUsageAttribution `json:"usageAttribution"` +} + +// BillingParty Party represents a person or business entity. +type BillingParty struct { + // Addresses Regular post addresses for where information should be sent if needed. + Addresses *[]Address `json:"addresses,omitempty"` + + // Id Unique identifier for the party (if available) + Id *string `json:"id,omitempty"` + + // Key An optional unique key of the party (if available) + Key *string `json:"key,omitempty"` + + // Name Legal name or representation of the organization. + Name *string `json:"name,omitempty"` + + // TaxId The entity's legal ID code used for tax purposes. They may have + // other numbers, but we're only interested in those valid for tax purposes. + TaxId *BillingPartyTaxIdentity `json:"taxId,omitempty"` +} + +// BillingPartyReplaceUpdate Resource update operation model. +type BillingPartyReplaceUpdate struct { + // Addresses Regular post addresses for where information should be sent if needed. + Addresses *[]Address `json:"addresses,omitempty"` + + // Key An optional unique key of the party (if available) + Key *string `json:"key,omitempty"` + + // Name Legal name or representation of the organization. + Name *string `json:"name,omitempty"` + + // TaxId The entity's legal ID code used for tax purposes. They may have + // other numbers, but we're only interested in those valid for tax purposes. + TaxId *BillingPartyTaxIdentity `json:"taxId,omitempty"` +} + +// BillingPartyTaxIdentity Identity stores the details required to identify an entity for tax purposes in a specific country. +type BillingPartyTaxIdentity struct { + // Code Normalized tax code shown on the original identity document. + Code *BillingTaxIdentificationCode `json:"code,omitempty"` +} + +// BillingProfile BillingProfile represents a billing profile +type BillingProfile struct { + // Apps The applications used by this billing profile. + // + // Expand settings govern if this includes the whole app object or just the ID references. + Apps BillingProfileAppsOrReference `json:"apps"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Default Is this the default profile? + Default bool `json:"default"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // Workflow The billing workflow settings for this profile + Workflow BillingWorkflow `json:"workflow"` +} + +// BillingProfileAppReferences BillingProfileAppReferences represents the references (id, type) to the apps used by a billing profile +type BillingProfileAppReferences struct { + // Invoicing The invoicing app used for this workflow + Invoicing AppReference `json:"invoicing"` + + // Payment The payment app used for this workflow + Payment AppReference `json:"payment"` + + // Tax The tax app used for this workflow + Tax AppReference `json:"tax"` +} + +// BillingProfileApps BillingProfileApps represents the applications used by a billing profile +type BillingProfileApps struct { + // Invoicing The invoicing app used for this workflow + Invoicing App `json:"invoicing"` + + // Payment The payment app used for this workflow + Payment App `json:"payment"` + + // Tax The tax app used for this workflow + Tax App `json:"tax"` +} + +// BillingProfileAppsCreate BillingProfileAppsCreate represents the input for creating a billing profile's apps +type BillingProfileAppsCreate struct { + // Invoicing The invoicing app used for this workflow + Invoicing string `json:"invoicing"` + + // Payment The payment app used for this workflow + Payment string `json:"payment"` + + // Tax The tax app used for this workflow + Tax string `json:"tax"` +} + +// BillingProfileAppsOrReference ProfileAppsOrReference represents the union of ProfileApps and ProfileAppReferences +// for a billing profile. +type BillingProfileAppsOrReference struct { + union json.RawMessage +} + +// BillingProfileCreate BillingProfileCreate represents the input for creating a billing profile +type BillingProfileCreate struct { + // Apps The apps used by this billing profile. + Apps BillingProfileAppsCreate `json:"apps"` + + // Default Is this the default profile? + Default bool `json:"default"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // Workflow The billing workflow settings for this profile. + Workflow BillingWorkflowCreate `json:"workflow"` +} + +// BillingProfileCustomerOverride Customer override values. +type BillingProfileCustomerOverride struct { + // BillingProfileId The billing profile this override is associated with. + // + // If empty the default profile is looked up dynamically. + BillingProfileId *string `json:"billingProfileId,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CustomerId The customer id this override is associated with. + CustomerId string `json:"customerId"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// BillingProfileCustomerOverrideCreate Payload for creating a new or updating an existing customer override. +type BillingProfileCustomerOverrideCreate struct { + // BillingProfileId The billing profile this override is associated with. + // + // If not provided, the default billing profile is chosen if available. + BillingProfileId *string `json:"billingProfileId,omitempty"` +} + +// BillingProfileCustomerOverrideExpand CustomerOverrideExpand specifies the parts of the profile to expand. +type BillingProfileCustomerOverrideExpand string + +// BillingProfileCustomerOverrideOrderBy Order by options for customers. +type BillingProfileCustomerOverrideOrderBy string + +// BillingProfileCustomerOverrideWithDetails Customer specific workflow overrides. +type BillingProfileCustomerOverrideWithDetails struct { + // BaseBillingProfileId The billing profile the customerProfile is associated with at the time of query. + // + // customerOverride contains the explicit mapping set in the customer override object. If that is + // empty, then the baseBillingProfileId is the default profile. + BaseBillingProfileId string `json:"baseBillingProfileId"` + + // Customer The customer this override belongs to. + Customer *Customer `json:"customer,omitempty"` + + // CustomerOverride The customer override values. + // + // If empty the merged values are calculated based on the default profile. + CustomerOverride *BillingProfileCustomerOverride `json:"customerOverride,omitempty"` + + // CustomerProfile Merged billing profile with the customer specific overrides. + CustomerProfile *BillingCustomerProfile `json:"customerProfile,omitempty"` +} + +// BillingProfileCustomerOverrideWithDetailsPaginatedResponse Paginated response +type BillingProfileCustomerOverrideWithDetailsPaginatedResponse struct { + // Items The items in the current page. + Items []BillingProfileCustomerOverrideWithDetails `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// BillingProfileExpand BillingProfileExpand details what profile fields to expand +type BillingProfileExpand string + +// BillingProfileOrderBy BillingProfileOrderBy specifies the ordering options for profiles +type BillingProfileOrderBy string + +// BillingProfilePaginatedResponse Paginated response +type BillingProfilePaginatedResponse struct { + // Items The items in the current page. + Items []BillingProfile `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// BillingProfileReplaceUpdateWithWorkflow BillingProfileReplaceUpdate represents the input for updating a billing profile +// +// The apps field cannot be updated directly, if an app change is desired a new +// profile should be created. +type BillingProfileReplaceUpdateWithWorkflow struct { + // Default Is this the default profile? + Default bool `json:"default"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Supplier The name and contact information for the supplier this billing profile represents + Supplier BillingParty `json:"supplier"` + + // Workflow The billing workflow settings for this profile. + Workflow BillingWorkflow `json:"workflow"` +} + +// BillingSettlementMode The settlement mode of a plan. +// It determines how the billing system generates invoices and credits for the subscriptions using this plan. +// - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode. +// - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. +type BillingSettlementMode string + +// BillingTaxIdentificationCode TaxIdentificationCode is a normalized tax code shown on the original identity document. +type BillingTaxIdentificationCode = string + +// BillingWorkflow BillingWorkflow represents the settings for a billing workflow. +type BillingWorkflow struct { + // Collection The collection settings for this workflow + Collection *BillingWorkflowCollectionSettings `json:"collection,omitempty"` + + // Invoicing The invoicing settings for this workflow + Invoicing *BillingWorkflowInvoicingSettings `json:"invoicing,omitempty"` + + // Payment The payment settings for this workflow + Payment *BillingWorkflowPaymentSettings `json:"payment,omitempty"` + + // Tax The tax settings for this workflow + Tax *BillingWorkflowTaxSettings `json:"tax,omitempty"` +} + +// BillingWorkflowCollectionAlignment The alignment for collecting the pending line items into an invoice. +// +// Defaults to subscription, which means that we are to create a new invoice every time the +// a subscription period starts (for in advance items) or ends (for in arrears items). +type BillingWorkflowCollectionAlignment struct { + union json.RawMessage +} + +// BillingWorkflowCollectionAlignmentAnchored BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items +// into an invoice. +type BillingWorkflowCollectionAlignmentAnchored struct { + // RecurringPeriod The recurring period for the alignment. + RecurringPeriod RecurringPeriodV2 `json:"recurringPeriod"` + + // Type The type of alignment. + Type BillingWorkflowCollectionAlignmentAnchoredType `json:"type"` +} + +// BillingWorkflowCollectionAlignmentAnchoredType The type of alignment. +type BillingWorkflowCollectionAlignmentAnchoredType string + +// BillingWorkflowCollectionAlignmentSubscription BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items +// into an invoice. +type BillingWorkflowCollectionAlignmentSubscription struct { + // Type The type of alignment. + Type BillingWorkflowCollectionAlignmentSubscriptionType `json:"type"` +} + +// BillingWorkflowCollectionAlignmentSubscriptionType The type of alignment. +type BillingWorkflowCollectionAlignmentSubscriptionType string + +// BillingWorkflowCollectionSettings Workflow collection specifies how to collect the pending line items for an invoice +type BillingWorkflowCollectionSettings struct { + // Alignment The alignment for collecting the pending line items into an invoice. + Alignment *BillingWorkflowCollectionAlignment `json:"alignment,omitempty"` + + // Interval This grace period can be used to delay the collection of the pending line items specified in + // alignment. + // + // This is useful, in case of multiple subscriptions having slightly different billing periods. + Interval *string `json:"interval,omitempty"` +} + +// BillingWorkflowCreate Resource create operation model. +type BillingWorkflowCreate struct { + // Collection The collection settings for this workflow + Collection *BillingWorkflowCollectionSettings `json:"collection,omitempty"` + + // Invoicing The invoicing settings for this workflow + Invoicing *BillingWorkflowInvoicingSettings `json:"invoicing,omitempty"` + + // Payment The payment settings for this workflow + Payment *BillingWorkflowPaymentSettings `json:"payment,omitempty"` + + // Tax The tax settings for this workflow + Tax *BillingWorkflowTaxSettings `json:"tax,omitempty"` +} + +// BillingWorkflowInvoicingSettings BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow +type BillingWorkflowInvoicingSettings struct { + // AutoAdvance Whether to automatically issue the invoice after the draftPeriod has passed. + AutoAdvance *bool `json:"autoAdvance,omitempty"` + + // DefaultTaxConfig Default tax configuration to apply to the invoices. + // + // Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + // deprecated and can no longer be added or changed: the organization default tax code is + // used instead. Existing tax-code values may still be removed, and `behavior` remains + // fully supported. + DefaultTaxConfig *TaxConfig `json:"defaultTaxConfig,omitempty"` + + // DraftPeriod The period for the invoice to be kept in draft status for manual reviews. + DraftPeriod *string `json:"draftPeriod,omitempty"` + + // DueAfter The period after which the invoice is due. + // With some payment solutions it's only applicable for manual collection method. + DueAfter *string `json:"dueAfter,omitempty"` + + // ProgressiveBilling Should progressive billing be allowed for this workflow? + ProgressiveBilling *bool `json:"progressiveBilling,omitempty"` + + // SubscriptionEndProrationMode Controls how subscription-ending shortened service periods are billed. + SubscriptionEndProrationMode *BillingWorkflowInvoicingSubscriptionEndProrationMode `json:"subscriptionEndProrationMode,omitempty"` +} + +// BillingWorkflowInvoicingSubscriptionEndProrationMode Billing workflow subscription end proration mode. +type BillingWorkflowInvoicingSubscriptionEndProrationMode string + +// BillingWorkflowPaymentSettings BillingWorkflowPaymentSettings represents the payment settings for a billing workflow +type BillingWorkflowPaymentSettings struct { + // CollectionMethod The payment method for the invoice. + CollectionMethod *CollectionMethod `json:"collectionMethod,omitempty"` +} + +// BillingWorkflowTaxSettings BillingWorkflowTaxSettings represents the tax settings for a billing workflow +type BillingWorkflowTaxSettings struct { + // Enabled Enable automatic tax calculation when tax is supported by the app. + // For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + Enabled *bool `json:"enabled,omitempty"` + + // Enforced Enforce tax calculation when tax is supported by the app. + // When enabled, OpenMeter will not allow to create an invoice without tax calculation. + // Enforcement is different per apps, for example, Stripe app requires customer + // to have a tax location when starting a paid subscription. + Enforced *bool `json:"enforced,omitempty"` +} + +// CheckoutSessionCustomTextAfterSubmitParams Stripe CheckoutSession.custom_text +type CheckoutSessionCustomTextAfterSubmitParams struct { + // AfterSubmit Custom text that should be displayed after the payment confirmation button. + AfterSubmit *struct { + Message *string `json:"message,omitempty"` + } `json:"afterSubmit,omitempty"` + + // ShippingAddress Custom text that should be displayed alongside shipping address collection. + ShippingAddress *struct { + Message *string `json:"message,omitempty"` + } `json:"shippingAddress,omitempty"` + + // Submit Custom text that should be displayed alongside the payment confirmation button. + Submit *struct { + Message *string `json:"message,omitempty"` + } `json:"submit,omitempty"` + + // TermsOfServiceAcceptance Custom text that should be displayed in place of the default terms of service agreement text. + TermsOfServiceAcceptance *struct { + Message *string `json:"message,omitempty"` + } `json:"termsOfServiceAcceptance,omitempty"` +} + +// CheckoutSessionUIMode Stripe CheckoutSession.ui_mode +type CheckoutSessionUIMode string + +// ClientAppStartResponse Response from the client app (OpenMeter backend) to start the OAuth2 flow. +type ClientAppStartResponse struct { + // Url The URL to start the OAuth2 authorization code grant flow. + Url string `json:"url"` +} + +// CollectionMethod CollectionMethod specifies how the invoice should be collected (automatic vs manual) +type CollectionMethod string + +// ConflictProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type ConflictProblemResponse = UnexpectedProblemResponse + +// CountryCode [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. +// Custom two-letter country codes are also supported for convenience. +type CountryCode = string + +// CreateCheckoutSessionTaxIdCollection Create Stripe checkout session tax ID collection. +type CreateCheckoutSessionTaxIdCollection struct { + // Enabled Enable tax ID collection during checkout. Defaults to false. + Enabled bool `json:"enabled"` + + // Required Describes whether a tax ID is required during checkout. Defaults to never. + Required *CreateCheckoutSessionTaxIdCollectionRequired `json:"required,omitempty"` +} + +// CreateCheckoutSessionTaxIdCollectionRequired Create Stripe checkout session tax ID collection required. +type CreateCheckoutSessionTaxIdCollectionRequired string + +// CreateStripeCheckoutSessionBillingAddressCollection Specify whether Checkout should collect the customer’s billing address. +type CreateStripeCheckoutSessionBillingAddressCollection string + +// CreateStripeCheckoutSessionConsentCollection Configure fields for the Checkout Session to gather active consent from customers. +type CreateStripeCheckoutSessionConsentCollection struct { + // PaymentMethodReuseAgreement Determines the position and visibility of the payment method reuse agreement in the UI. + // When set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI. + PaymentMethodReuseAgreement *CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement `json:"paymentMethodReuseAgreement,omitempty"` + + // Promotions If set to auto, enables the collection of customer consent for promotional communications. + // The Checkout Session will determine whether to display an option to opt into promotional + // communication from the merchant depending on the customer’s locale. Only available to US merchants. + Promotions *CreateStripeCheckoutSessionConsentCollectionPromotions `json:"promotions,omitempty"` + + // TermsOfService If set to required, it requires customers to check a terms of service checkbox before being able to pay. + // There must be a valid terms of service URL set in your Stripe Dashboard settings. + // https://dashboard.stripe.com/settings/public + TermsOfService *CreateStripeCheckoutSessionConsentCollectionTermsOfService `json:"termsOfService,omitempty"` +} + +// CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement Create Stripe checkout session payment method reuse agreement. +type CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement struct { + // Position Create Stripe checkout session consent collection agreement position. + Position *CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition `json:"position,omitempty"` +} + +// CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition Create Stripe checkout session consent collection agreement position. +type CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition string + +// CreateStripeCheckoutSessionConsentCollectionPromotions Create Stripe checkout session consent collection promotions. +type CreateStripeCheckoutSessionConsentCollectionPromotions string + +// CreateStripeCheckoutSessionConsentCollectionTermsOfService Create Stripe checkout session consent collection terms of service. +type CreateStripeCheckoutSessionConsentCollectionTermsOfService string + +// CreateStripeCheckoutSessionCustomerUpdate Controls what fields on Customer can be updated by the Checkout Session. +type CreateStripeCheckoutSessionCustomerUpdate struct { + // Address Describes whether Checkout saves the billing address onto customer.address. + // To always collect a full billing address, use billing_address_collection. + // Defaults to never. + Address *CreateStripeCheckoutSessionCustomerUpdateBehavior `json:"address,omitempty"` + + // Name Describes whether Checkout saves the name onto customer.name. + // Defaults to never. + Name *CreateStripeCheckoutSessionCustomerUpdateBehavior `json:"name,omitempty"` + + // Shipping Describes whether Checkout saves shipping information onto customer.shipping. + // To collect shipping information, use shipping_address_collection. + // Defaults to never. + Shipping *CreateStripeCheckoutSessionCustomerUpdateBehavior `json:"shipping,omitempty"` +} + +// CreateStripeCheckoutSessionCustomerUpdateBehavior Create Stripe checkout session customer update behavior. +type CreateStripeCheckoutSessionCustomerUpdateBehavior string + +// CreateStripeCheckoutSessionRedirectOnCompletion Create Stripe checkout session redirect on completion. +type CreateStripeCheckoutSessionRedirectOnCompletion string + +// CreateStripeCheckoutSessionRequest Create Stripe checkout session request. +type CreateStripeCheckoutSessionRequest struct { + // AppId If not provided, the default Stripe app is used if any. + AppId *string `json:"appId,omitempty"` + + // Customer Provide a customer ID or key to use an existing OpenMeter customer. + // or provide a customer object to create a new customer. + Customer CreateStripeCheckoutSessionRequest_Customer `json:"customer"` + + // Options Options passed to Stripe when creating the checkout session. + Options CreateStripeCheckoutSessionRequestOptions `json:"options"` + + // StripeCustomerId Stripe customer ID. + // If not provided OpenMeter creates a new Stripe customer or + // uses the OpenMeter customer's default Stripe customer ID. + StripeCustomerId *string `json:"stripeCustomerId,omitempty"` +} + +// CreateStripeCheckoutSessionRequest_Customer Provide a customer ID or key to use an existing OpenMeter customer. +// or provide a customer object to create a new customer. +type CreateStripeCheckoutSessionRequest_Customer struct { + union json.RawMessage +} + +// CreateStripeCheckoutSessionRequestOptions Create Stripe checkout session options +// See https://docs.stripe.com/api/checkout/sessions/create +type CreateStripeCheckoutSessionRequestOptions struct { + // BillingAddressCollection Specify whether Checkout should collect the customer’s billing address. Defaults to auto. + BillingAddressCollection *CreateStripeCheckoutSessionBillingAddressCollection `json:"billingAddressCollection,omitempty"` + + // CancelURL If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + // This parameter is not allowed if ui_mode is embedded. + CancelURL *string `json:"cancelURL,omitempty"` + + // ClientReferenceID A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + ClientReferenceID *string `json:"clientReferenceID,omitempty"` + + // ConsentCollection Configure fields for the Checkout Session to gather active consent from customers. + ConsentCollection *CreateStripeCheckoutSessionConsentCollection `json:"consentCollection,omitempty"` + + // Currency Three-letter ISO currency code, in lowercase. + Currency *CurrencyCode `json:"currency,omitempty"` + + // CustomText Display additional text for your customers using custom text. + CustomText *CheckoutSessionCustomTextAfterSubmitParams `json:"customText,omitempty"` + + // CustomerUpdate Controls what fields on Customer can be updated by the Checkout Session. + CustomerUpdate *CreateStripeCheckoutSessionCustomerUpdate `json:"customerUpdate,omitempty"` + + // ExpiresAt The Epoch time in seconds at which the Checkout Session will expire. + // It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + ExpiresAt *int64 `json:"expiresAt,omitempty"` + Locale *string `json:"locale,omitempty"` + + // Metadata Set of key-value pairs that you can attach to an object. + // This can be useful for storing additional information about the object in a structured format. + // Individual keys can be unset by posting an empty value to them. + // All keys can be unset by posting an empty value to metadata. + Metadata *map[string]string `json:"metadata,omitempty"` + + // PaymentMethodTypes A list of the types of payment methods (e.g., card) this Checkout Session can accept. + PaymentMethodTypes *[]string `json:"paymentMethodTypes,omitempty"` + + // RedirectOnCompletion This parameter applies to ui_mode: embedded. Defaults to always. + // Learn more about the redirect behavior of embedded sessions at + // https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + RedirectOnCompletion *CreateStripeCheckoutSessionRedirectOnCompletion `json:"redirectOnCompletion,omitempty"` + + // ReturnURL The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site. + // This parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session. + ReturnURL *string `json:"returnURL,omitempty"` + + // SuccessURL The URL to which Stripe should send customers when payment or setup is complete. + // This parameter is not allowed if ui_mode is embedded. + // If you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page: + // https://docs.stripe.com/payments/checkout/custom-success-page + SuccessURL *string `json:"successURL,omitempty"` + + // TaxIdCollection Controls tax ID collection during checkout. + TaxIdCollection *CreateCheckoutSessionTaxIdCollection `json:"taxIdCollection,omitempty"` + + // UiMode The UI mode of the Session. Defaults to hosted. + UiMode *CheckoutSessionUIMode `json:"uiMode,omitempty"` +} + +// CreateStripeCheckoutSessionResult Create Stripe Checkout Session response. +type CreateStripeCheckoutSessionResult struct { + // CancelURL Cancel URL. + CancelURL *string `json:"cancelURL,omitempty"` + + // ClientReferenceId A unique string to reference the Checkout Session. + // This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + ClientReferenceId *string `json:"clientReferenceId,omitempty"` + + // ClientSecret The client secret of the checkout session. + // This can be used to initialize Stripe.js for your client-side implementation. + ClientSecret *string `json:"clientSecret,omitempty"` + + // CreatedAt Timestamp at which the checkout session was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency Three-letter ISO currency code, in lowercase. + Currency *CurrencyCode `json:"currency,omitempty"` + + // CustomerEmail Customer's email address provided to Stripe. + CustomerEmail *string `json:"customerEmail,omitempty"` + + // CustomerId The OpenMeter customer ID. + CustomerId string `json:"customerId"` + + // ExpiresAt Timestamp at which the checkout session will expire. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Metadata Set of key-value pairs attached to the checkout session. + Metadata *map[string]string `json:"metadata,omitempty"` + + // Mode Mode + // Always `setup` for now. + Mode StripeCheckoutSessionMode `json:"mode"` + + // ReturnURL Return URL. + ReturnURL *string `json:"returnURL,omitempty"` + + // SessionId The checkout session ID. + SessionId string `json:"sessionId"` + + // SetupIntentId The checkout session setup intent ID. + SetupIntentId string `json:"setupIntentId"` + + // Status The status of the checkout session. + Status *string `json:"status,omitempty"` + + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // SuccessURL Success URL. + SuccessURL *string `json:"successURL,omitempty"` + + // Url URL to show the checkout session. + Url *string `json:"url,omitempty"` +} + +// CreateStripeCustomerPortalSessionParams Stripe customer portal request params. +type CreateStripeCustomerPortalSessionParams struct { + // ConfigurationId The ID of an existing configuration to use for this session, + // describing its functionality and features. + // If not specified, the session uses the default configuration. + // + // See https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration + ConfigurationId *string `json:"configurationId,omitempty"` + + // Locale The IETF language tag of the locale customer portal is displayed in. + // If blank or auto, the customer’s preferred_locales or browser’s locale is used. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale + Locale *string `json:"locale,omitempty"` + + // ReturnUrl The URL to redirect the customer to after they have completed + // their requested actions. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url + ReturnUrl *string `json:"returnUrl,omitempty"` +} + +// CreditNoteOriginalInvoiceRef Omitted fields: +// period: Tax period in which the referred document had an effect required by some tax regimes and formats. +// stamps: Seals of approval from other organisations that may need to be listed. +// ext: Extensions for additional codes that may be required. +type CreditNoteOriginalInvoiceRef = InvoiceGenericDocumentRef + +// Currency Currency describes a currency supported by OpenMeter. +type Currency struct { + // Code The currency ISO code. + Code CurrencyCode `json:"code"` + + // Name The currency name. + Name string `json:"name"` + + // Subunits Subunit of the currency. + Subunits uint32 `json:"subunits"` + + // Symbol The currency symbol. + Symbol string `json:"symbol"` +} + +// CurrencyCode Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. +// Custom three-letter currency codes are also supported for convenience. +type CurrencyCode = string + +// CustomInvoicingApp Custom Invoicing app can be used for interface with any invoicing or payment system. +// +// This app provides ways to manipulate invoices and payments, however the integration +// must rely on Notifications API to get notified about invoice changes. +type CustomInvoicingApp struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EnableDraftSyncHook Enable draft.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableDraftSyncHook bool `json:"enableDraftSyncHook"` + + // EnableIssuingSyncHook Enable issuing.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableIssuingSyncHook bool `json:"enableIssuingSyncHook"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // Type The app's type is CustomInvoicing. + Type CustomInvoicingAppType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// CustomInvoicingAppType The app's type is CustomInvoicing. +type CustomInvoicingAppType string + +// CustomInvoicingAppReplaceUpdate Resource update operation model. +type CustomInvoicingAppReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EnableDraftSyncHook Enable draft.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableDraftSyncHook bool `json:"enableDraftSyncHook"` + + // EnableIssuingSyncHook Enable issuing.sync hook. + // + // If the hook is not enabled, the invoice will be progressed to the next state automatically. + EnableIssuingSyncHook bool `json:"enableIssuingSyncHook"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Type The app's type is CustomInvoicing. + Type CustomInvoicingAppReplaceUpdateType `json:"type"` +} + +// CustomInvoicingAppReplaceUpdateType The app's type is CustomInvoicing. +type CustomInvoicingAppReplaceUpdateType string + +// CustomInvoicingCustomerAppData Custom Invoicing Customer App Data. +type CustomInvoicingCustomerAppData struct { + // App The installed custom invoicing app this data belongs to. + App *CustomInvoicingApp `json:"app,omitempty"` + + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // Metadata Metadata to be used by the custom invoicing provider. + Metadata *Metadata `json:"metadata,omitempty"` + + // Type The app name. + Type CustomInvoicingCustomerAppDataType `json:"type"` +} + +// CustomInvoicingCustomerAppDataType The app name. +type CustomInvoicingCustomerAppDataType string + +// CustomInvoicingDraftSynchronizedRequest Information to finalize the draft details of an invoice. +type CustomInvoicingDraftSynchronizedRequest struct { + // Invoicing The result of the synchronization. + Invoicing *CustomInvoicingSyncResult `json:"invoicing,omitempty"` +} + +// CustomInvoicingFinalizedInvoicingRequest Information to finalize the invoicing details of an invoice. +type CustomInvoicingFinalizedInvoicingRequest struct { + // InvoiceNumber If set the invoice's number will be set to this value. + InvoiceNumber *InvoiceNumber `json:"invoiceNumber,omitempty"` + + // SentToCustomerAt If set the invoice's sent to customer at will be set to this value. + SentToCustomerAt *time.Time `json:"sentToCustomerAt,omitempty"` +} + +// CustomInvoicingFinalizedPaymentRequest Information to finalize the payment details of an invoice. +type CustomInvoicingFinalizedPaymentRequest struct { + // ExternalId If set the invoice's payment external ID will be set to this value. + ExternalId *string `json:"externalId,omitempty"` +} + +// CustomInvoicingFinalizedRequest Information to finalize the invoice. +// +// If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix). +type CustomInvoicingFinalizedRequest struct { + // Invoicing The result of the synchronization. + Invoicing *CustomInvoicingFinalizedInvoicingRequest `json:"invoicing,omitempty"` + + // Payment The result of the payment synchronization. + Payment *CustomInvoicingFinalizedPaymentRequest `json:"payment,omitempty"` +} + +// CustomInvoicingLineDiscountExternalIdMapping Mapping between line discounts and external IDs. +type CustomInvoicingLineDiscountExternalIdMapping struct { + // ExternalId The external ID (e.g. custom invoicing system's ID). + ExternalId string `json:"externalId"` + + // LineDiscountId The line discount ID. + LineDiscountId string `json:"lineDiscountId"` +} + +// CustomInvoicingLineExternalIdMapping Mapping between lines and external IDs. +type CustomInvoicingLineExternalIdMapping struct { + // ExternalId The external ID (e.g. custom invoicing system's ID). + ExternalId string `json:"externalId"` + + // LineId The line ID. + LineId string `json:"lineId"` +} + +// CustomInvoicingPaymentTrigger Payment trigger to execute on a finalized invoice. +type CustomInvoicingPaymentTrigger string + +// CustomInvoicingSyncResult Information to synchronize the invoice. +// +// Can be used to store external app's IDs on the invoice or lines. +type CustomInvoicingSyncResult struct { + // ExternalId If set the invoice's invoicing external ID will be set to this value. + ExternalId *string `json:"externalId,omitempty"` + + // InvoiceNumber If set the invoice's number will be set to this value. + InvoiceNumber *InvoiceNumber `json:"invoiceNumber,omitempty"` + + // LineDiscountExternalIds If set the invoice's line discount external IDs will be set to this value. + // + // This can be used to reference the external system's entities in the + // invoice. + LineDiscountExternalIds *[]CustomInvoicingLineDiscountExternalIdMapping `json:"lineDiscountExternalIds,omitempty"` + + // LineExternalIds If set the invoice's line external IDs will be set to this value. + // + // This can be used to reference the external system's entities in the + // invoice. + LineExternalIds *[]CustomInvoicingLineExternalIdMapping `json:"lineExternalIds,omitempty"` +} + +// CustomInvoicingTaxConfig Custom invoicing tax config. +type CustomInvoicingTaxConfig struct { + // Code Tax code. + // + // The tax code should be interpreted by the custom invoicing provider. + Code string `json:"code"` +} + +// CustomInvoicingUpdatePaymentStatusRequest Update payment status request. +// +// Can be used to manipulate invoice's payment status (when custominvoicing app is being used). +type CustomInvoicingUpdatePaymentStatusRequest struct { + // Trigger The trigger to be executed on the invoice. + Trigger CustomInvoicingPaymentTrigger `json:"trigger"` +} + +// CustomPlanInput The template for omitting properties. +type CustomPlanInput struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // Currency The currency code of the plan. + Currency CurrencyCode `json:"currency"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` +} + +// CustomSubscriptionChange Change a custom subscription. +type CustomSubscriptionChange struct { + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // CustomPlan The custom plan description which defines the Subscription. + CustomPlan CustomPlanInput `json:"customPlan"` + + // Timing Timing configuration for the change, when the change should take effect. + // For changing a subscription, the accepted values depend on the subscription configuration. + Timing SubscriptionTiming `json:"timing"` +} + +// CustomSubscriptionCreate Create a custom subscription. +type CustomSubscriptionCreate struct { + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // CustomPlan The custom plan description which defines the Subscription. + CustomPlan CustomPlanInput `json:"customPlan"` + + // CustomerId The ID of the customer. Provide either the key or ID. Has presedence over the key. + CustomerId *string `json:"customerId,omitempty"` + + // CustomerKey The key of the customer. Provide either the key or ID. + CustomerKey *string `json:"customerKey,omitempty"` + + // Timing Timing configuration for the change, when the change should take effect. + // The default is immediate. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// Customer A customer object. +type Customer struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // BillingAddress The billing address of the customer. + // Used for tax and invoicing. + BillingAddress *Address `json:"billingAddress,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency Currency of the customer. + // Used for billing, tax and invoicing. + Currency *CurrencyCode `json:"currency,omitempty"` + + // CurrentSubscriptionId The ID of the Subscription if the customer has one. + CurrentSubscriptionId *string `json:"currentSubscriptionId,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Key An optional unique key of the customer. + // Either key or usageAttribution.subjectKeys must be provided. + // Useful to reference the customer in external systems. + // For example, your database ID. + Key *string `json:"key,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PrimaryEmail The primary email address of the customer. + PrimaryEmail *string `json:"primaryEmail,omitempty"` + + // Subscriptions The subscriptions of the customer. + // Only with the `subscriptions` expand option. + Subscriptions *[]Subscription `json:"subscriptions,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsageAttribution Mapping to attribute metered usage to the customer + // Either key or usageAttribution.subjectKeys must be provided. + UsageAttribution *CustomerUsageAttribution `json:"usageAttribution,omitempty"` +} + +// CustomerAccess CustomerAccess describes what features the customer has access to. +type CustomerAccess struct { + // Entitlements Map of entitlements the customer has access to. + // The key is the feature key, the value is the entitlement value + the entitlement ID. + Entitlements map[string]EntitlementValue `json:"entitlements"` +} + +// CustomerAppData CustomerAppData +// Stores the app specific data for the customer. +// One of: stripe, sandbox, custom_invoicing +type CustomerAppData struct { + union json.RawMessage +} + +// CustomerAppDataCreateOrUpdateItem CustomerAppData +// Stores the app specific data for the customer. +// One of: stripe, sandbox, custom_invoicing +type CustomerAppDataCreateOrUpdateItem struct { + union json.RawMessage +} + +// CustomerAppDataPaginatedResponse Paginated response +type CustomerAppDataPaginatedResponse struct { + // Items The items in the current page. + Items []CustomerAppData `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// CustomerCreate Resource create operation model. +type CustomerCreate struct { + // BillingAddress The billing address of the customer. + // Used for tax and invoicing. + BillingAddress *Address `json:"billingAddress,omitempty"` + + // Currency Currency of the customer. + // Used for billing, tax and invoicing. + Currency *CurrencyCode `json:"currency,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Key An optional unique key of the customer. + // Either key or usageAttribution.subjectKeys must be provided. + // Useful to reference the customer in external systems. + // For example, your database ID. + Key *string `json:"key,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PrimaryEmail The primary email address of the customer. + PrimaryEmail *string `json:"primaryEmail,omitempty"` + + // UsageAttribution Mapping to attribute metered usage to the customer + // Either key or usageAttribution.subjectKeys must be provided. + UsageAttribution *CustomerUsageAttribution `json:"usageAttribution,omitempty"` +} + +// CustomerExpand CustomerExpand specifies the parts of the customer to expand in the list output. +type CustomerExpand string + +// CustomerId Create Stripe checkout session with customer ID. +type CustomerId struct { + // Id ULID (Universally Unique Lexicographically Sortable Identifier). + Id string `json:"id"` +} + +// CustomerKey Create Stripe checkout session with customer key. +type CustomerKey struct { + Key string `json:"key"` +} + +// CustomerOrderBy Order by options for customers. +type CustomerOrderBy string + +// CustomerPaginatedResponse Paginated response +type CustomerPaginatedResponse struct { + // Items The items in the current page. + Items []Customer `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// CustomerReplaceUpdate Resource update operation model. +type CustomerReplaceUpdate struct { + // BillingAddress The billing address of the customer. + // Used for tax and invoicing. + BillingAddress *Address `json:"billingAddress,omitempty"` + + // Currency Currency of the customer. + // Used for billing, tax and invoicing. + Currency *CurrencyCode `json:"currency,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Key An optional unique key of the customer. + // Either key or usageAttribution.subjectKeys must be provided. + // Useful to reference the customer in external systems. + // For example, your database ID. + Key *string `json:"key,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PrimaryEmail The primary email address of the customer. + PrimaryEmail *string `json:"primaryEmail,omitempty"` + + // UsageAttribution Mapping to attribute metered usage to the customer + // Either key or usageAttribution.subjectKeys must be provided. + UsageAttribution *CustomerUsageAttribution `json:"usageAttribution,omitempty"` +} + +// CustomerSubscriptionOrderBy Order by options for customer subscriptions. +type CustomerSubscriptionOrderBy string + +// CustomerUsageAttribution Mapping to attribute metered usage to the customer. +// One customer can have zero or more subjects, +// but one subject can only belong to one customer. +type CustomerUsageAttribution struct { + // SubjectKeys The subjects that are attributed to the customer. + // Can be empty when no subjects are associated with the customer. + SubjectKeys []string `json:"subjectKeys"` +} + +// DiscountPercentage Percentage discount. +type DiscountPercentage struct { + // Percentage The percentage of the discount. + Percentage Percentage `json:"percentage"` +} + +// DiscountReasonMaximumSpend The reason for the discount is a maximum spend. +type DiscountReasonMaximumSpend struct { + Type DiscountReasonMaximumSpendType `json:"type"` +} + +// DiscountReasonMaximumSpendType defines model for DiscountReasonMaximumSpend.Type. +type DiscountReasonMaximumSpendType string + +// DiscountReasonRatecardPercentage The reason for the discount is a ratecard percentage. +type DiscountReasonRatecardPercentage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Percentage The percentage of the discount. + Percentage Percentage `json:"percentage"` + Type DiscountReasonRatecardPercentageType `json:"type"` +} + +// DiscountReasonRatecardPercentageType defines model for DiscountReasonRatecardPercentage.Type. +type DiscountReasonRatecardPercentageType string + +// DiscountReasonRatecardUsage The reason for the discount is a ratecard usage. +type DiscountReasonRatecardUsage struct { + // CorrelationId Correlation ID for the discount. + // + // This is used to link discounts across different invoices (progressive billing use case). + // + // If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + // please make sure to keep the same correlation ID of the discount or in progressive billing + // setups the discount amounts might be incorrect. + CorrelationId *string `json:"correlationId,omitempty"` + + // Quantity The quantity of the usage discount. + // + // Must be positive. + Quantity Numeric `json:"quantity"` + Type DiscountReasonRatecardUsageType `json:"type"` +} + +// DiscountReasonRatecardUsageType defines model for DiscountReasonRatecardUsage.Type. +type DiscountReasonRatecardUsageType string + +// DiscountUsage Usage discount. +// +// Usage discount means that the first N items are free. From billing perspective +// this means that any usage on a specific feature is considered 0 until this discount +// is exhausted. +type DiscountUsage struct { + // Quantity The quantity of the usage discount. + // + // Must be positive. + Quantity Numeric `json:"quantity"` +} + +// Discounts Discount by type on a price +type Discounts struct { + // Percentage The percentage discount. + Percentage *DiscountPercentage `json:"percentage,omitempty"` + + // Usage The usage discount. + Usage *DiscountUsage `json:"usage,omitempty"` +} + +// DynamicPriceWithCommitments Dynamic price with spend commitments. +type DynamicPriceWithCommitments struct { + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // Multiplier The multiplier to apply to the base price to get the dynamic price. + // + // Examples: + // - 0.0: the price is zero + // - 0.5: the price is 50% of the base price + // - 1.0: the price is the same as the base price + // - 1.5: the price is 150% of the base price + Multiplier *Numeric `json:"multiplier,omitempty"` + + // Type The type of the price. + Type DynamicPriceWithCommitmentsType `json:"type"` +} + +// DynamicPriceWithCommitmentsType The type of the price. +type DynamicPriceWithCommitmentsType string + +// EditSubscriptionAddItem Add a new item to a phase. +type EditSubscriptionAddItem struct { + Op EditSubscriptionAddItemOp `json:"op"` + PhaseKey string `json:"phaseKey"` + + // RateCard A rate card defines the pricing and entitlement of a feature or service. + RateCard RateCard `json:"rateCard"` +} + +// EditSubscriptionAddItemOp defines model for EditSubscriptionAddItem.Op. +type EditSubscriptionAddItemOp string + +// EditSubscriptionAddPhase Add a new phase +type EditSubscriptionAddPhase struct { + Op EditSubscriptionAddPhaseOp `json:"op"` + + // Phase Subscription phase create input. + Phase SubscriptionPhaseCreate `json:"phase"` +} + +// EditSubscriptionAddPhaseOp defines model for EditSubscriptionAddPhase.Op. +type EditSubscriptionAddPhaseOp string + +// EditSubscriptionRemoveItem Remove an item from a phase. +type EditSubscriptionRemoveItem struct { + ItemKey string `json:"itemKey"` + Op EditSubscriptionRemoveItemOp `json:"op"` + PhaseKey string `json:"phaseKey"` +} + +// EditSubscriptionRemoveItemOp defines model for EditSubscriptionRemoveItem.Op. +type EditSubscriptionRemoveItemOp string + +// EditSubscriptionRemovePhase Remove a phase +type EditSubscriptionRemovePhase struct { + Op EditSubscriptionRemovePhaseOp `json:"op"` + PhaseKey string `json:"phaseKey"` + + // Shift The direction of the phase shift when a phase is removed. + Shift RemovePhaseShifting `json:"shift"` +} + +// EditSubscriptionRemovePhaseOp defines model for EditSubscriptionRemovePhase.Op. +type EditSubscriptionRemovePhaseOp string + +// EditSubscriptionStretchPhase Stretch a phase +type EditSubscriptionStretchPhase struct { + ExtendBy string `json:"extendBy"` + Op EditSubscriptionStretchPhaseOp `json:"op"` + PhaseKey string `json:"phaseKey"` +} + +// EditSubscriptionStretchPhaseOp defines model for EditSubscriptionStretchPhase.Op. +type EditSubscriptionStretchPhaseOp string + +// EditSubscriptionUnscheduleEdit Unschedules any edits from the current phase. +type EditSubscriptionUnscheduleEdit struct { + Op EditSubscriptionUnscheduleEditOp `json:"op"` +} + +// EditSubscriptionUnscheduleEditOp defines model for EditSubscriptionUnscheduleEdit.Op. +type EditSubscriptionUnscheduleEditOp string + +// Entitlement Entitlement templates are used to define the entitlements of a plan. +// Features are omitted from the entitlement template, as they are defined in the rate card. +type Entitlement struct { + union json.RawMessage +} + +// EntitlementBoolean Entitlement template of a boolean entitlement. +type EntitlementBoolean struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + Type EntitlementBooleanType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementBooleanType defines model for EntitlementBoolean.Type. +type EntitlementBooleanType string + +// EntitlementBooleanCreateInputs Create inputs for boolean entitlement +type EntitlementBooleanCreateInputs struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementBooleanCreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod *RecurringPeriodCreateInput `json:"usagePeriod,omitempty"` +} + +// EntitlementBooleanCreateInputsType defines model for EntitlementBooleanCreateInputs.Type. +type EntitlementBooleanCreateInputsType string + +// EntitlementBooleanV2 Entitlement template of a boolean entitlement. +type EntitlementBooleanV2 struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementBooleanV2Type `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementBooleanV2Type defines model for EntitlementBooleanV2.Type. +type EntitlementBooleanV2Type string + +// EntitlementCreateInputs Create inputs for entitlement +type EntitlementCreateInputs struct { + union json.RawMessage +} + +// EntitlementGrant The grant. +type EntitlementGrant struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // Annotations Grant annotations + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // EntitlementId The unique entitlement ULID that the grant is associated with. + EntitlementId string `json:"entitlementId"` + + // Expiration The grant expiration definition + Expiration ExpirationPeriod `json:"expiration"` + + // ExpiresAt The time the grant expires. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // NextRecurrence The next time the grant will recurr. + NextRecurrence *time.Time `json:"nextRecurrence,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The recurrence period of the grant. + Recurrence *RecurringPeriod `json:"recurrence,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // VoidedAt The time the grant was voided. + VoidedAt *time.Time `json:"voidedAt,omitempty"` +} + +// EntitlementGrantCreateInput The grant creation input. +type EntitlementGrantCreateInput struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // Expiration The grant expiration definition + Expiration ExpirationPeriod `json:"expiration"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The subject of the grant. + Recurrence *RecurringPeriodCreateInput `json:"recurrence,omitempty"` +} + +// EntitlementGrantCreateInputV2 The grant creation input. +type EntitlementGrantCreateInputV2 struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // Annotations Grant annotations + Annotations *Annotations `json:"annotations,omitempty"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // Expiration The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + Expiration *ExpirationPeriod `json:"expiration,omitempty"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The subject of the grant. + Recurrence *RecurringPeriodCreateInput `json:"recurrence,omitempty"` +} + +// EntitlementGrantV2 The grant. +type EntitlementGrantV2 struct { + // Amount The amount to grant. Should be a positive number. + Amount float64 `json:"amount"` + + // Annotations Grant annotations + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // EffectiveAt Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + EffectiveAt time.Time `json:"effectiveAt"` + + // EntitlementId The unique entitlement ULID that the grant is associated with. + EntitlementId string `json:"entitlementId"` + + // Expiration The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + Expiration *ExpirationPeriod `json:"expiration,omitempty"` + + // ExpiresAt The time the grant expires. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // MaxRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MaxRolloverAmount *float64 `json:"maxRolloverAmount,omitempty"` + + // Metadata The grant metadata. + Metadata *Metadata `json:"metadata,omitempty"` + + // MinRolloverAmount Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + // Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + MinRolloverAmount *float64 `json:"minRolloverAmount,omitempty"` + + // NextRecurrence The next time the grant will recurr. + NextRecurrence *time.Time `json:"nextRecurrence,omitempty"` + + // Priority The priority of the grant. Grants with higher priority are applied first. + // Priority is a positive decimal numbers. With lower numbers indicating higher importance. + // For example, a priority of 1 is more urgent than a priority of 2. + // When there are several grants available for the same subject, the system selects the grant with the highest priority. + // In cases where grants share the same priority level, the grant closest to its expiration will be used first. + // In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + Priority *uint8 `json:"priority,omitempty"` + + // Recurrence The recurrence period of the grant. + Recurrence *RecurringPeriod `json:"recurrence,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // VoidedAt The time the grant was voided. + VoidedAt *time.Time `json:"voidedAt,omitempty"` +} + +// EntitlementMetered Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. +// Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). +type EntitlementMetered struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod Period `json:"currentUsagePeriod"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // IsUnlimited Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IsUnlimited *bool `json:"isUnlimited,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // LastReset The time the last reset happened. + LastReset time.Time `json:"lastReset"` + + // MeasureUsageFrom The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom time.Time `json:"measureUsageFrom"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + Type EntitlementMeteredType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod THe usage period of the entitlement. + UsagePeriod RecurringPeriod `json:"usagePeriod"` +} + +// EntitlementMeteredType defines model for EntitlementMetered.Type. +type EntitlementMeteredType string + +// EntitlementMeteredCreateInputs Create inpurs for metered entitlement +type EntitlementMeteredCreateInputs struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // IsUnlimited Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IsUnlimited *bool `json:"isUnlimited,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // MeasureUsageFrom Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom *MeasureUsageFrom `json:"measureUsageFrom,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type EntitlementMeteredCreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod RecurringPeriodCreateInput `json:"usagePeriod"` +} + +// EntitlementMeteredCreateInputsType defines model for EntitlementMeteredCreateInputs.Type. +type EntitlementMeteredCreateInputsType string + +// EntitlementMeteredV2 Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. +// Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). +type EntitlementMeteredV2 struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod Period `json:"currentUsagePeriod"` + + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // Issue Issue after reset + Issue *IssueAfterReset `json:"issue,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // LastReset The time the last reset happened. + LastReset time.Time `json:"lastReset"` + + // MeasureUsageFrom The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom time.Time `json:"measureUsageFrom"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type EntitlementMeteredV2Type `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod THe usage period of the entitlement. + UsagePeriod RecurringPeriod `json:"usagePeriod"` +} + +// EntitlementMeteredV2Type defines model for EntitlementMeteredV2.Type. +type EntitlementMeteredV2Type string + +// EntitlementMeteredV2CreateInputs Create inputs for metered entitlement +type EntitlementMeteredV2CreateInputs struct { + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Grants Grants + Grants *[]EntitlementGrantCreateInputV2 `json:"grants,omitempty"` + + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // Issue Issue after reset + Issue *IssueAfterReset `json:"issue,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // MeasureUsageFrom Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + MeasureUsageFrom *MeasureUsageFrom `json:"measureUsageFrom,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type EntitlementMeteredV2CreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod RecurringPeriodCreateInput `json:"usagePeriod"` +} + +// EntitlementMeteredV2CreateInputsType defines model for EntitlementMeteredV2CreateInputs.Type. +type EntitlementMeteredV2CreateInputsType string + +// EntitlementOrderBy Order by options for entitlements. +type EntitlementOrderBy string + +// EntitlementPaginatedResponse Paginated response +type EntitlementPaginatedResponse struct { + // Items The items in the current page. + Items []Entitlement `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// EntitlementStatic A static entitlement. +type EntitlementStatic struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // SubjectKey The identifier key unique to the subject. + // NOTE: Subjects are being deprecated, please use the new customer APIs. + SubjectKey string `json:"subjectKey"` + Type EntitlementStaticType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementStaticType defines model for EntitlementStatic.Type. +type EntitlementStaticType string + +// EntitlementStaticCreateInputs Create inputs for static entitlement +type EntitlementStaticCreateInputs struct { + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // FeatureId The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureId *string `json:"featureId,omitempty"` + + // FeatureKey The feature the subject is entitled to use. + // Either featureKey or featureId is required. + FeatureKey *string `json:"featureKey,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementStaticCreateInputsType `json:"type"` + + // UsagePeriod The usage period associated with the entitlement. + UsagePeriod *RecurringPeriodCreateInput `json:"usagePeriod,omitempty"` +} + +// EntitlementStaticCreateInputsType defines model for EntitlementStaticCreateInputs.Type. +type EntitlementStaticCreateInputsType string + +// EntitlementStaticV2 A static entitlement. +type EntitlementStaticV2 struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Annotations The annotations of the entitlement. + Annotations *Annotations `json:"annotations,omitempty"` + + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentUsagePeriod The current usage period. + CurrentUsagePeriod *Period `json:"currentUsagePeriod,omitempty"` + + // CustomerId The identifier unique to the customer + CustomerId string `json:"customerId"` + + // CustomerKey The identifier key unique to the customer + CustomerKey *string `json:"customerKey,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FeatureId The feature the subject is entitled to use. + FeatureId string `json:"featureId"` + + // FeatureKey The feature the subject is entitled to use. + FeatureKey string `json:"featureKey"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type EntitlementStaticV2Type `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // UsagePeriod The defined usage period of the entitlement + UsagePeriod *RecurringPeriod `json:"usagePeriod,omitempty"` +} + +// EntitlementStaticV2Type defines model for EntitlementStaticV2.Type. +type EntitlementStaticV2Type string + +// EntitlementType Type of the entitlement. +type EntitlementType = string + +// EntitlementV2 Entitlement templates are used to define the entitlements of a plan. +// Features are omitted from the entitlement template, as they are defined in the rate card. +type EntitlementV2 struct { + union json.RawMessage +} + +// EntitlementV2CreateInputs Create inputs for entitlement +type EntitlementV2CreateInputs struct { + union json.RawMessage +} + +// EntitlementV2PaginatedResponse Paginated response +type EntitlementV2PaginatedResponse struct { + // Items The items in the current page. + Items []EntitlementV2 `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// EntitlementValue Entitlements are the core of OpenMeter access management. They define access to features for subjects. Entitlements can be metered, boolean, or static. +type EntitlementValue struct { + // Balance Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + Balance *float64 `json:"balance,omitempty"` + + // Config Only available for static entitlements. The JSON parsable config of the entitlement. + Config *string `json:"config,omitempty"` + + // HasAccess Whether the subject has access to the feature. Shared accross all entitlement types. + HasAccess bool `json:"hasAccess"` + + // Overage Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + Overage *float64 `json:"overage,omitempty"` + + // TotalAvailableGrantAmount Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + TotalAvailableGrantAmount *float64 `json:"totalAvailableGrantAmount,omitempty"` + + // Usage Only available for metered entitlements. Returns the total feature usage in the current period. + Usage *float64 `json:"usage,omitempty"` +} + +// EntitlementValueV2 EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 APIs. +type EntitlementValueV2 struct { + // Balance Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + Balance *float64 `json:"balance,omitempty"` + + // Config Only available for static entitlements. The JSON parsable config of the entitlement. + Config *string `json:"config,omitempty"` + + // GrantBalances Only available for metered entitlements. The closing balance of each active grant at query time. + // The key is the grant ID and the value is the remaining balance. + GrantBalances *map[string]float64 `json:"grantBalances,omitempty"` + + // HasAccess Whether the subject has access to the feature. Shared accross all entitlement types. + HasAccess bool `json:"hasAccess"` + + // Overage Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + Overage *float64 `json:"overage,omitempty"` + + // TotalAvailableGrantAmount Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + TotalAvailableGrantAmount *float64 `json:"totalAvailableGrantAmount,omitempty"` + + // Usage Only available for metered entitlements. Returns the total feature usage in the current period. + Usage *float64 `json:"usage,omitempty"` +} + +// ErrorExtension Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode] +type ErrorExtension struct { + // Code The machine readable description of the error. + Code string `json:"code"` + + // Field The path to the field. + Field string `json:"field"` + + // Message The human readable description of the error. + Message string `json:"message"` + AdditionalProperties map[string]interface{} `json:"-"` +} + +// Event CloudEvents Specification JSON Schema +// +// Optional properties are nullable according to the CloudEvents specification: +// OPTIONAL not omitted attributes MAY be represented as a null JSON value. +type Event = event.Event + +// EventDeliveryAttemptResponse The response of the event delivery attempt. +type EventDeliveryAttemptResponse struct { + // Body The body of the response. + Body string `json:"body"` + + // DurationMs The duration of the response in milliseconds. + DurationMs int `json:"durationMs"` + + // StatusCode Status code of the response if available. + StatusCode *int `json:"statusCode,omitempty"` + + // Url URL where the event was sent in case of notification channel with webhook type. + Url *string `json:"url,omitempty"` +} + +// ExpirationDuration The expiration duration enum +type ExpirationDuration string + +// ExpirationPeriod The grant expiration definition +type ExpirationPeriod struct { + // Count The number of time units in the expiration period. + Count uint32 `json:"count"` + + // Duration The unit of time for the expiration period. + Duration ExpirationDuration `json:"duration"` +} + +// Feature Represents a feature that can be enabled or disabled for a plan. +// Used both for product catalog and entitlements. +type Feature struct { + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *map[string]FilterString `json:"advancedMeterGroupByFilters,omitempty"` + + // ArchivedAt Timestamp of when the resource was archived. + ArchivedAt *time.Time `json:"archivedAt,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Id Readonly unique ULID identifier. + Id string `json:"id"` + + // Key A key is a unique string that is used to identify a resource. + Key string `json:"key"` + Metadata *Metadata `json:"metadata,omitempty"` + + // MeterGroupByFilters Optional meter group by filters. + // Useful if the meter scope is broader than what feature tracks. + // Example scenario would be a meter tracking all token use with groupBy fields for the model, + // then the feature could filter for model=gpt-4. + // + // ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + MeterGroupByFilters *map[string]string `json:"meterGroupByFilters,omitempty"` + + // MeterSlug A key is a unique string that is used to identify a resource. + MeterSlug *string `json:"meterSlug,omitempty"` + Name string `json:"name"` + + // UnitCost Optional per-unit cost configuration. + // Use "manual" for a fixed per-unit cost, or "llm" to look up cost + // from the LLM cost database based on meter group-by properties. + UnitCost *FeatureUnitCost `json:"unitCost,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// FeatureCreateInputs Represents a feature that can be enabled or disabled for a plan. +// Used both for product catalog and entitlements. +type FeatureCreateInputs struct { + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *map[string]FilterString `json:"advancedMeterGroupByFilters,omitempty"` + + // Key A key is a unique string that is used to identify a resource. + Key string `json:"key"` + Metadata *Metadata `json:"metadata,omitempty"` + + // MeterGroupByFilters Optional meter group by filters. + // Useful if the meter scope is broader than what feature tracks. + // Example scenario would be a meter tracking all token use with groupBy fields for the model, + // then the feature could filter for model=gpt-4. + // + // ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + MeterGroupByFilters *map[string]string `json:"meterGroupByFilters,omitempty"` + + // MeterSlug A key is a unique string that is used to identify a resource. + MeterSlug *string `json:"meterSlug,omitempty"` + Name string `json:"name"` + + // UnitCost Optional per-unit cost configuration. + // Use "manual" for a fixed per-unit cost, or "llm" to look up cost + // from the LLM cost database based on meter group-by properties. + UnitCost *FeatureUnitCost `json:"unitCost,omitempty"` +} + +// FeatureLLMUnitCost LLM cost lookup configuration. +// Maps meter group-by dimensions to LLM cost database fields. +type FeatureLLMUnitCost struct { + // Model Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). + // Use this when the feature tracks a single model. + // Mutually exclusive with `modelProperty`. + Model *string `json:"model,omitempty"` + + // ModelProperty Meter group-by property that holds the model ID. + // Use this when the meter has a group-by dimension for model. + // Mutually exclusive with `model`. + ModelProperty *string `json:"modelProperty,omitempty"` + + // Pricing Resolved per-token pricing from the LLM cost database. + // Only populated in responses when the feature's meter group-by filters + // specify exact provider and model values. + Pricing *FeatureLLMUnitCostPricing `json:"pricing,omitempty"` + + // Provider Static LLM provider value (e.g., "openai", "anthropic"). + // Use this when the feature tracks a single provider. + // Mutually exclusive with `providerProperty`. + Provider *string `json:"provider,omitempty"` + + // ProviderProperty Meter group-by property that holds the LLM provider. + // Use this when the meter has a group-by dimension for provider. + // Mutually exclusive with `provider`. + ProviderProperty *string `json:"providerProperty,omitempty"` + + // TokenType Static token type value. + // Use this when the feature tracks a single token type (e.g., only input tokens). + // Expected values: input, output, cache_read, reasoning, cache_write, request, response. + // `request` is an alias for `input`, `response` is an alias for `output`. + // Mutually exclusive with `tokenTypeProperty`. + TokenType *string `json:"tokenType,omitempty"` + + // TokenTypeProperty Meter group-by property that holds the token type. + // Use this when the meter has a group-by dimension for token type. + // Mutually exclusive with `tokenType`. + TokenTypeProperty *string `json:"tokenTypeProperty,omitempty"` + Type FeatureLLMUnitCostType `json:"type"` +} + +// FeatureLLMUnitCostType defines model for FeatureLLMUnitCost.Type. +type FeatureLLMUnitCostType string + +// FeatureLLMUnitCostPricing Resolved per-token pricing from the LLM cost database. +type FeatureLLMUnitCostPricing struct { + // CacheReadPerToken Cost per cache read token in USD. + CacheReadPerToken *Numeric `json:"cacheReadPerToken,omitempty"` + + // CacheWritePerToken Cost per cache write token in USD. + CacheWritePerToken *Numeric `json:"cacheWritePerToken,omitempty"` + + // InputPerToken Cost per input token in USD. + InputPerToken Numeric `json:"inputPerToken"` + + // OutputPerToken Cost per output token in USD. + OutputPerToken Numeric `json:"outputPerToken"` + + // ReasoningPerToken Cost per reasoning token in USD. + ReasoningPerToken *Numeric `json:"reasoningPerToken,omitempty"` +} + +// FeatureManualUnitCost A fixed per-unit cost amount. +type FeatureManualUnitCost struct { + // Amount Fixed per-unit cost amount in USD. + Amount Numeric `json:"amount"` + Type FeatureManualUnitCostType `json:"type"` +} + +// FeatureManualUnitCostType defines model for FeatureManualUnitCost.Type. +type FeatureManualUnitCostType string + +// FeatureMeta Limited representation of a feature resource which includes only its unique identifiers (id, key). +type FeatureMeta struct { + // Id Unique identifier of a feature. + Id string `json:"id"` + + // Key The key is an immutable unique identifier of the feature used throughout the API, + // for example when interacting with a subject's entitlements. + Key string `json:"key"` +} + +// FeatureOrderBy Order by options for features. +type FeatureOrderBy string + +// FeaturePaginatedResponse Paginated response +type FeaturePaginatedResponse struct { + // Items The items in the current page. + Items []Feature `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// FeatureUnitCost Per-unit cost configuration for a feature. +// Either a fixed manual amount or a dynamic LLM cost lookup. +type FeatureUnitCost struct { + union json.RawMessage +} + +// FilterIDExact A filter for a ID (ULID) field allowing only equality or inclusion. +type FilterIDExact struct { + // In The field must be in the provided list of values. + In *[]string `json:"$in,omitempty"` +} + +// FilterString A filter for a string field. +type FilterString struct { + // And Provide a list of filters to be combined with a logical AND. + And *[]FilterString `json:"$and,omitempty"` + + // Eq The field must be equal to the provided value. + Eq *string `json:"$eq,omitempty"` + + // Gt The field must be greater than the provided value. + Gt *string `json:"$gt,omitempty"` + + // Gte The field must be greater than or equal to the provided value. + Gte *string `json:"$gte,omitempty"` + + // Ilike The field must match the provided value, ignoring case. + Ilike *string `json:"$ilike,omitempty"` + + // In The field must be in the provided list of values. + In *[]string `json:"$in,omitempty"` + + // Like The field must match the provided value. + Like *string `json:"$like,omitempty"` + + // Lt The field must be less than the provided value. + Lt *string `json:"$lt,omitempty"` + + // Lte The field must be less than or equal to the provided value. + Lte *string `json:"$lte,omitempty"` + + // Ne The field must not be equal to the provided value. + Ne *string `json:"$ne,omitempty"` + + // Nilike The field must not match the provided value, ignoring case. + Nilike *string `json:"$nilike,omitempty"` + + // Nin The field must not be in the provided list of values. + Nin *[]string `json:"$nin,omitempty"` + + // Nlike The field must not match the provided value. + Nlike *string `json:"$nlike,omitempty"` + + // Or Provide a list of filters to be combined with a logical OR. + Or *[]FilterString `json:"$or,omitempty"` +} + +// FilterTime A filter for a time field. +type FilterTime struct { + // And Provide a list of filters to be combined with a logical AND. + And *[]FilterTime `json:"$and,omitempty"` + + // Gt The field must be greater than the provided value. + Gt *time.Time `json:"$gt,omitempty"` + + // Gte The field must be greater than or equal to the provided value. + Gte *time.Time `json:"$gte,omitempty"` + + // Lt The field must be less than the provided value. + Lt *time.Time `json:"$lt,omitempty"` + + // Lte The field must be less than or equal to the provided value. + Lte *time.Time `json:"$lte,omitempty"` + + // Or Provide a list of filters to be combined with a logical OR. + Or *[]FilterTime `json:"$or,omitempty"` +} + +// FlatPrice Flat price. +type FlatPrice struct { + // Amount The amount of the flat price. + Amount Numeric `json:"amount"` + + // Type The type of the price. + Type FlatPriceType `json:"type"` +} + +// FlatPriceType The type of the price. +type FlatPriceType string + +// FlatPriceWithPaymentTerm Flat price with payment term. +type FlatPriceWithPaymentTerm struct { + // Amount The amount of the flat price. + Amount Numeric `json:"amount"` + + // PaymentTerm The payment term of the flat price. + // Defaults to in advance. + PaymentTerm *PricePaymentTerm `json:"paymentTerm,omitempty"` + + // Type The type of the price. + Type FlatPriceWithPaymentTermType `json:"type"` +} + +// FlatPriceWithPaymentTermType The type of the price. +type FlatPriceWithPaymentTermType string + +// ForbiddenProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type ForbiddenProblemResponse = UnexpectedProblemResponse + +// GrantBurnDownHistorySegment A segment of the grant burn down history. +// +// A given segment represents the usage of a grant between events that changed either the grant burn down priority order or the usag period. +type GrantBurnDownHistorySegment struct { + // BalanceAtEnd The entitlement balance at the end of the period. + BalanceAtEnd float64 `json:"balanceAtEnd"` + + // BalanceAtStart entitlement balance at the start of the period. + BalanceAtStart float64 `json:"balanceAtStart"` + + // GrantBalancesAtEnd The balance breakdown of each active grant at the end of the period: GrantID: Balance + GrantBalancesAtEnd map[string]float64 `json:"grantBalancesAtEnd"` + + // GrantBalancesAtStart The balance breakdown of each active grant at the start of the period: GrantID: Balance + GrantBalancesAtStart map[string]float64 `json:"grantBalancesAtStart"` + + // GrantUsages Which grants were actually burnt down in the period and by what amount. + GrantUsages []GrantUsageRecord `json:"grantUsages"` + + // Overage Overuse that wasn't covered by grants. + Overage float64 `json:"overage"` + + // Period The period of the segment. + Period Period `json:"period"` + + // Usage The total usage of the grant in the period. + Usage float64 `json:"usage"` +} + +// GrantOrderBy Order by options for grants. +type GrantOrderBy string + +// GrantPaginatedResponse Paginated response +type GrantPaginatedResponse struct { + // Items The items in the current page. + Items []EntitlementGrant `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// GrantUsageRecord Usage Record +type GrantUsageRecord struct { + // GrantId The id of the grant + GrantId string `json:"grantId"` + + // Usage The usage in the period + Usage float64 `json:"usage"` +} + +// GrantV2PaginatedResponse Paginated response +type GrantV2PaginatedResponse struct { + // Items The items in the current page. + Items []EntitlementGrantV2 `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// IDResource IDResource is a resouce with an ID. +type IDResource struct { + // Id A unique identifier for the resource. + Id string `json:"id"` +} + +// IngestEventsBody The body of the events request. +// Either a single event or a batch of events. +type IngestEventsBody struct { + union json.RawMessage +} + +// IngestEventsBody1 defines model for . +type IngestEventsBody1 = []Event + +// IngestedEvent An ingested event with optional validation error. +type IngestedEvent struct { + // CustomerId The customer ID if the event is associated with a customer. + CustomerId *string `json:"customerId,omitempty"` + + // Event The original event ingested. + Event Event `json:"event"` + + // IngestedAt The date and time the event was ingested. + IngestedAt time.Time `json:"ingestedAt"` + + // StoredAt The date and time the event was stored. + StoredAt time.Time `json:"storedAt"` + + // ValidationError The validation error if the event failed validation. + ValidationError *string `json:"validationError,omitempty"` +} + +// IngestedEventCursorPaginatedResponse A response for cursor pagination. +type IngestedEventCursorPaginatedResponse struct { + // Items The items in the response. + Items []IngestedEvent `json:"items"` + + // NextCursor The cursor of the last item in the list. + NextCursor *string `json:"nextCursor,omitempty"` +} + +// InstallMethod Install method of the application. +type InstallMethod string + +// InternalServerErrorProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type InternalServerErrorProblemResponse = UnexpectedProblemResponse + +// Invoice Invoice represents an invoice in the system. +type Invoice struct { + // CollectionAt The time when the invoice will be/has been collected. + CollectionAt *time.Time `json:"collectionAt,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency Currency for all invoice line items. + // + // Multi currency invoices are not supported yet. + Currency CurrencyCode `json:"currency"` + + // Customer Legal entity receiving the goods or services. + Customer BillingInvoiceCustomerExtendedDetails `json:"customer"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // DraftUntil The time until the invoice is in draft status. + // + // On draft invoice creation it is calculated from the workflow settings. + // + // If manual approval is required, the draftUntil time is set. + DraftUntil *time.Time `json:"draftUntil,omitempty"` + + // DueAt Due time of the fulfillment of the invoice (if available). + DueAt *time.Time `json:"dueAt,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceAppExternalIds `json:"externalIds,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // IssuedAt The time the invoice was issued. + // + // Depending on the status of the invoice this can mean multiple things: + // - draft, gathering: The time the invoice will be issued based on the workflow settings. + // - issued: The time the invoice was issued. + IssuedAt *time.Time `json:"issuedAt,omitempty"` + + // Lines List of invoice lines representing each of the items sold to the customer. + Lines *[]InvoiceLine `json:"lines,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Number Number specifies the human readable key used to reference this Invoice. + // + // The invoice number can change in the draft phases, as we are allocating temporary draft + // invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + // + // Please note that the number is (depending on the upstream settings) either unique for the + // whole organization or unique for the customer, or in multi (stripe) account setups unique for the + // account. + Number InvoiceNumber `json:"number"` + + // Payment Information on when, how, and to whom the invoice should be paid. + Payment *InvoicePaymentTerms `json:"payment,omitempty"` + + // Period The period the invoice covers. If the invoice has no line items, it's not set. + Period *Period `json:"period,omitempty"` + + // Preceding Key information regarding previous invoices and potentially details as to why they were corrected. + Preceding *[]InvoiceDocumentRef `json:"preceding,omitempty"` + + // QuantitySnapshotedAt The time when the quantity snapshots on the invoice lines were taken. + QuantitySnapshotedAt *time.Time `json:"quantitySnapshotedAt,omitempty"` + + // SentToCustomerAt The time the invoice was sent to customer. + SentToCustomerAt *time.Time `json:"sentToCustomerAt,omitempty"` + + // Status The status of the invoice. + // + // This field only conatins a simplified status, for more detailed information use the statusDetails field. + Status InvoiceStatus `json:"status"` + + // StatusDetails The details of the current invoice status. + StatusDetails InvoiceStatusDetails `json:"statusDetails"` + + // Supplier The taxable entity supplying the goods or services. + Supplier BillingParty `json:"supplier"` + + // Totals Summary of all the invoice totals, including taxes (calculated). + Totals InvoiceTotals `json:"totals"` + + // Type Type of the invoice. + // + // The type of invoice determines the purpose of the invoice and how it should be handled. + // + // Supported types: + // - standard: A regular commercial invoice document between a supplier and customer. + // - credit_note: Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + Type InvoiceType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationIssues Validation issues reported by the invoice workflow. + ValidationIssues *[]ValidationIssue `json:"validationIssues,omitempty"` + + // VoidedAt The time the invoice was voided. + // + // If the invoice was voided, this field will be set to the time the invoice was voided. + VoidedAt *time.Time `json:"voidedAt,omitempty"` + + // Workflow The workflow associated with the invoice. + // + // It is always a snapshot of the workflow settings at the time of invoice creation. The + // field is optional as it should be explicitly requested with expand options. + Workflow InvoiceWorkflowSettings `json:"workflow"` +} + +// InvoiceAppExternalIds InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. +type InvoiceAppExternalIds struct { + // Invoicing The external ID of the invoice in the invoicing app if available. + Invoicing *string `json:"invoicing,omitempty"` + + // Payment The external ID of the invoice in the payment app if available. + Payment *string `json:"payment,omitempty"` + + // Tax The external ID of the invoice in the tax app if available. + Tax *string `json:"tax,omitempty"` +} + +// InvoiceAvailableActionDetails InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for +// non-gathering invoices. +type InvoiceAvailableActionDetails struct { + // ResultingState The state the invoice will reach if the action is activated and + // all intermediate steps are successful. + // + // For example advancing a draft_created invoice will result in a draft_manual_approval_needed invoice. + ResultingState string `json:"resultingState"` +} + +// InvoiceAvailableActionInvoiceDetails InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for +// gathering invoices. +type InvoiceAvailableActionInvoiceDetails = map[string]interface{} + +// InvoiceAvailableActions InvoiceAvailableActions represents the actions that can be performed on the invoice. +type InvoiceAvailableActions struct { + // Advance Advance the invoice to the next status. + Advance *InvoiceAvailableActionDetails `json:"advance,omitempty"` + + // Approve Approve an invoice that requires manual approval. + Approve *InvoiceAvailableActionDetails `json:"approve,omitempty"` + + // Delete Delete the invoice (only non-issued invoices can be deleted). + Delete *InvoiceAvailableActionDetails `json:"delete,omitempty"` + + // Invoice Invoice a gathering invoice + Invoice *InvoiceAvailableActionInvoiceDetails `json:"invoice,omitempty"` + + // Retry Retry an invoice issuing step that failed. + Retry *InvoiceAvailableActionDetails `json:"retry,omitempty"` + + // SnapshotQuantities Snapshot quantities for usage based line items. + SnapshotQuantities *InvoiceAvailableActionDetails `json:"snapshotQuantities,omitempty"` + + // Void Void an already issued invoice. + Void *InvoiceAvailableActionDetails `json:"void,omitempty"` +} + +// InvoiceDetailedLine InvoiceDetailedLine represents a line item that is sold to the customer as a manually added fee. +type InvoiceDetailedLine struct { + // Category Category of the flat fee. + Category *InvoiceDetailedLineCostCategory `json:"category,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CreditAllocations Credit allocations applied to this line. + // + // Credits are deducted from the line total before taxes are applied. + CreditAllocations *[]InvoiceLineCreditAllocation `json:"creditAllocations,omitempty"` + + // Currency The currency of this line. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts Discounts detailes applied to this line. + // + // New discounts can be added via the invoice's discounts API, to facilitate + // discounts that are affecting multiple lines. + Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the line. + Id string `json:"id"` + + // Invoice The invoice this item belongs to. + Invoice *InvoiceReference `json:"invoice,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + InvoiceAt time.Time `json:"invoiceAt"` + + // ManagedBy managedBy specifies if the line is manually added via the api or managed by OpenMeter. + ManagedBy InvoiceLineManagedBy `json:"managedBy"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // PaymentTerm Payment term of the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + PaymentTerm *PricePaymentTerm `json:"paymentTerm,omitempty"` + + // PerUnitAmount Price of the item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + PerUnitAmount *Numeric `json:"perUnitAmount,omitempty"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Quantity Quantity of the item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Quantity *Numeric `json:"quantity,omitempty"` + + // RateCard The rate card that is used for this line. + RateCard *InvoiceDetailedLineRateCard `json:"rateCard,omitempty"` + + // Status Status of the line. + // + // External calls always create valid lines, other line types are managed by the + // billing engine of OpenMeter. + Status InvoiceLineStatus `json:"status"` + + // Subscription Subscription are the references to the subscritpions that this line is related to. + Subscription *InvoiceLineSubscriptionReference `json:"subscription,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Taxes Taxes applied to the invoice totals. + Taxes *[]InvoiceLineTaxItem `json:"taxes,omitempty"` + + // Totals Totals for this line. + Totals InvoiceTotals `json:"totals"` + + // Type Type of the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Type InvoiceDetailedLineType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceDetailedLineType Type of the line. +type InvoiceDetailedLineType string + +// InvoiceDetailedLineCostCategory InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a +// commitment. +type InvoiceDetailedLineCostCategory string + +// InvoiceDetailedLineRateCard InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. +type InvoiceDetailedLineRateCard struct { + // Discounts The discounts that are applied to the line. + Discounts *BillingDiscounts `json:"discounts,omitempty"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *FlatPriceWithPaymentTerm `json:"price"` + + // Quantity Quantity of the item being sold. + // + // Default: 1 + Quantity *Numeric `json:"quantity,omitempty"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceDocumentRef CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is based on. +type InvoiceDocumentRef = CreditNoteOriginalInvoiceRef + +// InvoiceDocumentRefType InvoiceDocumentRefType defines the type of document that is being referenced. +type InvoiceDocumentRefType string + +// InvoiceExpand InvoiceExpand specifies the parts of the invoice to expand in the list output. +type InvoiceExpand string + +// InvoiceGenericDocumentRef Omitted fields: +// period: Tax period in which the referred document had an effect required by some tax regimes and formats. +// stamps: Seals of approval from other organisations that may need to be listed. +// ext: Extensions for additional codes that may be required. +type InvoiceGenericDocumentRef struct { + // Description Additional details about the document. + Description *string `json:"description,omitempty"` + + // Reason Human readable description on why this reference is here or needs to be used. + Reason *string `json:"reason,omitempty"` + + // Type Type of the document referenced. + Type InvoiceDocumentRefType `json:"type"` +} + +// InvoiceLine InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. +type InvoiceLine struct { + // Children The lines detailing the item or service sold. + Children *[]InvoiceDetailedLine `json:"children,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CreditAllocations Credit allocations applied to this line. + // + // Credits are deducted from the line total before taxes are applied. + CreditAllocations *[]InvoiceLineCreditAllocation `json:"creditAllocations,omitempty"` + + // Currency The currency of this line. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts Discounts detailes applied to this line. + // + // New discounts can be added via the invoice's discounts API, to facilitate + // discounts that are affecting multiple lines. + Discounts *InvoiceLineDiscounts `json:"discounts,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // Id ID of the line. + Id string `json:"id"` + + // Invoice The invoice this item belongs to. + Invoice *InvoiceReference `json:"invoice,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // ManagedBy managedBy specifies if the line is manually added via the api or managed by OpenMeter. + ManagedBy InvoiceLineManagedBy `json:"managedBy"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // MeteredPreLinePeriodQuantity The metered quantity of the item used in before this line's period without any discounts applied. + // + // It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + MeteredPreLinePeriodQuantity *Numeric `json:"meteredPreLinePeriodQuantity,omitempty"` + + // MeteredQuantity The quantity of the item that has been metered for the period before any discounts were applied. + MeteredQuantity *Numeric `json:"meteredQuantity,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // PreLinePeriodQuantity The quantity of the item used before this line's period. + // + // It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + // + // Any usage discounts applied previously are deducted from this quantity. + PreLinePeriodQuantity *Numeric `json:"preLinePeriodQuantity,omitempty"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // Quantity The quantity of the item being sold. + // + // Any usage discounts applied previously are deducted from this quantity. + Quantity *Numeric `json:"quantity,omitempty"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // Status Status of the line. + // + // External calls always create valid lines, other line types are managed by the + // billing engine of OpenMeter. + Status InvoiceLineStatus `json:"status"` + + // Subscription Subscription are the references to the subscritpions that this line is related to. + Subscription *InvoiceLineSubscriptionReference `json:"subscription,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Taxes Taxes applied to the invoice totals. + Taxes *[]InvoiceLineTaxItem `json:"taxes,omitempty"` + + // Totals Totals for this line. + Totals InvoiceTotals `json:"totals"` + + // Type Type of the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Type InvoiceLineType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceLineType Type of the line. +type InvoiceLineType string + +// InvoiceLineAmountDiscount InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied before taxes. +type InvoiceLineAmountDiscount struct { + // Amount Fixed discount amount to apply (calculated if percent present). + Amount Numeric `json:"amount"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Text description as to why the discount was applied. + Description *string `json:"description,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // Reason Reason code. + Reason BillingDiscountReason `json:"reason"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceLineAppExternalIds InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. +type InvoiceLineAppExternalIds struct { + // Invoicing The external ID of the invoice in the invoicing app if available. + Invoicing *string `json:"invoicing,omitempty"` + + // Tax The external ID of the invoice in the tax app if available. + Tax *string `json:"tax,omitempty"` +} + +// InvoiceLineCreditAllocation InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are applied. +type InvoiceLineCreditAllocation struct { + // Amount Amount allocated from credits. + Amount Numeric `json:"amount"` + + // Description Text description as to why the credit was allocated. + Description *string `json:"description,omitempty"` +} + +// InvoiceLineDiscounts InvoiceLineDiscounts represents the discounts applied to the invoice line by type. +type InvoiceLineDiscounts struct { + // Amount Amount based discounts applied to the line. + // + // Amount based discounts are deduced from the total price of the line. + Amount *[]InvoiceLineAmountDiscount `json:"amount,omitempty"` + + // Usage Usage based discounts applied to the line. + // + // Usage based discounts are deduced from the usage of the line before price calculations are applied. + Usage *[]InvoiceLineUsageDiscount `json:"usage,omitempty"` +} + +// InvoiceLineManagedBy InvoiceLineManagedBy specifies who manages the line. +type InvoiceLineManagedBy string + +// InvoiceLineReplaceUpdate InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. +// +// This type makes ID optional to allow for creating new lines as part of the update. +type InvoiceLineReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // Id The ID of the line. + Id *string `json:"id,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceLineStatus Line status specifies the status of the line. +type InvoiceLineStatus string + +// InvoiceLineSubscriptionReference InvoiceLineSubscriptionReference contains the references to the subscription that this line is related to. +type InvoiceLineSubscriptionReference struct { + // BillingPeriod The billing period of the subscription. In case the subscription item's billing period is different + // from the subscription's billing period, this field will contain the billing period of the subscription itself. + // + // For example, in case of: + // - A monthly billed subscription anchored to 2025-01-01 + // - A subscription item billed daily + // + // An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed daily, but the subscription's billing period + // will be 2025-01-01 to 2025-01-31. + BillingPeriod Period `json:"billingPeriod"` + + // Item The item this line is related to. + Item IDResource `json:"item"` + + // Phase The phase of the subscription. + Phase IDResource `json:"phase"` + + // Subscription The subscription. + Subscription IDResource `json:"subscription"` +} + +// InvoiceLineTaxBehavior InvoiceLineTaxBehavior details how the tax item is applied to the base amount. +// +// Inclusive means the tax is included in the base amount. +// Exclusive means the tax is added to the base amount. +type InvoiceLineTaxBehavior string + +// InvoiceLineTaxItem TaxConfig stores the configuration for a tax line relative to an invoice line. +type InvoiceLineTaxItem struct { + // Behavior Is the tax item inclusive or exclusive of the base amount. + Behavior *InvoiceLineTaxBehavior `json:"behavior,omitempty"` + + // Config Tax provider configuration. + Config *TaxConfig `json:"config,omitempty"` + + // Percent Percent defines the percentage set manually or determined from + // the rate key (calculated if rate present). A nil percent implies that + // this tax combo is **exempt** from tax.") + Percent *Percentage `json:"percent,omitempty"` + + // Surcharge Some countries require an additional surcharge (calculated if rate present). + Surcharge *Numeric `json:"surcharge,omitempty"` +} + +// InvoiceLineUsageDiscount InvoiceLineUsageDiscount represents an usage-based discount applied to the line. +// +// The deduction is done before the pricing algorithm is applied. +type InvoiceLineUsageDiscount struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Text description as to why the discount was applied. + Description *string `json:"description,omitempty"` + + // ExternalIds External IDs of the invoice in other apps such as Stripe. + ExternalIds *InvoiceLineAppExternalIds `json:"externalIds,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // PreLinePeriodQuantity The usage discount already applied to the previous split lines. + // + // Only set if progressive billing is enabled and the line is a split line. + PreLinePeriodQuantity *Numeric `json:"preLinePeriodQuantity,omitempty"` + + // Quantity The usage to apply. + Quantity Numeric `json:"quantity"` + + // Reason Reason code. + Reason BillingDiscountReason `json:"reason"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// InvoiceNumber InvoiceNumber is a unique identifier for the invoice, generated by the +// invoicing app. +// +// The uniqueness depends on a lot of factors: +// - app setting (unique per app or unique per customer) +// - multiple app scenarios (multiple apps generating invoices with the same prefix) +type InvoiceNumber = string + +// InvoiceOrderBy InvoiceOrderBy specifies the ordering options for invoice listing. +type InvoiceOrderBy string + +// InvoicePaginatedResponse Paginated response +type InvoicePaginatedResponse struct { + // Items The items in the current page. + Items []Invoice `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// InvoicePaymentTerms Payment contains details as to how the invoice should be paid. +type InvoicePaymentTerms struct { + // Terms The terms of payment for the invoice. + Terms *PaymentTerms `json:"terms,omitempty"` +} + +// InvoicePendingLineCreate InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage. +type InvoicePendingLineCreate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoicePendingLineCreateInput InvoicePendingLineCreate represents the create model for a pending invoice line. +type InvoicePendingLineCreateInput struct { + // Currency The currency of the lines to be created. + Currency CurrencyCode `json:"currency"` + + // Lines The lines to be created. + Lines []InvoicePendingLineCreate `json:"lines"` +} + +// InvoicePendingLineCreateResponse InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. +type InvoicePendingLineCreateResponse struct { + // Invoice The invoice containing the created lines. + Invoice Invoice `json:"invoice"` + + // IsInvoiceNew Whether the invoice was newly created. + IsInvoiceNew bool `json:"isInvoiceNew"` + + // Lines The lines that were created. + Lines []InvoiceLine `json:"lines"` +} + +// InvoicePendingLinesActionFiltersInput InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. +type InvoicePendingLinesActionFiltersInput struct { + // LineIds The pending line items to include in the invoice, if not provided: + // - all line items that have invoice_at < asOf will be included + // - [progressive billing only] all usage based line items will be included up to asOf, new + // usage-based line items will be staged for the rest of the billing cycle + // + // All lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail. + LineIds *[]string `json:"lineIds,omitempty"` +} + +// InvoicePendingLinesActionInput BillingInvoiceActionInput is the input for creating an invoice. +// +// Invoice creation is always based on already pending line items created by the billingCreateLineByCustomer +// operation. Empty invoices are not allowed. +type InvoicePendingLinesActionInput struct { + // AsOf The time as of which the invoice is created. + // + // If not provided, the current time is used. + AsOf *time.Time `json:"asOf,omitempty"` + + // CustomerId The customer ID for which to create the invoice. + CustomerId string `json:"customerId"` + + // Filters Filters to apply when creating the invoice. + Filters *InvoicePendingLinesActionFiltersInput `json:"filters,omitempty"` + + // ProgressiveBillingOverride Override the progressive billing setting of the customer. + // + // Can be used to disable/enable progressive billing in case the business logic + // requires it, if not provided the billing profile's progressive billing setting will be used. + ProgressiveBillingOverride *bool `json:"progressiveBillingOverride,omitempty"` +} + +// InvoiceReference Reference to an invoice. +type InvoiceReference struct { + // Id The ID of the invoice. + Id string `json:"id"` + + // Number The number of the invoice. + Number *InvoiceNumber `json:"number,omitempty"` +} + +// InvoiceReplaceUpdate InvoiceReplaceUpdate represents the update model for an invoice. +type InvoiceReplaceUpdate struct { + // Customer The customer the invoice is sent to. + Customer BillingPartyReplaceUpdate `json:"customer"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Lines The lines included in the invoice. + Lines []InvoiceLineReplaceUpdate `json:"lines"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Supplier The supplier of the lines included in the invoice. + Supplier BillingPartyReplaceUpdate `json:"supplier"` + + // Workflow The workflow settings for the invoice. + Workflow InvoiceWorkflowReplaceUpdate `json:"workflow"` +} + +// InvoiceSimulationInput InvoiceSimulationInput is the input for simulating an invoice. +type InvoiceSimulationInput struct { + // Currency Currency for all invoice line items. + // + // Multi currency invoices are not supported yet. + Currency CurrencyCode `json:"currency"` + + // Lines Lines to be included in the generated invoice. + Lines []InvoiceSimulationLine `json:"lines"` + + // Number The number of the invoice. + Number *InvoiceNumber `json:"number,omitempty"` +} + +// InvoiceSimulationLine InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint. +type InvoiceSimulationLine struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // FeatureKey The feature that the usage is based on. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + FeatureKey *string `json:"featureKey,omitempty"` + + // Id ID of the line. If not specified it will be auto-generated. + // + // When discounts are specified, this must be provided, so that the discount can reference it. + Id *string `json:"id,omitempty"` + + // InvoiceAt The time this line item should be invoiced. + InvoiceAt time.Time `json:"invoiceAt"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Period Period of the line item applies to for revenue recognition pruposes. + // + // Billing always treats periods as start being inclusive and end being exclusive. + Period Period `json:"period"` + + // PreLinePeriodQuantity The quantity of the item used before this line's period, if the line is billed progressively. + PreLinePeriodQuantity *Numeric `json:"preLinePeriodQuantity,omitempty"` + + // Price Price of the usage-based item being sold. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Price *RateCardUsageBasedPrice `json:"price,omitempty"` + + // Quantity The quantity of the item being sold. + Quantity Numeric `json:"quantity"` + + // RateCard The rate card that is used for this line. + // + // The rate card captures the intent of the price and discounts for the usage-based item. + RateCard *InvoiceUsageBasedRateCard `json:"rateCard,omitempty"` + + // TaxConfig Tax config specify the tax configuration for this line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceStatus InvoiceStatus describes the status of an invoice. +type InvoiceStatus string + +// InvoiceStatusDetails InvoiceStatusDetails represents the details of the invoice status. +// +// API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine +// the next steps of the invoice instead of the extendedStatus field. +type InvoiceStatusDetails struct { + // AvailableActions The actions that can be performed on the invoice. + AvailableActions InvoiceAvailableActions `json:"availableActions"` + + // ExtendedStatus Extended status information for the invoice. + ExtendedStatus string `json:"extendedStatus"` + + // Failed Is the invoice in a failed state? + Failed bool `json:"failed"` + + // Immutable Is the invoice editable? + Immutable bool `json:"immutable"` +} + +// InvoiceTotals Totals contains the summaries of all calculations for the invoice. +type InvoiceTotals struct { + // Amount The total value of the line before taxes, discounts and commitments. + Amount Numeric `json:"amount"` + + // ChargesTotal The amount of value of the line that are due to additional charges. + ChargesTotal Numeric `json:"chargesTotal"` + + // CreditsTotal The amount of value of the line that are due to credits. + CreditsTotal Numeric `json:"creditsTotal"` + + // DiscountsTotal The amount of value of the line that are due to discounts. + DiscountsTotal Numeric `json:"discountsTotal"` + + // TaxesExclusiveTotal The total amount of taxes that are added on top of amount from the line. + TaxesExclusiveTotal Numeric `json:"taxesExclusiveTotal"` + + // TaxesInclusiveTotal The total amount of taxes that are included in the line. + TaxesInclusiveTotal Numeric `json:"taxesInclusiveTotal"` + + // TaxesTotal The total amount of taxes for this line. + TaxesTotal Numeric `json:"taxesTotal"` + + // Total The total amount value of the line after taxes, discounts and commitments. + Total Numeric `json:"total"` +} + +// InvoiceType InvoiceType represents the type of invoice. +// +// The type of invoice determines the purpose of the invoice and how it should be handled. +type InvoiceType string + +// InvoiceUsageBasedRateCard InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. +type InvoiceUsageBasedRateCard struct { + // Discounts The discounts that are applied to the line. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Discounts *BillingDiscounts `json:"discounts,omitempty"` + + // FeatureKey The feature the customer is entitled to use. + FeatureKey *string `json:"featureKey,omitempty"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *RateCardUsageBasedPrice `json:"price"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` +} + +// InvoiceWorkflowInvoicingSettingsReplaceUpdate InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow. +type InvoiceWorkflowInvoicingSettingsReplaceUpdate struct { + // AutoAdvance Whether to automatically issue the invoice after the draftPeriod has passed. + AutoAdvance *bool `json:"autoAdvance,omitempty"` + + // DefaultTaxConfig Default tax configuration to apply to the invoices. + // + // Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + // deprecated and can no longer be added or changed: the organization default tax code is + // used instead. Existing tax-code values may still be removed, and `behavior` remains + // fully supported. + DefaultTaxConfig *TaxConfig `json:"defaultTaxConfig,omitempty"` + + // DraftPeriod The period for the invoice to be kept in draft status for manual reviews. + DraftPeriod *string `json:"draftPeriod,omitempty"` + + // DueAfter The period after which the invoice is due. + // With some payment solutions it's only applicable for manual collection method. + DueAfter *string `json:"dueAfter,omitempty"` + + // SubscriptionEndProrationMode Controls how subscription-ending shortened service periods are billed. + SubscriptionEndProrationMode *BillingWorkflowInvoicingSubscriptionEndProrationMode `json:"subscriptionEndProrationMode,omitempty"` +} + +// InvoiceWorkflowReplaceUpdate InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. +// +// Fields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings. +type InvoiceWorkflowReplaceUpdate struct { + // Workflow The workflow used for this invoice. + Workflow InvoiceWorkflowSettingsReplaceUpdate `json:"workflow"` +} + +// InvoiceWorkflowSettings InvoiceWorkflowSettings represents the workflow settings used by the invoice. +// +// This is a clone of the billing profile's workflow settings at the time of invoice creation +// with customer overrides considered. +type InvoiceWorkflowSettings struct { + // Apps The apps that will be used to orchestrate the invoice's workflow. + Apps *BillingProfileAppsOrReference `json:"apps,omitempty"` + + // SourceBillingProfileId sourceBillingProfileID is the billing profile on which the workflow was based on. + // + // The profile is snapshotted on invoice creation, after which it can be altered independently + // of the profile itself. + SourceBillingProfileId string `json:"sourceBillingProfileId"` + + // Workflow The workflow details used by this invoice. + Workflow BillingWorkflow `json:"workflow"` +} + +// InvoiceWorkflowSettingsReplaceUpdate Mutable workflow settings for an invoice. +// +// Other fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow +// at creation time. +type InvoiceWorkflowSettingsReplaceUpdate struct { + // Invoicing The invoicing settings for this workflow + Invoicing InvoiceWorkflowInvoicingSettingsReplaceUpdate `json:"invoicing"` + + // Payment The payment settings for this workflow + Payment BillingWorkflowPaymentSettings `json:"payment"` +} + +// IssueAfterReset Issue after reset +type IssueAfterReset struct { + // Amount The initial grant amount + Amount float64 `json:"amount"` + + // Priority The priority of the issue after reset + Priority *uint8 `json:"priority,omitempty"` +} + +// ListEntitlementsResult List entitlements result +type ListEntitlementsResult struct { + union json.RawMessage +} + +// ListEntitlementsResult0 defines model for . +type ListEntitlementsResult0 = []Entitlement + +// ListFeaturesResult List features result +type ListFeaturesResult struct { + union json.RawMessage +} + +// ListFeaturesResult0 defines model for . +type ListFeaturesResult0 = []Feature + +// MarketplaceInstallRequestPayload Marketplace install request payload. +type MarketplaceInstallRequestPayload struct { + // CreateBillingProfile If true, a billing profile will be created for the app. + // The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + CreateBillingProfile *bool `json:"createBillingProfile,omitempty"` + + // Name Name of the application to install. + // + // If name is not provided defaults to the marketplace listing's name. + Name *string `json:"name,omitempty"` +} + +// MarketplaceInstallResponse Marketplace install response. +type MarketplaceInstallResponse struct { + // App App. + // One of: stripe + App App `json:"app"` + + // DefaultForCapabilityTypes Default for capabilities + DefaultForCapabilityTypes []AppCapabilityType `json:"defaultForCapabilityTypes"` +} + +// MarketplaceListing A marketplace listing. +// Represent an available app in the app marketplace that can be installed to the organization. +// +// Marketplace apps only exist in config so they don't extend the Resource model. +type MarketplaceListing struct { + // Capabilities The app's capabilities. + Capabilities []AppCapability `json:"capabilities"` + + // Description The app's description. + Description string `json:"description"` + + // InstallMethods Install methods. + // + // List of methods to install the app. + InstallMethods []InstallMethod `json:"installMethods"` + + // Name The app's name. + Name string `json:"name"` + + // Type The app's type + Type AppType `json:"type"` +} + +// MarketplaceListingPaginatedResponse Paginated response +type MarketplaceListingPaginatedResponse struct { + // Items The items in the current page. + Items []MarketplaceListing `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// MeasureUsageFrom Measure usage from +type MeasureUsageFrom struct { + union json.RawMessage +} + +// MeasureUsageFromPreset Start of measurement options +type MeasureUsageFromPreset string + +// MeasureUsageFromTime [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. +type MeasureUsageFromTime = time.Time + +// Metadata Set of key-value pairs. +// Metadata can be used to store additional information about a resource. +type Metadata = map[string]string + +// Meter A meter is a configuration that defines how to match and aggregate events. +type Meter struct { + // Aggregation The aggregation type to use for the meter. + Aggregation MeterAggregation `json:"aggregation"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EventFrom The date since the meter should include events. + // Useful to skip old events. + // If not specified, all historical events are included. + EventFrom *time.Time `json:"eventFrom,omitempty"` + + // EventType The event type to aggregate. + EventType string `json:"eventType"` + + // GroupBy Named JSONPath expressions to extract the group by values from the event data. + // + // Keys must be unique and consist only alphanumeric and underscore characters. + GroupBy *map[string]string `json:"groupBy,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + // Defaults to the slug if not specified. + Name *string `json:"name,omitempty"` + + // Slug A unique, human-readable identifier for the meter. + // Must consist only alphanumeric and underscore characters. + Slug string `json:"slug"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValueProperty JSONPath expression to extract the value from the ingested event's data property. + // + // The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + // + // For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + ValueProperty *string `json:"valueProperty,omitempty"` +} + +// MeterAggregation The aggregation type to use for the meter. +type MeterAggregation string + +// MeterCreate A meter create model. +type MeterCreate struct { + // Aggregation The aggregation type to use for the meter. + Aggregation MeterAggregation `json:"aggregation"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EventFrom The date since the meter should include events. + // Useful to skip old events. + // If not specified, all historical events are included. + EventFrom *time.Time `json:"eventFrom,omitempty"` + + // EventType The event type to aggregate. + EventType string `json:"eventType"` + + // GroupBy Named JSONPath expressions to extract the group by values from the event data. + // + // Keys must be unique and consist only alphanumeric and underscore characters. + GroupBy *map[string]string `json:"groupBy,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + // Defaults to the slug if not specified. + Name *string `json:"name,omitempty"` + + // Slug A unique, human-readable identifier for the meter. + // Must consist only alphanumeric and underscore characters. + Slug string `json:"slug"` + + // ValueProperty JSONPath expression to extract the value from the ingested event's data property. + // + // The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + // + // For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + ValueProperty *string `json:"valueProperty,omitempty"` +} + +// MeterOrderBy Order by options for meters. +type MeterOrderBy string + +// MeterQueryRequest A meter query request. +type MeterQueryRequest struct { + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *map[string]FilterString `json:"advancedMeterGroupByFilters,omitempty"` + + // ClientId Client ID + // Useful to track progress of a query. + ClientId *string `json:"clientId,omitempty"` + + // FilterCustomerId Filtering by multiple customers. + FilterCustomerId *[]string `json:"filterCustomerId,omitempty"` + + // FilterGroupBy Simple filter for group bys with exact match. + FilterGroupBy *map[string][]string `json:"filterGroupBy,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + From *time.Time `json:"from,omitempty"` + + // GroupBy If not specified a single aggregate will be returned for each subject and time window. + // `subject` is a reserved group by value. + GroupBy *[]string `json:"groupBy,omitempty"` + + // Subject Filtering by multiple subjects. + Subject *[]string `json:"subject,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + To *time.Time `json:"to,omitempty"` + + // WindowSize If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + WindowSize *WindowSize `json:"windowSize,omitempty"` + + // WindowTimeZone The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + // If not specified, the UTC timezone will be used. + WindowTimeZone *string `json:"windowTimeZone,omitempty"` +} + +// MeterQueryResult The result of a meter query. +type MeterQueryResult struct { + // Data The usage data. + // If no data is available, an empty array is returned. + Data []MeterQueryRow `json:"data"` + + // From The start of the period the usage is queried from. + // If not specified, the usage is queried from the beginning of time. + From *time.Time `json:"from,omitempty"` + + // To The end of the period the usage is queried to. + // If not specified, the usage is queried up to the current time. + To *time.Time `json:"to,omitempty"` + + // WindowSize The window size that the usage is aggregated. + // If not specified, the usage is aggregated over the entire period. + WindowSize *WindowSize `json:"windowSize,omitempty"` +} + +// MeterQueryRow A row in the result of a meter query. +type MeterQueryRow struct { + // CustomerId The customer ID the value is aggregated over. + CustomerId *string `json:"customerId,omitempty"` + + // GroupBy The group by values the value is aggregated over. + GroupBy map[string]*string `json:"groupBy"` + + // Subject The subject the value is aggregated over. + // If not specified, the value is aggregated over all subjects. + Subject *string `json:"subject"` + + // Value The aggregated value. + Value float64 `json:"value"` + + // WindowEnd The end of the window the value is aggregated over. + WindowEnd time.Time `json:"windowEnd"` + + // WindowStart The start of the window the value is aggregated over. + WindowStart time.Time `json:"windowStart"` +} + +// MeterUpdate A meter update model. +// +// Only the properties that can be updated are included. +// For example, the slug and aggregation cannot be updated. +type MeterUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // GroupBy Named JSONPath expressions to extract the group by values from the event data. + // + // Keys must be unique and consist only alphanumeric and underscore characters. + GroupBy *map[string]string `json:"groupBy,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + // Defaults to the slug if not specified. + Name *string `json:"name,omitempty"` +} + +// NotFoundProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type NotFoundProblemResponse = UnexpectedProblemResponse + +// NotificationChannel Notification channel with webhook type. +type NotificationChannel = NotificationChannelWebhook + +// NotificationChannelCreateRequest Request with input parameters for creating new notification channel with webhook type. +type NotificationChannelCreateRequest = NotificationChannelWebhookCreateRequest + +// NotificationChannelMeta Metadata only fields of a notification channel. +type NotificationChannelMeta struct { + // Id Identifies the notification channel. + Id string `json:"id"` + + // Type Notification channel type. + Type NotificationChannelType `json:"type"` +} + +// NotificationChannelOrderBy Order by options for notification channels. +type NotificationChannelOrderBy string + +// NotificationChannelPaginatedResponse Paginated response +type NotificationChannelPaginatedResponse struct { + // Items The items in the current page. + Items []NotificationChannel `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// NotificationChannelType Type of the notification channel. +type NotificationChannelType string + +// NotificationChannelWebhook Notification channel with webhook type. +type NotificationChannelWebhook struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CustomHeaders Custom HTTP headers sent as part of the webhook request. + CustomHeaders *map[string]string `json:"customHeaders,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the channel is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Id Identifies the notification channel. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name User friendly name of the channel. + Name string `json:"name"` + + // SigningSecret Signing secret used for webhook request validation on the receiving end. + // + // Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + SigningSecret *string `json:"signingSecret,omitempty"` + + // Type Notification channel type. + Type NotificationChannelWebhookType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // Url Webhook URL where the notification is sent. + Url string `json:"url"` +} + +// NotificationChannelWebhookType Notification channel type. +type NotificationChannelWebhookType string + +// NotificationChannelWebhookCreateRequest Request with input parameters for creating new notification channel with webhook type. +type NotificationChannelWebhookCreateRequest struct { + // CustomHeaders Custom HTTP headers sent as part of the webhook request. + CustomHeaders *map[string]string `json:"customHeaders,omitempty"` + + // Disabled Whether the channel is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name User friendly name of the channel. + Name string `json:"name"` + + // SigningSecret Signing secret used for webhook request validation on the receiving end. + // + // Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + SigningSecret *string `json:"signingSecret,omitempty"` + + // Type Notification channel type. + Type NotificationChannelWebhookCreateRequestType `json:"type"` + + // Url Webhook URL where the notification is sent. + Url string `json:"url"` +} + +// NotificationChannelWebhookCreateRequestType Notification channel type. +type NotificationChannelWebhookCreateRequestType string + +// NotificationEvent Type of the notification event. +type NotificationEvent struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp when the notification event was created in RFC 3339 format. + CreatedAt time.Time `json:"createdAt"` + + // DeliveryStatus The delivery status of the notification event. + DeliveryStatus []NotificationEventDeliveryStatus `json:"deliveryStatus"` + + // Id A unique identifier of the notification event. + Id string `json:"id"` + + // Payload Timestamp when the notification event was created in RFC 3339 format. + Payload NotificationEventPayload `json:"payload"` + + // Rule The nnotification rule which generated this event. + Rule NotificationRule `json:"rule"` + + // Type Type of the notification event. + Type NotificationEventType `json:"type"` +} + +// NotificationEventBalanceThresholdPayload Payload for notification event with `entitlements.balance.threshold` type. +type NotificationEventBalanceThresholdPayload struct { + // Data The data of the payload. + Data NotificationEventBalanceThresholdPayloadData `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventBalanceThresholdPayloadType `json:"type"` +} + +// NotificationEventBalanceThresholdPayloadType Type of the notification event. +type NotificationEventBalanceThresholdPayloadType string + +// NotificationEventBalanceThresholdPayloadData Data of the payload for notification event with `entitlements.balance.threshold` type. +type NotificationEventBalanceThresholdPayloadData struct { + Customer *Customer `json:"customer,omitempty"` + Entitlement EntitlementMetered `json:"entitlement"` + Feature Feature `json:"feature"` + Subject Subject `json:"subject"` + Threshold NotificationRuleBalanceThresholdValue `json:"threshold"` + Value EntitlementValue `json:"value"` +} + +// NotificationEventDeliveryAttempt The delivery attempt of the notification event. +type NotificationEventDeliveryAttempt struct { + // Response Response returned by the notification event recipient. + Response EventDeliveryAttemptResponse `json:"response"` + + // State State of teh delivery attempt. + State NotificationEventDeliveryStatusState `json:"state"` + + // Timestamp Timestamp of the delivery attempt. + Timestamp time.Time `json:"timestamp"` +} + +// NotificationEventDeliveryStatus The delivery status of the notification event. +type NotificationEventDeliveryStatus struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Attempts List of delivery attempts. + Attempts []NotificationEventDeliveryAttempt `json:"attempts"` + + // Channel Notification channel the delivery status associated with. + Channel NotificationChannelMeta `json:"channel"` + + // NextAttempt Timestamp of the next delivery attempt. If null it means there will be no more delivery attempts. + NextAttempt *time.Time `json:"nextAttempt,omitempty"` + + // Reason The reason of the last deliverry state update. + Reason string `json:"reason"` + + // State Delivery state of the notification event to the channel. + State NotificationEventDeliveryStatusState `json:"state"` + + // UpdatedAt Timestamp of when the status was last updated in RFC 3339 format. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationEventDeliveryStatusState The delivery state of the notification event to the channel. +type NotificationEventDeliveryStatusState string + +// NotificationEventEntitlementValuePayloadBase Base data for any payload with entitlement entitlement value. +type NotificationEventEntitlementValuePayloadBase struct { + Customer *Customer `json:"customer,omitempty"` + Entitlement EntitlementMetered `json:"entitlement"` + Feature Feature `json:"feature"` + Subject Subject `json:"subject"` + Value EntitlementValue `json:"value"` +} + +// NotificationEventInvoiceCreatedPayload Payload for notification event with `invoice.created` type. +type NotificationEventInvoiceCreatedPayload struct { + // Data The data of the payload. + Data Invoice `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventInvoiceCreatedPayloadType `json:"type"` +} + +// NotificationEventInvoiceCreatedPayloadType Type of the notification event. +type NotificationEventInvoiceCreatedPayloadType string + +// NotificationEventInvoiceUpdatedPayload Payload for notification event with `invoice.updated` type. +type NotificationEventInvoiceUpdatedPayload struct { + // Data The data of the payload. + Data Invoice `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventInvoiceUpdatedPayloadType `json:"type"` +} + +// NotificationEventInvoiceUpdatedPayloadType Type of the notification event. +type NotificationEventInvoiceUpdatedPayloadType string + +// NotificationEventOrderBy Order by options for notification channels. +type NotificationEventOrderBy string + +// NotificationEventPaginatedResponse Paginated response +type NotificationEventPaginatedResponse struct { + // Items The items in the current page. + Items []NotificationEvent `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// NotificationEventPayload The delivery status of the notification event. +type NotificationEventPayload struct { + union json.RawMessage +} + +// NotificationEventResendRequest A notification event that will be re-sent. +type NotificationEventResendRequest struct { + // Channels Notification channels to which the event should be re-sent. + Channels *[]string `json:"channels,omitempty"` +} + +// NotificationEventResetPayload Payload for notification event with `entitlements.reset` type. +type NotificationEventResetPayload struct { + // Data The data of the payload. + Data NotificationEventEntitlementValuePayloadBase `json:"data"` + + // Id A unique identifier for the notification event the payload belongs to. + Id string `json:"id"` + + // Timestamp Timestamp when the notification event was created in RFC 3339 format. + Timestamp time.Time `json:"timestamp"` + + // Type Type of the notification event. + Type NotificationEventResetPayloadType `json:"type"` +} + +// NotificationEventResetPayloadType Type of the notification event. +type NotificationEventResetPayloadType string + +// NotificationEventType Type of the notification event. +type NotificationEventType string + +// NotificationRule Notification Rule. +type NotificationRule struct { + union json.RawMessage +} + +// NotificationRuleBalanceThreshold Notification rule with entitlements.balance.threshold type. +type NotificationRuleBalanceThreshold struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field containing list of features the rule applies to. + Features *[]FeatureMeta `json:"features,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Thresholds List of thresholds the rule suppose to be triggered. + Thresholds []NotificationRuleBalanceThresholdValue `json:"thresholds"` + + // Type Notification rule type. + Type NotificationRuleBalanceThresholdType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleBalanceThresholdType Notification rule type. +type NotificationRuleBalanceThresholdType string + +// NotificationRuleBalanceThresholdCreateRequest Request with input parameters for creating new notification rule with entitlements.balance.threshold type. +type NotificationRuleBalanceThresholdCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field for defining the scope of notification by feature. It may contain features by id or key. + Features *[]string `json:"features,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Thresholds List of thresholds the rule suppose to be triggered. + Thresholds []NotificationRuleBalanceThresholdValue `json:"thresholds"` + + // Type Notification rule type. + Type NotificationRuleBalanceThresholdCreateRequestType `json:"type"` +} + +// NotificationRuleBalanceThresholdCreateRequestType Notification rule type. +type NotificationRuleBalanceThresholdCreateRequestType string + +// NotificationRuleBalanceThresholdValue Threshold value with multiple supported types. +type NotificationRuleBalanceThresholdValue struct { + // Type Type of the threshold. + Type NotificationRuleBalanceThresholdValueType `json:"type"` + + // Value Value of the threshold. + Value float64 `json:"value"` +} + +// NotificationRuleBalanceThresholdValueType Type of the rule in the balance threshold specification: +// * `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period +// * `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period +// * `usage_value`: threshold defined by the usage value in the current usage period +// * `NUMBER` (**deprecated**): see `usage_value` +// * `PERCENT` (**deprecated**): see `usage_percentage` +type NotificationRuleBalanceThresholdValueType string + +// NotificationRuleCreateRequest Union type for requests creating new notification rule with certain type. +type NotificationRuleCreateRequest struct { + union json.RawMessage +} + +// NotificationRuleEntitlementReset Notification rule with entitlements.reset type. +type NotificationRuleEntitlementReset struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field containing list of features the rule applies to. + Features *[]FeatureMeta `json:"features,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleEntitlementResetType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleEntitlementResetType Notification rule type. +type NotificationRuleEntitlementResetType string + +// NotificationRuleEntitlementResetCreateRequest Request with input parameters for creating new notification rule with entitlements.reset type. +type NotificationRuleEntitlementResetCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Features Optional field for defining the scope of notification by feature. It may contain features by id or key. + Features *[]string `json:"features,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleEntitlementResetCreateRequestType `json:"type"` +} + +// NotificationRuleEntitlementResetCreateRequestType Notification rule type. +type NotificationRuleEntitlementResetCreateRequestType string + +// NotificationRuleInvoiceCreated Notification rule with invoice.created type. +type NotificationRuleInvoiceCreated struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceCreatedType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleInvoiceCreatedType Notification rule type. +type NotificationRuleInvoiceCreatedType string + +// NotificationRuleInvoiceCreatedCreateRequest Request with input parameters for creating new notification rule with invoice.created type. +type NotificationRuleInvoiceCreatedCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceCreatedCreateRequestType `json:"type"` +} + +// NotificationRuleInvoiceCreatedCreateRequestType Notification rule type. +type NotificationRuleInvoiceCreatedCreateRequestType string + +// NotificationRuleInvoiceUpdated Notification rule with invoice.updated type. +type NotificationRuleInvoiceUpdated struct { + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // Channels List of notification channels the rule applies to. + Channels []NotificationChannelMeta `json:"channels"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Id Identifies the notification rule. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceUpdatedType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// NotificationRuleInvoiceUpdatedType Notification rule type. +type NotificationRuleInvoiceUpdatedType string + +// NotificationRuleInvoiceUpdatedCreateRequest Request with input parameters for creating new notification rule with invoice.updated type. +type NotificationRuleInvoiceUpdatedCreateRequest struct { + // Channels List of notification channels the rule is applied to. + Channels []string `json:"channels"` + + // Disabled Whether the rule is disabled or not. + Disabled *bool `json:"disabled,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The user friendly name of the notification rule. + Name string `json:"name"` + + // Type Notification rule type. + Type NotificationRuleInvoiceUpdatedCreateRequestType `json:"type"` +} + +// NotificationRuleInvoiceUpdatedCreateRequestType Notification rule type. +type NotificationRuleInvoiceUpdatedCreateRequestType string + +// NotificationRuleOrderBy Order by options for notification channels. +type NotificationRuleOrderBy string + +// NotificationRulePaginatedResponse Paginated response +type NotificationRulePaginatedResponse struct { + // Items The items in the current page. + Items []NotificationRule `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// Numeric Numeric represents an arbitrary precision number. +type Numeric = string + +// OAuth2AuthorizationCodeGrantErrorType OAuth2 authorization code grant error types. +type OAuth2AuthorizationCodeGrantErrorType string + +// PackagePriceWithCommitments Package price with spend commitments. +type PackagePriceWithCommitments struct { + // Amount The price of one package. + Amount Numeric `json:"amount"` + + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // QuantityPerPackage The quantity per package. + QuantityPerPackage Numeric `json:"quantityPerPackage"` + + // Type The type of the price. + Type PackagePriceWithCommitmentsType `json:"type"` +} + +// PackagePriceWithCommitmentsType The type of the price. +type PackagePriceWithCommitmentsType string + +// PaymentDueDate PaymentDueDate contains an amount that should be paid by the given date. +type PaymentDueDate struct { + // Amount How much needs to be paid by the date. + Amount Numeric `json:"amount"` + + // Currency If different from the parent document's base currency. + Currency *CurrencyCode `json:"currency,omitempty"` + + // DueAt When the payment is due. + DueAt time.Time `json:"dueAt"` + + // Notes Other details to take into account for the due date. + Notes *string `json:"notes,omitempty"` + + // Percent Percentage of the total that should be paid by the date. + Percent *Percentage `json:"percent,omitempty"` +} + +// PaymentTermDueDate PaymentTermDueDate defines the terms for payment on a specific date. +type PaymentTermDueDate struct { + // Detail Text detail of the chosen payment terms. + Detail *string `json:"detail,omitempty"` + + // DueAt When the payment is due. + DueAt []PaymentDueDate `json:"dueAt"` + + // Notes Description of the conditions for payment. + Notes *string `json:"notes,omitempty"` + + // Type Type of terms to be applied. + Type PaymentTermDueDateType `json:"type"` +} + +// PaymentTermDueDateType Type of terms to be applied. +type PaymentTermDueDateType string + +// PaymentTermInstant PaymentTermInstant defines the terms for payment on receipt of invoice. +type PaymentTermInstant struct { + // Detail Text detail of the chosen payment terms. + Detail *string `json:"detail,omitempty"` + + // Notes Description of the conditions for payment. + Notes *string `json:"notes,omitempty"` + + // Type Type of terms to be applied. + Type PaymentTermInstantType `json:"type"` +} + +// PaymentTermInstantType Type of terms to be applied. +type PaymentTermInstantType string + +// PaymentTerms PaymentTerms defines the terms for payment. +type PaymentTerms struct { + union json.RawMessage +} + +// Percentage Numeric representation of a percentage +// +// 50% is represented as 50 +type Percentage = models.Percentage + +// Period A period with a start and end time. +type Period struct { + // From Period start time. + From time.Time `json:"from"` + + // To Period end time. + To time.Time `json:"to"` +} + +// Plan Plans provide a template for subscriptions. +type Plan struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the plan. + Currency CurrencyCode `json:"currency"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // EffectiveFrom The date and time when the plan becomes effective. When not specified, the plan is a draft. + EffectiveFrom *time.Time `json:"effectiveFrom,omitempty"` + + // EffectiveTo The date and time when the plan is no longer effective. When not specified, the plan is effective indefinitely. + EffectiveTo *time.Time `json:"effectiveTo,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` + + // Status The status of the plan. + // Computed based on the effective start and end dates: + // - draft = no effectiveFrom + // - active = effectiveFrom <= now < effectiveTo + // - archived / inactive = effectiveTo <= now + // - scheduled = now < effectiveFrom < effectiveTo + Status PlanStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationErrors List of validation errors. + ValidationErrors *[]ValidationError `json:"validationErrors"` + + // Version Version of the plan. Incremented when the plan is updated. + Version int `json:"version"` +} + +// PlanAddon The PlanAddon describes the association between a plan and add-on. +type PlanAddon struct { + // Addon Add-on object. + Addon Addon `json:"addon"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // FromPlanPhase The key of the plan phase from the add-on becomes available for purchase. + FromPlanPhase string `json:"fromPlanPhase"` + + // MaxQuantity The maximum number of times the add-on can be purchased for the plan. + // It is not applicable for add-ons with single instance type. + MaxQuantity *int `json:"maxQuantity,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` + + // ValidationErrors List of validation errors. + ValidationErrors *[]ValidationError `json:"validationErrors"` +} + +// PlanAddonCreate A plan add-on assignment create request. +type PlanAddonCreate struct { + // AddonId The add-on unique identifier in ULID format. + AddonId string `json:"addonId"` + + // FromPlanPhase The key of the plan phase from the add-on becomes available for purchase. + FromPlanPhase string `json:"fromPlanPhase"` + + // MaxQuantity The maximum number of times the add-on can be purchased for the plan. + // It is not applicable for add-ons with single instance type. + MaxQuantity *int `json:"maxQuantity,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` +} + +// PlanAddonOrderBy Order by options for plan add-on assignments. +type PlanAddonOrderBy string + +// PlanAddonPaginatedResponse Paginated response +type PlanAddonPaginatedResponse struct { + // Items The items in the current page. + Items []PlanAddon `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// PlanAddonReplaceUpdate Resource update operation model. +type PlanAddonReplaceUpdate struct { + // FromPlanPhase The key of the plan phase from the add-on becomes available for purchase. + FromPlanPhase string `json:"fromPlanPhase"` + + // MaxQuantity The maximum number of times the add-on can be purchased for the plan. + // It is not applicable for add-ons with single instance type. + MaxQuantity *int `json:"maxQuantity,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` +} + +// PlanCreate Resource create operation model. +type PlanCreate struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // Currency The currency code of the plan. + Currency CurrencyCode `json:"currency"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` +} + +// PlanOrderBy Order by options for plans. +type PlanOrderBy string + +// PlanPaginatedResponse Paginated response +type PlanPaginatedResponse struct { + // Items The items in the current page. + Items []Plan `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// PlanPhase The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. +type PlanPhase struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Duration The duration of the phase. + Duration *string `json:"duration"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // RateCards The rate cards of the plan. + RateCards []RateCard `json:"rateCards"` +} + +// PlanReference References an exact plan. +type PlanReference struct { + // Id The plan ID. + Id string `json:"id"` + + // Key The plan key. + Key string `json:"key"` + + // Version The plan version. + Version int `json:"version"` +} + +// PlanReferenceInput References an exact plan defaulting to the current active version. +type PlanReferenceInput struct { + // Key The plan key. + Key string `json:"key"` + + // Version The plan version. + Version *int `json:"version,omitempty"` +} + +// PlanReplaceUpdate Resource update operation model. +type PlanReplaceUpdate struct { + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingCadence The default billing cadence for subscriptions using this plan. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + // A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + Phases []PlanPhase `json:"phases"` + + // ProRatingConfig Default pro-rating configuration for subscriptions using this plan. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the plan. + // It determines how the billing system generates invoices and credits for the subscriptions using this plan. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` +} + +// PlanStatus The status of a plan. +type PlanStatus string + +// PlanSubscriptionChange Change subscription based on plan. +type PlanSubscriptionChange struct { + // Alignment What alignment settings the subscription should have. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // Description Description for the Subscription. + Description *string `json:"description,omitempty"` + + // Metadata Arbitrary metadata associated with the subscription. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The name of the Subscription. If not provided the plan name is used. + Name *string `json:"name,omitempty"` + + // Plan The plan reference to change to. + Plan PlanReferenceInput `json:"plan"` + + // SettlementMode The settlement mode of the subscription. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` + + // StartingPhase The key of the phase to start the subscription in. + // If not provided, the subscription will start in the first phase of the plan. + StartingPhase *string `json:"startingPhase,omitempty"` + + // Timing Timing configuration for the change, when the change should take effect. + // For changing a subscription, the accepted values depend on the subscription configuration. + Timing SubscriptionTiming `json:"timing"` +} + +// PlanSubscriptionCreate Create subscription based on plan. +type PlanSubscriptionCreate struct { + // Alignment What alignment settings the subscription should have. + Alignment *Alignment `json:"alignment,omitempty"` + + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // CustomerId The ID of the customer. Provide either the key or ID. Has presedence over the key. + CustomerId *string `json:"customerId,omitempty"` + + // CustomerKey The key of the customer. Provide either the key or ID. + CustomerKey *string `json:"customerKey,omitempty"` + + // Description Description for the Subscription. + Description *string `json:"description,omitempty"` + + // Metadata Arbitrary metadata associated with the subscription. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name The name of the Subscription. If not provided the plan name is used. + Name *string `json:"name,omitempty"` + + // Plan The plan reference to change to. + Plan PlanReferenceInput `json:"plan"` + + // SettlementMode The settlement mode of the subscription. + SettlementMode *BillingSettlementMode `json:"settlementMode,omitempty"` + + // StartingPhase The key of the phase to start the subscription in. + // If not provided, the subscription will start in the first phase of the plan. + StartingPhase *string `json:"startingPhase,omitempty"` + + // Timing Timing configuration for the change, when the change should take effect. + // The default is immediate. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// PortalToken A consumer portal token. +// +// Validator doesn't obey required for readOnly properties +// See: https://github.com/stoplightio/spectral/issues/1274 +type PortalToken struct { + // AllowedMeterSlugs Optional, if defined only the specified meters will be allowed. + AllowedMeterSlugs *[]string `json:"allowedMeterSlugs,omitempty"` + + // CreatedAt [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + CreatedAt *time.Time `json:"createdAt,omitempty"` + Expired *bool `json:"expired,omitempty"` + + // ExpiresAt [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + ExpiresAt *time.Time `json:"expiresAt,omitempty"` + + // Id ULID (Universally Unique Lexicographically Sortable Identifier). + Id *string `json:"id,omitempty"` + Subject string `json:"subject"` + + // Token The token is only returned at creation. + Token *string `json:"token,omitempty"` +} + +// PreconditionFailedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type PreconditionFailedProblemResponse = UnexpectedProblemResponse + +// PricePaymentTerm The payment term of a flat price. +// One of: in_advance or in_arrears. +type PricePaymentTerm string + +// PriceTier A price tier. +// At least one price component is required in each tier. +type PriceTier struct { + // FlatPrice The flat price component of the tier. + FlatPrice *FlatPrice `json:"flatPrice"` + + // UnitPrice The unit price component of the tier. + UnitPrice *UnitPrice `json:"unitPrice"` + + // UpToAmount Up to and including to this quantity will be contained in the tier. + // If null, the tier is open-ended. + UpToAmount *Numeric `json:"upToAmount,omitempty"` +} + +// ProRatingConfig Configuration for pro-rating behavior. +type ProRatingConfig struct { + // Enabled Whether pro-rating is enabled for this plan. + Enabled bool `json:"enabled"` + + // Mode How to handle pro-rating for billing period changes. + Mode ProRatingMode `json:"mode"` +} + +// ProRatingMode Pro-rating mode options for handling billing period changes. +type ProRatingMode string + +// Progress Progress describes a progress of a task. +type Progress struct { + // Failed Failed is the number of items that failed + Failed uint64 `json:"failed"` + + // Success Success is the number of items that succeeded + Success uint64 `json:"success"` + + // Total The total number of items to process + Total uint64 `json:"total"` + + // UpdatedAt The time the progress was last updated + UpdatedAt time.Time `json:"updatedAt"` +} + +// RateCard A rate card defines the pricing and entitlement of a feature or service. +type RateCard struct { + union json.RawMessage +} + +// RateCardBooleanEntitlement Entitlement template of a boolean entitlement. +type RateCardBooleanEntitlement struct { + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type RateCardBooleanEntitlementType `json:"type"` +} + +// RateCardBooleanEntitlementType defines model for RateCardBooleanEntitlement.Type. +type RateCardBooleanEntitlementType string + +// RateCardEntitlement Entitlement templates are used to define the entitlements of a plan. +// Features are omitted from the entitlement template, as they are defined in the rate card. +type RateCardEntitlement struct { + union json.RawMessage +} + +// RateCardFlatFee A flat fee rate card defines a one-time purchase or a recurring fee. +type RateCardFlatFee struct { + // BillingCadence The billing cadence of the rate card. + // When null it means it is a one time fee. + BillingCadence *string `json:"billingCadence"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discount of the rate card. For flat fee rate cards only percentage discounts are supported. + // Only available when price is set. + Discounts *Discounts `json:"discounts,omitempty"` + + // EntitlementTemplate The entitlement of the rate card. + // Only available when featureKey is set. + EntitlementTemplate *RateCardEntitlement `json:"entitlementTemplate,omitempty"` + + // FeatureKey The feature the customer is entitled to use. + FeatureKey *string `json:"featureKey,omitempty"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *FlatPriceWithPaymentTerm `json:"price"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Type The type of the RateCard. + Type RateCardFlatFeeType `json:"type"` +} + +// RateCardFlatFeeType The type of the RateCard. +type RateCardFlatFeeType string + +// RateCardMeteredEntitlement The entitlement template with a metered entitlement. +type RateCardMeteredEntitlement struct { + // IsSoftLimit If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + IsSoftLimit *bool `json:"isSoftLimit,omitempty"` + + // IssueAfterReset You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + // If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + // That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + // Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + IssueAfterReset *float64 `json:"issueAfterReset,omitempty"` + + // IssueAfterResetPriority Defines the grant priority for the default grant. + IssueAfterResetPriority *uint8 `json:"issueAfterResetPriority,omitempty"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + + // PreserveOverageAtReset If true, the overage is preserved at reset. If false, the usage is reset to 0. + PreserveOverageAtReset *bool `json:"preserveOverageAtReset,omitempty"` + Type RateCardMeteredEntitlementType `json:"type"` + + // UsagePeriod The interval of the metered entitlement. + // Defaults to the billing cadence of the rate card. + UsagePeriod *string `json:"usagePeriod,omitempty"` +} + +// RateCardMeteredEntitlementType defines model for RateCardMeteredEntitlement.Type. +type RateCardMeteredEntitlementType string + +// RateCardStaticEntitlement Entitlement template of a static entitlement. +type RateCardStaticEntitlement struct { + // Config The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + Config json.RawMessage `json:"config"` + + // Metadata Additional metadata for the feature. + Metadata *Metadata `json:"metadata,omitempty"` + Type RateCardStaticEntitlementType `json:"type"` +} + +// RateCardStaticEntitlementType defines model for RateCardStaticEntitlement.Type. +type RateCardStaticEntitlementType string + +// RateCardUsageBased A usage-based rate card defines a price based on usage. +type RateCardUsageBased struct { + // BillingCadence The billing cadence of the rate card. + BillingCadence string `json:"billingCadence"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts of the rate card. + // + // Flat fee rate cards only support percentage discounts. + Discounts *Discounts `json:"discounts,omitempty"` + + // EntitlementTemplate The entitlement of the rate card. + // Only available when featureKey is set. + EntitlementTemplate *RateCardEntitlement `json:"entitlementTemplate,omitempty"` + + // FeatureKey The feature the customer is entitled to use. + FeatureKey *string `json:"featureKey,omitempty"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *RateCardUsageBasedPrice `json:"price"` + + // TaxConfig The tax config of the rate card. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // Type The type of the RateCard. + Type RateCardUsageBasedType `json:"type"` +} + +// RateCardUsageBasedType The type of the RateCard. +type RateCardUsageBasedType string + +// RateCardUsageBasedPrice The price of the usage based rate card. +type RateCardUsageBasedPrice struct { + union json.RawMessage +} + +// RecurringPeriod Recurring period with an interval and an anchor. +type RecurringPeriod struct { + // Anchor A date-time anchor to base the recurring period on. + Anchor time.Time `json:"anchor"` + + // Interval The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + Interval RecurringPeriodInterval `json:"interval"` + + // IntervalISO The unit of time for the interval in ISO8601 format. + IntervalISO string `json:"intervalISO"` +} + +// RecurringPeriodCreateInput Recurring period with an interval and an anchor. +type RecurringPeriodCreateInput struct { + // Anchor A date-time anchor to base the recurring period on. + Anchor *time.Time `json:"anchor,omitempty"` + + // Interval The unit of time for the interval. + Interval RecurringPeriodInterval `json:"interval"` +} + +// RecurringPeriodInterval Period duration for the recurrence +type RecurringPeriodInterval struct { + union json.RawMessage +} + +// RecurringPeriodInterval0 defines model for . +type RecurringPeriodInterval0 = string + +// RecurringPeriodIntervalEnum The unit of time for the interval. +// One of: `day`, `week`, `month`, or `year`. +type RecurringPeriodIntervalEnum string + +// RecurringPeriodV2 Recurring period with an interval and an anchor. +type RecurringPeriodV2 struct { + // Anchor A date-time anchor to base the recurring period on. + Anchor time.Time `json:"anchor"` + + // Interval The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + Interval RecurringPeriodInterval `json:"interval"` +} + +// RemovePhaseShifting The direction of the phase shift when a phase is removed. +type RemovePhaseShifting string + +// ResetEntitlementUsageInput Reset parameters +type ResetEntitlementUsageInput struct { + // EffectiveAt The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored. + EffectiveAt *time.Time `json:"effectiveAt,omitempty"` + + // PreserveOverage Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior. + // - If true, the overage is preserved. + // - If false, the overage is forgiven. + PreserveOverage *bool `json:"preserveOverage,omitempty"` + + // RetainAnchor Determines whether the usage period anchor is retained or reset to the effectiveAt time. + // - If true, the usage period anchor is retained. + // - If false, the usage period anchor is reset to the effectiveAt time. + RetainAnchor *bool `json:"retainAnchor,omitempty"` +} + +// SandboxApp Sandbox app can be used for testing OpenMeter features. +// +// The app is not creating anything in external systems, thus it is safe to use for +// verifying OpenMeter features. +type SandboxApp struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // Type The app's type is Sandbox. + Type SandboxAppType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SandboxAppType The app's type is Sandbox. +type SandboxAppType string + +// SandboxAppReplaceUpdate Resource update operation model. +type SandboxAppReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Type The app's type is Sandbox. + Type SandboxAppReplaceUpdateType `json:"type"` +} + +// SandboxAppReplaceUpdateType The app's type is Sandbox. +type SandboxAppReplaceUpdateType string + +// SandboxCustomerAppData Sandbox Customer App Data. +type SandboxCustomerAppData struct { + // App The installed sandbox app this data belongs to. + App *SandboxApp `json:"app,omitempty"` + + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // Type The app name. + Type SandboxCustomerAppDataType `json:"type"` +} + +// SandboxCustomerAppDataType The app name. +type SandboxCustomerAppDataType string + +// ServiceUnavailableProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type ServiceUnavailableProblemResponse = UnexpectedProblemResponse + +// SortOrder The order direction. +type SortOrder string + +// StripeAPIKeyInput The Stripe API key input. +// Used to authenticate with the Stripe API. +type StripeAPIKeyInput struct { + SecretAPIKey string `json:"secretAPIKey"` +} + +// StripeApp A installed Stripe app object. +type StripeApp struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Listing The marketplace listing that this installed app is based on. + Listing MarketplaceListing `json:"listing"` + + // Livemode Livemode, true if the app is in production mode. + Livemode bool `json:"livemode"` + + // MaskedAPIKey The masked API key. + // Only shows the first 8 and last 3 characters. + MaskedAPIKey string `json:"maskedAPIKey"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Status Status of the app connection. + Status AppStatus `json:"status"` + + // StripeAccountId The Stripe account ID. + StripeAccountId string `json:"stripeAccountId"` + + // Type The app's type is Stripe. + Type StripeAppType `json:"type"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// StripeAppType The app's type is Stripe. +type StripeAppType string + +// StripeAppReplaceUpdate Resource update operation model. +type StripeAppReplaceUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // SecretAPIKey The Stripe API key. + SecretAPIKey *string `json:"secretAPIKey,omitempty"` + + // Type The app's type is Stripe. + Type StripeAppReplaceUpdateType `json:"type"` +} + +// StripeAppReplaceUpdateType The app's type is Stripe. +type StripeAppReplaceUpdateType string + +// StripeCheckoutSessionMode Stripe CheckoutSession.mode +type StripeCheckoutSessionMode string + +// StripeCustomerAppData Stripe Customer App Data. +type StripeCustomerAppData struct { + // App The installed stripe app this data belongs to. + App *StripeApp `json:"app,omitempty"` + + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // StripeDefaultPaymentMethodId The Stripe default payment method ID. + StripeDefaultPaymentMethodId *string `json:"stripeDefaultPaymentMethodId,omitempty"` + + // Type The app name. + Type StripeCustomerAppDataType `json:"type"` +} + +// StripeCustomerAppDataType The app name. +type StripeCustomerAppDataType string + +// StripeCustomerAppDataBase Stripe Customer App Data Base. +type StripeCustomerAppDataBase struct { + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // StripeDefaultPaymentMethodId The Stripe default payment method ID. + StripeDefaultPaymentMethodId *string `json:"stripeDefaultPaymentMethodId,omitempty"` +} + +// StripeCustomerAppDataCreateOrUpdateItem Stripe Customer App Data. +type StripeCustomerAppDataCreateOrUpdateItem struct { + // Id The app ID. + // If not provided, it will use the global default for the app type. + Id *string `json:"id,omitempty"` + + // StripeCustomerId The Stripe customer ID. + StripeCustomerId string `json:"stripeCustomerId"` + + // StripeDefaultPaymentMethodId The Stripe default payment method ID. + StripeDefaultPaymentMethodId *string `json:"stripeDefaultPaymentMethodId,omitempty"` + + // Type The app name. + Type StripeCustomerAppDataCreateOrUpdateItemType `json:"type"` +} + +// StripeCustomerAppDataCreateOrUpdateItemType The app name. +type StripeCustomerAppDataCreateOrUpdateItemType string + +// StripeCustomerPortalSession Stripe customer portal session. +// +// See: https://docs.stripe.com/api/customer_portal/sessions/object +type StripeCustomerPortalSession struct { + // ConfigurationId Configuration used to customize the customer portal. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + ConfigurationId string `json:"configurationId"` + + // CreatedAt Created at. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + CreatedAt time.Time `json:"createdAt"` + + // Id The ID of the customer portal session. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + Id string `json:"id"` + + // Livemode Livemode. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + Livemode bool `json:"livemode"` + + // Locale Status. + // /** + // The IETF language tag of the locale customer portal is displayed in. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + Locale string `json:"locale"` + + // ReturnUrl Return URL. + // + // See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + ReturnUrl string `json:"returnUrl"` + + // StripeCustomerId The ID of the stripe customer. + StripeCustomerId string `json:"stripeCustomerId"` + + // Url /** + // The ID of the customer.The URL to redirect the customer to after they have completed + // their requested actions. + Url string `json:"url"` +} + +// StripeTaxConfig The tax config for Stripe. +type StripeTaxConfig struct { + // Code Product tax code. + // + // See: https://docs.stripe.com/tax/tax-codes + Code string `json:"code"` +} + +// StripeWebhookEvent Stripe webhook event. +type StripeWebhookEvent struct { + // Created The event created timestamp. + Created int32 `json:"created"` + + // Data The event data. + Data struct { + Object interface{} `json:"object"` + } `json:"data"` + + // Id The event ID. + Id string `json:"id"` + + // Livemode Live mode. + Livemode bool `json:"livemode"` + + // Type The event type. + Type string `json:"type"` +} + +// StripeWebhookResponse Stripe webhook response. +type StripeWebhookResponse struct { + // AppId ULID (Universally Unique Lexicographically Sortable Identifier). + AppId string `json:"appId"` + + // CustomerId ULID (Universally Unique Lexicographically Sortable Identifier). + CustomerId *string `json:"customerId,omitempty"` + Message *string `json:"message,omitempty"` + + // NamespaceId ULID (Universally Unique Lexicographically Sortable Identifier). + NamespaceId string `json:"namespaceId"` +} + +// Subject A subject is a unique identifier for a usage attribution by its key. +// Subjects only exist in the concept of metering. +// Subjects are optional to create and work as an enrichment for the subject key like displayName, metadata, etc. +// Subjects are useful when you are reporting usage events with your own database ID but want to enrich the subject with a human-readable name or metadata. +// For most use cases, a subject is equivalent to a customer. +// +// ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. +type Subject struct { + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // CurrentPeriodEnd The end of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"` + + // CurrentPeriodStart The start of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodStart *time.Time `json:"currentPeriodStart,omitempty"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // DisplayName A human-readable display name for the subject. + DisplayName *string `json:"displayName,omitempty"` + + // Id A unique identifier for the subject. + Id string `json:"id"` + + // Key A unique, human-readable identifier for the subject. + // This is typically a database ID or a customer key. + Key string `json:"key"` + + // Metadata Metadata for the subject. + Metadata *map[string]interface{} `json:"metadata,omitempty"` + + // StripeCustomerId The Stripe customer ID for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + StripeCustomerId *string `json:"stripeCustomerId,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubjectUpsert A subject is a unique identifier for a user or entity. +// +// ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. +type SubjectUpsert struct { + // CurrentPeriodEnd The end of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"` + + // CurrentPeriodStart The start of the current period for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CurrentPeriodStart *time.Time `json:"currentPeriodStart,omitempty"` + + // DisplayName A human-readable display name for the subject. + DisplayName *string `json:"displayName,omitempty"` + + // Key A unique, human-readable identifier for the subject. + // This is typically a database ID or a customer key. + Key string `json:"key"` + + // Metadata Metadata for the subject. + Metadata *map[string]interface{} `json:"metadata,omitempty"` + + // StripeCustomerId The Stripe customer ID for the subject. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + StripeCustomerId *string `json:"stripeCustomerId,omitempty"` +} + +// Subscription Subscription is an exact subscription instance. +type Subscription struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Alignment Alignment configuration for the plan. + Alignment *Alignment `json:"alignment,omitempty"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // BillingAnchor The normalizedbilling anchor of the subscription. + BillingAnchor time.Time `json:"billingAnchor"` + + // BillingCadence The billing cadence for the subscriptions. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the subscription. + // Will be revised once we add multi currency support. + Currency CurrencyCode `json:"currency"` + + // CustomerId The customer ID of the subscription. + CustomerId string `json:"customerId"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Plan The plan of the subscription. + Plan *PlanReference `json:"plan,omitempty"` + + // ProRatingConfig The pro-rating configuration for the subscriptions. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the subscription. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode BillingSettlementMode `json:"settlementMode"` + + // Status The status of the subscription. + Status SubscriptionStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionAddon A subscription add-on, represents concrete instances of an add-on for a given subscription. +type SubscriptionAddon struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Addon Partially populated add-on properties. + Addon struct { + // Id The ID of the add-on. + Id string `json:"id"` + + // InstanceType The instance type of the add-on. + InstanceType AddonInstanceType `json:"instanceType"` + + // Key A semi-unique identifier for the resource. + Key string `json:"key"` + + // Version The version of the Add-on which templates this instance. + Version int `json:"version"` + } `json:"addon"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Quantity The quantity of the add-on. Always 1 for single instance add-ons. + Quantity int `json:"quantity"` + + // QuantityAt For which point in time the quantity was resolved to. + QuantityAt time.Time `json:"quantityAt"` + + // RateCards The rate cards of the add-on. + RateCards []SubscriptionAddonRateCard `json:"rateCards"` + + // SubscriptionId The ID of the subscription. + SubscriptionId string `json:"subscriptionId"` + + // Timeline The timeline of the add-on. The returned periods are sorted and continuous. + Timeline []SubscriptionAddonTimelineSegment `json:"timeline"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionAddonCreate A subscription add-on create body. +type SubscriptionAddonCreate struct { + // Addon The add-on to create. + Addon struct { + // Id The ID of the add-on. + Id string `json:"id"` + } `json:"addon"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Quantity The quantity of the add-on. Always 1 for single instance add-ons. + Quantity int `json:"quantity"` + + // Timing The timing of the operation. After the create or update, a new entry will be created in the timeline. + Timing SubscriptionTiming `json:"timing"` +} + +// SubscriptionAddonRateCard A rate card for a subscription add-on. +type SubscriptionAddonRateCard struct { + // AffectedSubscriptionItemIds The IDs of the subscription items that this rate card belongs to. + AffectedSubscriptionItemIds []string `json:"affectedSubscriptionItemIds"` + + // RateCard The rate card. + RateCard RateCard `json:"rateCard"` +} + +// SubscriptionAddonTimelineSegment A subscription add-on event. +type SubscriptionAddonTimelineSegment struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Quantity The quantity of the add-on for the given period. + Quantity int `json:"quantity"` +} + +// SubscriptionAddonUpdate Resource create or update operation model. +type SubscriptionAddonUpdate struct { + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name *string `json:"name,omitempty"` + + // Quantity The quantity of the add-on. Always 1 for single instance add-ons. + Quantity *int `json:"quantity,omitempty"` + + // Timing The timing of the operation. After the create or update, a new entry will be created in the timeline. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// SubscriptionAlignment Alignment details enriched with the current billing period. +type SubscriptionAlignment struct { + // BillablesMustAlign Whether all Billable items and RateCards must align. + // Alignment means the Price's BillingCadence must align for both duration and anchor time. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + BillablesMustAlign *bool `json:"billablesMustAlign,omitempty"` + + // CurrentAlignedBillingPeriod The current billing period. Only has value if the subscription is aligned and active. + CurrentAlignedBillingPeriod *Period `json:"currentAlignedBillingPeriod,omitempty"` +} + +// SubscriptionBadRequestErrorResponse The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. +type SubscriptionBadRequestErrorResponse struct { + // Detail A human-readable explanation specific to this occurrence of the problem. + Detail string `json:"detail"` + + // Extensions Additional properties specific to the problem type may be present. + Extensions *SubscriptionErrorExtensions `json:"extensions,omitempty"` + + // Instance A URI reference that identifies the specific occurrence of the problem. + Instance string `json:"instance"` + + // Status The HTTP status code generated by the origin server for this occurrence of the problem. + Status *int16 `json:"status,omitempty"` + + // Title A a short, human-readable summary of the problem type. + Title string `json:"title"` + + // Type Type contains a URI that identifies the problem type. + Type string `json:"type"` +} + +// SubscriptionChange Change a subscription. +type SubscriptionChange struct { + union json.RawMessage +} + +// SubscriptionChangeResponseBody Response body for subscription change. +type SubscriptionChangeResponseBody struct { + // Current The current subscription before the change. + Current Subscription `json:"current"` + + // Next The new state of the subscription after the change. + Next SubscriptionExpanded `json:"next"` +} + +// SubscriptionConflictErrorResponse The request could not be completed due to a conflict with the current state of the target resource. +// Variants with ErrorExtensions specific to subscriptions. +type SubscriptionConflictErrorResponse struct { + // Detail A human-readable explanation specific to this occurrence of the problem. + Detail string `json:"detail"` + + // Extensions Additional properties specific to the problem type may be present. + Extensions *SubscriptionErrorExtensions `json:"extensions,omitempty"` + + // Instance A URI reference that identifies the specific occurrence of the problem. + Instance string `json:"instance"` + + // Status The HTTP status code generated by the origin server for this occurrence of the problem. + Status *int16 `json:"status,omitempty"` + + // Title A a short, human-readable summary of the problem type. + Title string `json:"title"` + + // Type Type contains a URI that identifies the problem type. + Type string `json:"type"` +} + +// SubscriptionCreate Create a subscription. +type SubscriptionCreate struct { + union json.RawMessage +} + +// SubscriptionEdit Subscription edit input. +type SubscriptionEdit struct { + // Customizations Batch processing commands for manipulating running subscriptions. + // The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + Customizations []SubscriptionEditOperation `json:"customizations"` + + // Timing Whether the billing period should be restarted.Timing configuration to allow for the changes to take effect at different times. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// SubscriptionEditOperation The operation to be performed on the subscription. +type SubscriptionEditOperation struct { + union json.RawMessage +} + +// SubscriptionErrorExtensions Error extensions for the Subscription Errors. +type SubscriptionErrorExtensions struct { + ValidationErrors []ErrorExtension `json:"validationErrors"` +} + +// SubscriptionExpanded Expanded subscription +type SubscriptionExpanded struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // Alignment Alignment details enriched with the current billing period. + Alignment *SubscriptionAlignment `json:"alignment,omitempty"` + + // Annotations Set of key-value pairs managed by the system. Cannot be modified by user. + Annotations *Annotations `json:"annotations,omitempty"` + + // BillingAnchor The normalizedbilling anchor of the subscription. + BillingAnchor time.Time `json:"billingAnchor"` + + // BillingCadence The billing cadence for the subscriptions. + // Defines how often customers are billed using ISO8601 duration format. + // Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + BillingCadence string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // Currency The currency code of the subscription. + // Will be revised once we add multi currency support. + Currency CurrencyCode `json:"currency"` + + // CustomerId The customer ID of the subscription. + CustomerId string `json:"customerId"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Phases The phases of the subscription. + Phases []SubscriptionPhaseExpanded `json:"phases"` + + // Plan The plan of the subscription. + Plan *PlanReference `json:"plan,omitempty"` + + // ProRatingConfig The pro-rating configuration for the subscriptions. + ProRatingConfig *ProRatingConfig `json:"proRatingConfig,omitempty"` + + // SettlementMode The settlement mode of the subscription. + // - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + // - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + // This is the default and most common settlement mode. + SettlementMode BillingSettlementMode `json:"settlementMode"` + + // Status The status of the subscription. + Status SubscriptionStatus `json:"status"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionItem The actual contents of the Subscription, what the user gets, what they pay, etc... +type SubscriptionItem struct { + // ActiveFrom The cadence start of the resource. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The cadence end of the resource. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // BillingCadence The billing cadence of the rate card. + // When null, the rate card is a one-time purchase. + BillingCadence *string `json:"billingCadence"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts applied to the rate card. + Discounts *Discounts `json:"discounts,omitempty"` + + // FeatureKey The feature's key (if present). + FeatureKey *string `json:"featureKey,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // Included Describes what access is gained via the SubscriptionItem + Included *SubscriptionItemIncluded `json:"included,omitempty"` + + // Key The identifier of the RateCard. + // SubscriptionItem/RateCard can be identified, it has a reference: + // + // 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + // 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across versions) + // 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version of a Feature + // + // 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + // + // We say "referenced by the Price" regardless of how a price itself is referenced, it colloquially makes sense to say "paying the same price for the same thing". In practice this should be derived from what's printed on the invoice line-item. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // Price The price of the rate card. + // When null, the feature or service is free. + Price *RateCardUsageBasedPrice `json:"price"` + + // TaxConfig The tax config of the Subscription Item. + // When undefined, the tax config of the feature or the default tax config of the plan is used. + TaxConfig *TaxConfig `json:"taxConfig,omitempty"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionItemIncluded Included contents like Entitlement, or the Feature. +type SubscriptionItemIncluded struct { + // Entitlement The entitlement of the Subscription Item. + Entitlement *Entitlement `json:"entitlement,omitempty"` + + // Feature The feature the customer is entitled to use. + Feature Feature `json:"feature"` +} + +// SubscriptionPaginatedResponse Paginated response +type SubscriptionPaginatedResponse struct { + // Items The items in the current page. + Items []Subscription `json:"items"` + + // Page The page index. + Page int `json:"page"` + + // PageSize The maximum number of items per page. + PageSize int `json:"pageSize"` + + // TotalCount The total number of items. + TotalCount int `json:"totalCount"` +} + +// SubscriptionPhaseCreate Subscription phase create input. +type SubscriptionPhaseCreate struct { + // Description The description of the phase. + Description *string `json:"description,omitempty"` + + // Discounts The discounts on the plan. + Discounts *Discounts `json:"discounts,omitempty"` + + // Duration The intended duration of the new phase. + // Duration is required when the phase will not be the last phase. + Duration *string `json:"duration,omitempty"` + + // Key A locally unique identifier for the phase. + Key string `json:"key"` + + // Name The name of the phase. + Name string `json:"name"` + + // StartAfter Interval after the subscription starts to transition to the phase. + // When null, the phase starts immediately after the subscription starts. + StartAfter *string `json:"startAfter"` +} + +// SubscriptionPhaseExpanded Expanded subscription phase +type SubscriptionPhaseExpanded struct { + // ActiveFrom The time from which the phase is active. + ActiveFrom time.Time `json:"activeFrom"` + + // ActiveTo The until which the Phase is active. + ActiveTo *time.Time `json:"activeTo,omitempty"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Description Optional description of the resource. Maximum 1024 characters. + Description *string `json:"description,omitempty"` + + // Discounts The discounts on the plan. + Discounts *Discounts `json:"discounts,omitempty"` + + // Id A unique identifier for the resource. + Id string `json:"id"` + + // ItemTimelines Includes all versions of the items on each key, including all edits, scheduled changes, etc... + ItemTimelines map[string][]SubscriptionItem `json:"itemTimelines"` + + // Items The items of the phase. The structure is flattened to better conform to the Plan API. + // The timelines are flattened according to the following rules: + // - for the current phase, the `items` contains only the active item for each key + // - for past phases, the `items` contains only the last item for each key + // - for future phases, the `items` contains only the first version of the item for each key + Items []SubscriptionItem `json:"items"` + + // Key A locally unique identifier for the resource. + Key string `json:"key"` + + // Metadata Additional metadata for the resource. + Metadata *Metadata `json:"metadata,omitempty"` + + // Name Human-readable name for the resource. Between 1 and 256 characters. + Name string `json:"name"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// SubscriptionStatus Subscription status. +type SubscriptionStatus string + +// SubscriptionTiming Subscription edit timing defined when the changes should take effect. +// If the provided configuration is not supported by the subscription, an error will be returned. +type SubscriptionTiming struct { + union json.RawMessage +} + +// SubscriptionTiming1 [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. +type SubscriptionTiming1 = time.Time + +// SubscriptionTimingEnum Subscription edit timing. +// When immediate, the requested changes take effect immediately. +// When nextBillingCycle, the requested changes take effect at the next billing cycle. +type SubscriptionTimingEnum string + +// TaxBehavior Tax behavior. +// +// This enum is used to specify whether tax is included in the price or excluded from the price. +type TaxBehavior string + +// TaxConfig Set of provider specific tax configs. +type TaxConfig struct { + // Behavior Tax behavior. + // + // If not specified the billing profile is used to determine the tax behavior. + // If not specified in the billing profile, the provider's default behavior is used. + Behavior *TaxBehavior `json:"behavior,omitempty"` + + // CustomInvoicing Custom invoicing tax config. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + CustomInvoicing *CustomInvoicingTaxConfig `json:"customInvoicing,omitempty"` + + // Stripe Stripe tax config. + // Deprecated: this property has been marked as deprecated upstream, but no `x-deprecated-reason` was set + Stripe *StripeTaxConfig `json:"stripe,omitempty"` + + // TaxCodeId Tax code reference. + // + // When both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence: + // the referenced tax code entity is used and `stripe.code` is ignored. + TaxCodeId *string `json:"taxCodeId,omitempty"` +} + +// TieredPriceMode The mode of the tiered price. +type TieredPriceMode string + +// TieredPriceWithCommitments Tiered price with spend commitments. +type TieredPriceWithCommitments struct { + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // Mode Defines if the tiering mode is volume-based or graduated: + // - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + // - In `graduated` tiering, pricing can change as the quantity grows. + Mode TieredPriceMode `json:"mode"` + + // Tiers The tiers of the tiered price. + // At least one price component is required in each tier. + Tiers []PriceTier `json:"tiers"` + + // Type The type of the price. + // + // One of: flat, unit, or tiered. + Type TieredPriceWithCommitmentsType `json:"type"` +} + +// TieredPriceWithCommitmentsType The type of the price. +// +// One of: flat, unit, or tiered. +type TieredPriceWithCommitmentsType string + +// ULIDOrExternalKey ULID (Universally Unique Lexicographically Sortable Identifier) or external unique key. +type ULIDOrExternalKey = string + +// UnauthorizedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type UnauthorizedProblemResponse = UnexpectedProblemResponse + +// UnexpectedProblemResponse A Problem Details object (RFC 7807). +// Additional properties specific to the problem type may be present. +type UnexpectedProblemResponse = models.StatusProblem + +// UnitPrice Unit price. +type UnitPrice struct { + // Amount The amount of the unit price. + Amount Numeric `json:"amount"` + + // Type The type of the price. + Type UnitPriceType `json:"type"` +} + +// UnitPriceType The type of the price. +type UnitPriceType string + +// UnitPriceWithCommitments Unit price with spend commitments. +type UnitPriceWithCommitments struct { + // Amount The amount of the unit price. + Amount Numeric `json:"amount"` + + // MaximumAmount The customer is limited to spend at most the amount. + MaximumAmount *Numeric `json:"maximumAmount,omitempty"` + + // MinimumAmount The customer is committed to spend at least the amount. + MinimumAmount *Numeric `json:"minimumAmount,omitempty"` + + // Type The type of the price. + Type UnitPriceWithCommitmentsType `json:"type"` +} + +// UnitPriceWithCommitmentsType The type of the price. +type UnitPriceWithCommitmentsType string + +// ValidationError Validation errors providing detailed description of the issue. +type ValidationError struct { + // Attributes Additional attributes. + Attributes *Annotations `json:"attributes,omitempty"` + + // Code The machine readable description of the error. + Code string `json:"code"` + + // Field The path to the field. + Field string `json:"field"` + + // Message The human readable description of the error. + Message string `json:"message"` +} + +// ValidationIssue ValidationIssue captures any validation issues related to the invoice. +// +// Issues with severity "critical" will prevent the invoice from being issued. +type ValidationIssue struct { + // Code Machine indentifiable code for the issue, if available. + Code *string `json:"code,omitempty"` + + // Component Component reporting the issue. + Component string `json:"component"` + + // CreatedAt Timestamp of when the resource was created. + CreatedAt time.Time `json:"createdAt"` + + // DeletedAt Timestamp of when the resource was permanently deleted. + DeletedAt *time.Time `json:"deletedAt,omitempty"` + + // Field The field that the issue is related to, if available in JSON path format. + Field *string `json:"field,omitempty"` + + // Id ID of the charge or discount. + Id string `json:"id"` + + // Message A human-readable description of the issue. + Message string `json:"message"` + + // Metadata Additional context for the issue. + Metadata *Metadata `json:"metadata,omitempty"` + + // Severity The severity of the issue. + Severity ValidationIssueSeverity `json:"severity"` + + // UpdatedAt Timestamp of when the resource was last updated. + UpdatedAt time.Time `json:"updatedAt"` +} + +// ValidationIssueSeverity ValidationIssueSeverity describes the severity of a validation issue. +// +// Issues with severity "critical" will prevent the invoice from being issued. +type ValidationIssueSeverity string + +// VoidInvoiceActionCreate InvoiceVoidAction describes how to handle the voided line items. +type VoidInvoiceActionCreate struct { + // Action The action to take on the line items. + Action VoidInvoiceLineActionCreate `json:"action"` + + // Percentage How much of the total line items to be voided? (e.g. 100% means all charges are voided) + Percentage Percentage `json:"percentage"` +} + +// VoidInvoiceActionCreateItem InvoiceVoidAction describes how to handle the voided line items. +type VoidInvoiceActionCreateItem struct { + // Action The action to take on the line items. + Action VoidInvoiceLineActionCreateItem `json:"action"` + + // Percentage How much of the total line items to be voided? (e.g. 100% means all charges are voided) + Percentage Percentage `json:"percentage"` +} + +// VoidInvoiceActionInput Request to void an invoice +type VoidInvoiceActionInput struct { + // Action The action to take on the voided line items. + Action VoidInvoiceActionCreate `json:"action"` + + // Overrides Per line item overrides for the action. + // + // If not specified, the `action` will be applied to all line items. + Overrides *[]VoidInvoiceActionLineOverride `json:"overrides,omitempty"` + + // Reason The reason for voiding the invoice. + Reason string `json:"reason"` +} + +// VoidInvoiceActionLineOverride VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding. +type VoidInvoiceActionLineOverride struct { + // Action The action to take on the line item. + Action VoidInvoiceActionCreateItem `json:"action"` + + // LineId The line item ID to override. + LineId string `json:"lineId"` +} + +// VoidInvoiceLineActionCreate VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. +type VoidInvoiceLineActionCreate struct { + union json.RawMessage +} + +// VoidInvoiceLineActionCreateItem VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. +type VoidInvoiceLineActionCreateItem struct { + union json.RawMessage +} + +// VoidInvoiceLineDiscardAction VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. +type VoidInvoiceLineDiscardAction struct { + // Type The action to take on the line item. + Type VoidInvoiceLineDiscardActionType `json:"type"` +} + +// VoidInvoiceLineDiscardActionType The action to take on the line item. +type VoidInvoiceLineDiscardActionType string + +// VoidInvoiceLinePendingActionCreate VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. +type VoidInvoiceLinePendingActionCreate struct { + // NextInvoiceAt The time at which the line item should be invoiced again. + // + // If not provided, the line item will be re-invoiced now. + NextInvoiceAt *time.Time `json:"nextInvoiceAt,omitempty"` + + // Type The action to take on the line item. + Type VoidInvoiceLinePendingActionCreateType `json:"type"` +} + +// VoidInvoiceLinePendingActionCreateType The action to take on the line item. +type VoidInvoiceLinePendingActionCreateType string + +// VoidInvoiceLinePendingActionCreateItem VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. +type VoidInvoiceLinePendingActionCreateItem struct { + // NextInvoiceAt The time at which the line item should be invoiced again. + // + // If not provided, the line item will be re-invoiced now. + NextInvoiceAt *time.Time `json:"nextInvoiceAt,omitempty"` + + // Type The action to take on the line item. + Type VoidInvoiceLinePendingActionCreateItemType `json:"type"` +} + +// VoidInvoiceLinePendingActionCreateItemType The action to take on the line item. +type VoidInvoiceLinePendingActionCreateItemType string + +// WindowSize Aggregation window size. +type WindowSize string + +// WindowedBalanceHistory The windowed balance history. +type WindowedBalanceHistory struct { + // BurndownHistory Grant burndown history. + BurndownHistory []GrantBurnDownHistorySegment `json:"burndownHistory"` + + // WindowedHistory The windowed balance history. + // - It only returns rows for windows where there was usage. + // - The windows are inclusive at their start and exclusive at their end. + // - The last window may be smaller than the window size and is inclusive at both ends. + WindowedHistory []BalanceHistoryWindow `json:"windowedHistory"` +} + +// AddonOrderByOrderingOrder The order direction. +type AddonOrderByOrderingOrder = SortOrder + +// AddonOrderByOrderingOrderBy Order by options for add-ons. +type AddonOrderByOrderingOrderBy = AddonOrderBy + +// BillingProfileCustomerOverrideOrderByOrderingOrder The order direction. +type BillingProfileCustomerOverrideOrderByOrderingOrder = SortOrder + +// BillingProfileCustomerOverrideOrderByOrderingOrderBy Order by options for customers. +type BillingProfileCustomerOverrideOrderByOrderingOrderBy = BillingProfileCustomerOverrideOrderBy + +// BillingProfileListCustomerOverridesParamsBillingProfile defines model for BillingProfileListCustomerOverridesParams.billingProfile. +type BillingProfileListCustomerOverridesParamsBillingProfile = []string + +// BillingProfileListCustomerOverridesParamsCustomerId defines model for BillingProfileListCustomerOverridesParams.customerId. +type BillingProfileListCustomerOverridesParamsCustomerId = []string + +// BillingProfileListCustomerOverridesParamsCustomerKey defines model for BillingProfileListCustomerOverridesParams.customerKey. +type BillingProfileListCustomerOverridesParamsCustomerKey = string + +// BillingProfileListCustomerOverridesParamsCustomerName defines model for BillingProfileListCustomerOverridesParams.customerName. +type BillingProfileListCustomerOverridesParamsCustomerName = string + +// BillingProfileListCustomerOverridesParamsCustomerPrimaryEmail defines model for BillingProfileListCustomerOverridesParams.customerPrimaryEmail. +type BillingProfileListCustomerOverridesParamsCustomerPrimaryEmail = string + +// BillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile defines model for BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile. +type BillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile = bool + +// BillingProfileListCustomerOverridesParamsExpand defines model for BillingProfileListCustomerOverridesParams.expand. +type BillingProfileListCustomerOverridesParamsExpand = []BillingProfileCustomerOverrideExpand + +// BillingProfileListCustomerOverridesParamsIncludeAllCustomers defines model for BillingProfileListCustomerOverridesParams.includeAllCustomers. +type BillingProfileListCustomerOverridesParamsIncludeAllCustomers = bool + +// BillingProfileOrderByOrderingOrder The order direction. +type BillingProfileOrderByOrderingOrder = SortOrder + +// BillingProfileOrderByOrderingOrderBy BillingProfileOrderBy specifies the ordering options for profiles +type BillingProfileOrderByOrderingOrderBy = BillingProfileOrderBy + +// CursorPaginationCursor defines model for CursorPagination.cursor. +type CursorPaginationCursor = string + +// CursorPaginationLimit defines model for CursorPagination.limit. +type CursorPaginationLimit = int + +// CustomerOrderByOrderingOrder The order direction. +type CustomerOrderByOrderingOrder = SortOrder + +// CustomerOrderByOrderingOrderBy Order by options for customers. +type CustomerOrderByOrderingOrderBy = CustomerOrderBy + +// CustomerSubscriptionOrderByOrderingOrder The order direction. +type CustomerSubscriptionOrderByOrderingOrder = SortOrder + +// CustomerSubscriptionOrderByOrderingOrderBy Order by options for customer subscriptions. +type CustomerSubscriptionOrderByOrderingOrderBy = CustomerSubscriptionOrderBy + +// EntitlementOrderByOrderingOrder The order direction. +type EntitlementOrderByOrderingOrder = SortOrder + +// EntitlementOrderByOrderingOrderBy Order by options for entitlements. +type EntitlementOrderByOrderingOrderBy = EntitlementOrderBy + +// FeatureOrderByOrderingOrder The order direction. +type FeatureOrderByOrderingOrder = SortOrder + +// FeatureOrderByOrderingOrderBy Order by options for features. +type FeatureOrderByOrderingOrderBy = FeatureOrderBy + +// GrantOrderByOrderingOrder The order direction. +type GrantOrderByOrderingOrder = SortOrder + +// GrantOrderByOrderingOrderBy Order by options for grants. +type GrantOrderByOrderingOrderBy = GrantOrderBy + +// InvoiceListParamsCreatedAfter defines model for InvoiceListParams.createdAfter. +type InvoiceListParamsCreatedAfter = time.Time + +// InvoiceListParamsCreatedBefore defines model for InvoiceListParams.createdBefore. +type InvoiceListParamsCreatedBefore = time.Time + +// InvoiceListParamsCustomers defines model for InvoiceListParams.customers. +type InvoiceListParamsCustomers = []string + +// InvoiceListParamsExpand defines model for InvoiceListParams.expand. +type InvoiceListParamsExpand = []InvoiceExpand + +// InvoiceListParamsExtendedStatuses defines model for InvoiceListParams.extendedStatuses. +type InvoiceListParamsExtendedStatuses = []string + +// InvoiceListParamsIncludeDeleted defines model for InvoiceListParams.includeDeleted. +type InvoiceListParamsIncludeDeleted = bool + +// InvoiceListParamsIssuedAfter defines model for InvoiceListParams.issuedAfter. +type InvoiceListParamsIssuedAfter = time.Time + +// InvoiceListParamsIssuedBefore defines model for InvoiceListParams.issuedBefore. +type InvoiceListParamsIssuedBefore = time.Time + +// InvoiceListParamsPeriodStartAfter defines model for InvoiceListParams.periodStartAfter. +type InvoiceListParamsPeriodStartAfter = time.Time + +// InvoiceListParamsPeriodStartBefore defines model for InvoiceListParams.periodStartBefore. +type InvoiceListParamsPeriodStartBefore = time.Time + +// InvoiceListParamsStatuses defines model for InvoiceListParams.statuses. +type InvoiceListParamsStatuses = []InvoiceStatus + +// InvoiceOrderByOrderingOrder The order direction. +type InvoiceOrderByOrderingOrder = SortOrder + +// InvoiceOrderByOrderingOrderBy InvoiceOrderBy specifies the ordering options for invoice listing. +type InvoiceOrderByOrderingOrderBy = InvoiceOrderBy + +// LimitOffsetLimit defines model for LimitOffset.limit. +type LimitOffsetLimit = int + +// LimitOffsetOffset defines model for LimitOffset.offset. +type LimitOffsetOffset = int + +// MarketplaceApiKeyInstallRequestType Type of the app. +type MarketplaceApiKeyInstallRequestType = AppType + +// MarketplaceInstallRequestType Type of the app. +type MarketplaceInstallRequestType = AppType + +// MarketplaceOAuth2InstallAuthorizeRequestType Type of the app. +type MarketplaceOAuth2InstallAuthorizeRequestType = AppType + +// MeterOrderByOrderingOrder The order direction. +type MeterOrderByOrderingOrder = SortOrder + +// MeterOrderByOrderingOrderBy Order by options for meters. +type MeterOrderByOrderingOrderBy = MeterOrderBy + +// MeterQueryAdvancedMeterGroupByFilters defines model for MeterQuery.advancedMeterGroupByFilters. +type MeterQueryAdvancedMeterGroupByFilters map[string]FilterString + +// MeterQueryClientId defines model for MeterQuery.clientId. +type MeterQueryClientId = string + +// MeterQueryFilterCustomerId defines model for MeterQuery.filterCustomerId. +type MeterQueryFilterCustomerId = []string + +// MeterQueryFilterGroupBy defines model for MeterQuery.filterGroupBy. +type MeterQueryFilterGroupBy map[string]string + +// MeterQueryFrom defines model for MeterQuery.from. +type MeterQueryFrom = time.Time + +// MeterQueryGroupBy defines model for MeterQuery.groupBy. +type MeterQueryGroupBy = []string + +// MeterQuerySubject defines model for MeterQuery.subject. +type MeterQuerySubject = []string + +// MeterQueryTo defines model for MeterQuery.to. +type MeterQueryTo = time.Time + +// MeterQueryWindowSize Aggregation window size. +type MeterQueryWindowSize = WindowSize + +// MeterQueryWindowTimeZone defines model for MeterQuery.windowTimeZone. +type MeterQueryWindowTimeZone = string + +// NotificationChannelOrderByOrderingOrder The order direction. +type NotificationChannelOrderByOrderingOrder = SortOrder + +// NotificationChannelOrderByOrderingOrderBy Order by options for notification channels. +type NotificationChannelOrderByOrderingOrderBy = NotificationChannelOrderBy + +// NotificationEventOrderByOrderingOrder The order direction. +type NotificationEventOrderByOrderingOrder = SortOrder + +// NotificationEventOrderByOrderingOrderBy Order by options for notification channels. +type NotificationEventOrderByOrderingOrderBy = NotificationEventOrderBy + +// NotificationRuleOrderByOrderingOrder The order direction. +type NotificationRuleOrderByOrderingOrder = SortOrder + +// NotificationRuleOrderByOrderingOrderBy Order by options for notification channels. +type NotificationRuleOrderByOrderingOrderBy = NotificationRuleOrderBy + +// OAuth2AuthorizationCodeGrantErrorParamsError OAuth2 authorization code grant error types. +type OAuth2AuthorizationCodeGrantErrorParamsError = OAuth2AuthorizationCodeGrantErrorType + +// OAuth2AuthorizationCodeGrantErrorParamsErrorDescription defines model for OAuth2AuthorizationCodeGrantErrorParams.error_description. +type OAuth2AuthorizationCodeGrantErrorParamsErrorDescription = string + +// OAuth2AuthorizationCodeGrantErrorParamsErrorUri defines model for OAuth2AuthorizationCodeGrantErrorParams.error_uri. +type OAuth2AuthorizationCodeGrantErrorParamsErrorUri = string + +// OAuth2AuthorizationCodeGrantSuccessParamsCode defines model for OAuth2AuthorizationCodeGrantSuccessParams.code. +type OAuth2AuthorizationCodeGrantSuccessParamsCode = string + +// OAuth2AuthorizationCodeGrantSuccessParamsState defines model for OAuth2AuthorizationCodeGrantSuccessParams.state. +type OAuth2AuthorizationCodeGrantSuccessParamsState = string + +// PaginationPage defines model for Pagination.page. +type PaginationPage = int + +// PaginationPageSize defines model for Pagination.pageSize. +type PaginationPageSize = int + +// PlanAddonOrderByOrderingOrder The order direction. +type PlanAddonOrderByOrderingOrder = SortOrder + +// PlanAddonOrderByOrderingOrderBy Order by options for plan add-on assignments. +type PlanAddonOrderByOrderingOrderBy = PlanAddonOrderBy + +// PlanOrderByOrderingOrder The order direction. +type PlanOrderByOrderingOrder = SortOrder + +// PlanOrderByOrderingOrderBy Order by options for plans. +type PlanOrderByOrderingOrderBy = PlanOrderBy + +// ListCustomerAppDataParamsType Type of the app. +type ListCustomerAppDataParamsType = AppType + +// QueryCustomerGet defines model for queryCustomerGet. +type QueryCustomerGet = []CustomerExpand + +// QueryCustomerListExpand defines model for queryCustomerList.expand. +type QueryCustomerListExpand = []CustomerExpand + +// QueryCustomerListIncludeDeleted defines model for queryCustomerList.includeDeleted. +type QueryCustomerListIncludeDeleted = bool + +// QueryCustomerListKey defines model for queryCustomerList.key. +type QueryCustomerListKey = string + +// QueryCustomerListName defines model for queryCustomerList.name. +type QueryCustomerListName = string + +// QueryCustomerListPlanKey defines model for queryCustomerList.planKey. +type QueryCustomerListPlanKey = string + +// QueryCustomerListPrimaryEmail defines model for queryCustomerList.primaryEmail. +type QueryCustomerListPrimaryEmail = string + +// QueryCustomerListSubject defines model for queryCustomerList.subject. +type QueryCustomerListSubject = string + +// QueryMeterListIncludeDeleted defines model for queryMeterList.includeDeleted. +type QueryMeterListIncludeDeleted = bool + +// cloudCookieAuthContextKey is the context key for CloudCookieAuth security scheme +type cloudCookieAuthContextKey string + +// cloudPortalTokenAuthContextKey is the context key for CloudPortalTokenAuth security scheme +type cloudPortalTokenAuthContextKey string + +// cloudTokenAuthContextKey is the context key for CloudTokenAuth security scheme +type cloudTokenAuthContextKey string + +// ListAddonsParams defines parameters for ListAddons. +type ListAddonsParams struct { + // IncludeDeleted Include deleted add-ons in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Id Filter by addon.id attribute + Id *[]string `form:"id,omitempty" json:"id,omitempty"` + + // Key Filter by addon.key attribute + Key *[]string `form:"key,omitempty" json:"key,omitempty"` + + // KeyVersion Filter by addon.key and addon.version attributes + KeyVersion *map[string][]int `json:"keyVersion,omitempty"` + + // Status Only return add-ons with the given status. + // + // Usage: + // - `?status=active`: return only the currently active add-ons + // - `?status=draft`: return only the draft add-ons + // - `?status=archived`: return only the archived add-ons + Status *[]AddonStatus `form:"status,omitempty" json:"status,omitempty"` + + // Currency Filter by addon.currency attribute + Currency *[]CurrencyCode `form:"currency,omitempty" json:"currency,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *AddonOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *AddonOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetAddonParams defines parameters for GetAddon. +type GetAddonParams struct { + // IncludeLatest Include latest version of the add-on instead of the version in active state. + // + // Usage: `?includeLatest=true` + IncludeLatest *bool `form:"includeLatest,omitempty" json:"includeLatest,omitempty"` +} + +// ListAppsParams defines parameters for ListApps. +type ListAppsParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// ListBillingProfileCustomerOverridesParams defines parameters for ListBillingProfileCustomerOverrides. +type ListBillingProfileCustomerOverridesParams struct { + // BillingProfile Filter by billing profile. + BillingProfile *BillingProfileListCustomerOverridesParamsBillingProfile `form:"billingProfile,omitempty" json:"billingProfile,omitempty"` + + // CustomersWithoutPinnedProfile Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. + CustomersWithoutPinnedProfile *BillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile `form:"customersWithoutPinnedProfile,omitempty" json:"customersWithoutPinnedProfile,omitempty"` + + // IncludeAllCustomers Include customers without customer overrides. + // + // If set to false only the customers specifically associated with a billing profile will be returned. + // + // If set to true, in case of the default billing profile, all customers will be returned. + IncludeAllCustomers *BillingProfileListCustomerOverridesParamsIncludeAllCustomers `form:"includeAllCustomers,omitempty" json:"includeAllCustomers,omitempty"` + + // CustomerId Filter by customer id. + CustomerId *BillingProfileListCustomerOverridesParamsCustomerId `form:"customerId,omitempty" json:"customerId,omitempty"` + + // CustomerName Filter by customer name. + CustomerName *BillingProfileListCustomerOverridesParamsCustomerName `form:"customerName,omitempty" json:"customerName,omitempty"` + + // CustomerKey Filter by customer key + CustomerKey *BillingProfileListCustomerOverridesParamsCustomerKey `form:"customerKey,omitempty" json:"customerKey,omitempty"` + + // CustomerPrimaryEmail Filter by customer primary email + CustomerPrimaryEmail *BillingProfileListCustomerOverridesParamsCustomerPrimaryEmail `form:"customerPrimaryEmail,omitempty" json:"customerPrimaryEmail,omitempty"` + + // Expand Expand the response with additional details. + Expand *BillingProfileListCustomerOverridesParamsExpand `form:"expand,omitempty" json:"expand,omitempty"` + + // Order The order direction. + Order *BillingProfileCustomerOverrideOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *BillingProfileCustomerOverrideOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// GetBillingProfileCustomerOverrideParams defines parameters for GetBillingProfileCustomerOverride. +type GetBillingProfileCustomerOverrideParams struct { + Expand *[]BillingProfileCustomerOverrideExpand `form:"expand,omitempty" json:"expand,omitempty"` +} + +// ListInvoicesParams defines parameters for ListInvoices. +type ListInvoicesParams struct { + // Statuses Filter by the invoice status. + Statuses *InvoiceListParamsStatuses `form:"statuses,omitempty" json:"statuses,omitempty"` + + // ExtendedStatuses Filter by invoice extended statuses + ExtendedStatuses *InvoiceListParamsExtendedStatuses `form:"extendedStatuses,omitempty" json:"extendedStatuses,omitempty"` + + // IssuedAfter Filter by invoice issued time. + // Inclusive. + IssuedAfter *InvoiceListParamsIssuedAfter `form:"issuedAfter,omitempty" json:"issuedAfter,omitempty"` + + // IssuedBefore Filter by invoice issued time. + // Inclusive. + IssuedBefore *InvoiceListParamsIssuedBefore `form:"issuedBefore,omitempty" json:"issuedBefore,omitempty"` + + // PeriodStartAfter Filter by period start time. + // Inclusive. + PeriodStartAfter *InvoiceListParamsPeriodStartAfter `form:"periodStartAfter,omitempty" json:"periodStartAfter,omitempty"` + + // PeriodStartBefore Filter by period start time. + // Inclusive. + PeriodStartBefore *InvoiceListParamsPeriodStartBefore `form:"periodStartBefore,omitempty" json:"periodStartBefore,omitempty"` + + // CreatedAfter Filter by invoice created time. + // Inclusive. + CreatedAfter *InvoiceListParamsCreatedAfter `form:"createdAfter,omitempty" json:"createdAfter,omitempty"` + + // CreatedBefore Filter by invoice created time. + // Inclusive. + CreatedBefore *InvoiceListParamsCreatedBefore `form:"createdBefore,omitempty" json:"createdBefore,omitempty"` + + // Expand What parts of the list output to expand in listings + Expand *InvoiceListParamsExpand `form:"expand,omitempty" json:"expand,omitempty"` + + // Customers Filter by customer ID + Customers *InvoiceListParamsCustomers `form:"customers,omitempty" json:"customers,omitempty"` + + // IncludeDeleted Include deleted invoices + IncludeDeleted *InvoiceListParamsIncludeDeleted `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *InvoiceOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *InvoiceOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetInvoiceParams defines parameters for GetInvoice. +type GetInvoiceParams struct { + Expand *[]InvoiceExpand `form:"expand,omitempty" json:"expand,omitempty"` + IncludeDeletedLines *bool `form:"includeDeletedLines,omitempty" json:"includeDeletedLines,omitempty"` +} + +// ListBillingProfilesParams defines parameters for ListBillingProfiles. +type ListBillingProfilesParams struct { + IncludeArchived *bool `form:"includeArchived,omitempty" json:"includeArchived,omitempty"` + Expand *[]BillingProfileExpand `form:"expand,omitempty" json:"expand,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *BillingProfileOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *BillingProfileOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetBillingProfileParams defines parameters for GetBillingProfile. +type GetBillingProfileParams struct { + Expand *[]BillingProfileExpand `form:"expand,omitempty" json:"expand,omitempty"` +} + +// ListCustomersParams defines parameters for ListCustomers. +type ListCustomersParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *CustomerOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *CustomerOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // IncludeDeleted Include deleted customers. + IncludeDeleted *QueryCustomerListIncludeDeleted `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Key Filter customers by key. + // Case-insensitive partial match. + Key *QueryCustomerListKey `form:"key,omitempty" json:"key,omitempty"` + + // Name Filter customers by name. + // Case-insensitive partial match. + Name *QueryCustomerListName `form:"name,omitempty" json:"name,omitempty"` + + // PrimaryEmail Filter customers by primary email. + // Case-insensitive partial match. + PrimaryEmail *QueryCustomerListPrimaryEmail `form:"primaryEmail,omitempty" json:"primaryEmail,omitempty"` + + // Subject Filter customers by usage attribution subject. + // Case-insensitive partial match. + Subject *QueryCustomerListSubject `form:"subject,omitempty" json:"subject,omitempty"` + + // PlanKey Filter customers by the plan key of their susbcription. + PlanKey *QueryCustomerListPlanKey `form:"planKey,omitempty" json:"planKey,omitempty"` + + // Expand What parts of the list output to expand in listings + Expand *QueryCustomerListExpand `form:"expand,omitempty" json:"expand,omitempty"` +} + +// GetCustomerParams defines parameters for GetCustomer. +type GetCustomerParams struct { + // Expand What parts of the customer output to expand + Expand *QueryCustomerGet `form:"expand,omitempty" json:"expand,omitempty"` +} + +// ListCustomerAppDataParams defines parameters for ListCustomerAppData. +type ListCustomerAppDataParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Type Filter customer data by app type. + Type *ListCustomerAppDataParamsType `form:"type,omitempty" json:"type,omitempty"` +} + +// UpsertCustomerAppDataJSONBody defines parameters for UpsertCustomerAppData. +type UpsertCustomerAppDataJSONBody = []CustomerAppDataCreateOrUpdateItem + +// GetCustomerEntitlementValueParams defines parameters for GetCustomerEntitlementValue. +type GetCustomerEntitlementValueParams struct { + Time *time.Time `form:"time,omitempty" json:"time,omitempty"` +} + +// ListCustomerSubscriptionsParams defines parameters for ListCustomerSubscriptions. +type ListCustomerSubscriptionsParams struct { + Status *[]SubscriptionStatus `form:"status,omitempty" json:"status,omitempty"` + + // Order The order direction. + Order *CustomerSubscriptionOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *CustomerSubscriptionOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// ListEntitlementsParams defines parameters for ListEntitlements. +type ListEntitlementsParams struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Subject Filtering by multiple subjects. + // + // Usage: `?subject=customer-1&subject=customer-2` + Subject *[]string `form:"subject,omitempty" json:"subject,omitempty"` + + // EntitlementType Filtering by multiple entitlement types. + // + // Usage: `?entitlementType=metered&entitlementType=boolean` + EntitlementType *[]EntitlementType `form:"entitlementType,omitempty" json:"entitlementType,omitempty"` + + // ExcludeInactive Exclude inactive entitlements in the response (those scheduled for later or earlier) + ExcludeInactive *bool `form:"excludeInactive,omitempty" json:"excludeInactive,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *EntitlementOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *EntitlementOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListEventsParams defines parameters for ListEvents. +type ListEventsParams struct { + // ClientId Client ID + // Useful to track progress of a query. + ClientId *string `form:"clientId,omitempty" json:"clientId,omitempty"` + + // IngestedAtFrom Start date-time in RFC 3339 format. + // + // Inclusive. + IngestedAtFrom *time.Time `form:"ingestedAtFrom,omitempty" json:"ingestedAtFrom,omitempty"` + + // IngestedAtTo End date-time in RFC 3339 format. + // + // Inclusive. + IngestedAtTo *time.Time `form:"ingestedAtTo,omitempty" json:"ingestedAtTo,omitempty"` + + // Id The event ID. + // + // Accepts partial ID. + Id *string `form:"id,omitempty" json:"id,omitempty"` + + // Subject The event subject. + // + // Accepts partial subject. + Subject *string `form:"subject,omitempty" json:"subject,omitempty"` + + // CustomerId The event customer ID. + CustomerId *[]string `form:"customerId,omitempty" json:"customerId,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // Limit Number of events to return. + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// IngestEventsApplicationCloudeventsBatchPlusJSONBody defines parameters for IngestEvents. +type IngestEventsApplicationCloudeventsBatchPlusJSONBody = []Event + +// ListFeaturesParams defines parameters for ListFeatures. +type ListFeaturesParams struct { + // MeterSlug Filter by meterSlug + MeterSlug *[]string `form:"meterSlug,omitempty" json:"meterSlug,omitempty"` + + // IncludeArchived Include archived features in response. + IncludeArchived *bool `form:"includeArchived,omitempty" json:"includeArchived,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *FeatureOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *FeatureOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListGrantsParams defines parameters for ListGrants. +type ListGrantsParams struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Subject Filtering by multiple subjects. + // + // Usage: `?subject=customer-1&subject=customer-2` + Subject *[]string `form:"subject,omitempty" json:"subject,omitempty"` + + // IncludeDeleted Include deleted + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *GrantOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *GrantOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// VoidGrantParams defines parameters for VoidGrant. +type VoidGrantParams struct { + // At The time at which the grant should be voided. + // Must not be in the future and must be within the current usage period of the entitlement. + // Defaults to the current time if not specified. + At *time.Time `form:"at,omitempty" json:"at,omitempty"` +} + +// ListMarketplaceListingsParams defines parameters for ListMarketplaceListings. +type ListMarketplaceListingsParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` +} + +// MarketplaceAppAPIKeyInstallJSONBody defines parameters for MarketplaceAppAPIKeyInstall. +type MarketplaceAppAPIKeyInstallJSONBody struct { + // ApiKey The API key for the provider. + // For example, the Stripe API key. + ApiKey string `json:"apiKey"` + + // CreateBillingProfile If true, a billing profile will be created for the app. + // The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + CreateBillingProfile *bool `json:"createBillingProfile,omitempty"` + + // Name Name of the application to install. + // + // If name is not provided defaults to the marketplace listing's name. + Name *string `json:"name,omitempty"` +} + +// MarketplaceOAuth2InstallAuthorizeParams defines parameters for MarketplaceOAuth2InstallAuthorize. +type MarketplaceOAuth2InstallAuthorizeParams struct { + // State Required if the "state" parameter was present in the client authorization request. + // The exact value received from the client: + // + // Unique, randomly generated, opaque, and non-guessable string that is sent + // when starting an authentication request and validated when processing the response. + State *OAuth2AuthorizationCodeGrantSuccessParamsState `form:"state,omitempty" json:"state,omitempty"` + + // Code Authorization code which the client will later exchange for an access token. + // Required with the success response. + Code *OAuth2AuthorizationCodeGrantSuccessParamsCode `form:"code,omitempty" json:"code,omitempty"` + + // Error Error code. + // Required with the error response. + Error *OAuth2AuthorizationCodeGrantErrorParamsError `form:"error,omitempty" json:"error,omitempty"` + + // ErrorDescription Optional human-readable text providing additional information, + // used to assist the client developer in understanding the error that occurred. + ErrorDescription *OAuth2AuthorizationCodeGrantErrorParamsErrorDescription `form:"error_description,omitempty" json:"error_description,omitempty"` + + // ErrorUri Optional uri identifying a human-readable web page with + // information about the error, used to provide the client + // developer with additional information about the error + ErrorUri *OAuth2AuthorizationCodeGrantErrorParamsErrorUri `form:"error_uri,omitempty" json:"error_uri,omitempty"` +} + +// ListMetersParams defines parameters for ListMeters. +type ListMetersParams struct { + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *MeterOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *MeterOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` + + // IncludeDeleted Include deleted meters. + IncludeDeleted *QueryMeterListIncludeDeleted `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` +} + +// ListMeterGroupByValuesParams defines parameters for ListMeterGroupByValues. +type ListMeterGroupByValuesParams struct { + // From Start date-time in RFC 3339 format. + // + // Inclusive. Defaults to 24 hours ago. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *time.Time `form:"to,omitempty" json:"to,omitempty"` +} + +// QueryMeterParams defines parameters for QueryMeter. +type QueryMeterParams struct { + // ClientId Client ID + // Useful to track progress of a query. + ClientId *MeterQueryClientId `form:"clientId,omitempty" json:"clientId,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *MeterQueryFrom `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *MeterQueryTo `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + // + // For example: ?windowSize=DAY + WindowSize *MeterQueryWindowSize `form:"windowSize,omitempty" json:"windowSize,omitempty"` + + // WindowTimeZone The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + // If not specified, the UTC timezone will be used. + // + // For example: ?windowTimeZone=UTC + WindowTimeZone *MeterQueryWindowTimeZone `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` + + // Subject Filtering by multiple subjects. + // + // For example: ?subject=subject-1&subject=subject-2 + Subject *MeterQuerySubject `form:"subject,omitempty" json:"subject,omitempty"` + + // FilterCustomerId Filtering by multiple customers. + // + // For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + FilterCustomerId *MeterQueryFilterCustomerId `form:"filterCustomerId,omitempty" json:"filterCustomerId,omitempty"` + + // FilterGroupBy Simple filter for group bys with exact match. + // + // For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + // + // ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + FilterGroupBy *MeterQueryFilterGroupBy `json:"filterGroupBy,omitempty"` + + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *MeterQueryAdvancedMeterGroupByFilters `form:"advancedMeterGroupByFilters,omitempty" json:"advancedMeterGroupByFilters,omitempty"` + + // GroupBy If not specified a single aggregate will be returned for each subject and time window. + // `subject` is a reserved group by value. + // + // For example: ?groupBy=subject&groupBy=model + GroupBy *MeterQueryGroupBy `form:"groupBy,omitempty" json:"groupBy,omitempty"` +} + +// ListMeterSubjectsParams defines parameters for ListMeterSubjects. +type ListMeterSubjectsParams struct { + // From Start date-time in RFC 3339 format. + // + // Inclusive. Defaults to the beginning of time. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *time.Time `form:"to,omitempty" json:"to,omitempty"` +} + +// ListNotificationChannelsParams defines parameters for ListNotificationChannels. +type ListNotificationChannelsParams struct { + // IncludeDeleted Include deleted notification channels in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // IncludeDisabled Include disabled notification channels in response. + // + // Usage: `?includeDisabled=false` + IncludeDisabled *bool `form:"includeDisabled,omitempty" json:"includeDisabled,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *NotificationChannelOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *NotificationChannelOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListNotificationEventsParams defines parameters for ListNotificationEvents. +type ListNotificationEventsParams struct { + // From Start date-time in RFC 3339 format. + // Inclusive. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // Inclusive. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // Feature Filtering by multiple feature ids or keys. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Subject Filtering by multiple subject ids or keys. + // + // Usage: `?subject=subject-1&subject=subject-2` + Subject *[]string `form:"subject,omitempty" json:"subject,omitempty"` + + // Rule Filtering by multiple rule ids. + // + // Usage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5` + Rule *[]string `form:"rule,omitempty" json:"rule,omitempty"` + + // Channel Filtering by multiple channel ids. + // + // Usage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J` + Channel *[]string `form:"channel,omitempty" json:"channel,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *NotificationEventOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *NotificationEventOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListNotificationRulesParams defines parameters for ListNotificationRules. +type ListNotificationRulesParams struct { + // IncludeDeleted Include deleted notification rules in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // IncludeDisabled Include disabled notification rules in response. + // + // Usage: `?includeDisabled=false` + IncludeDisabled *bool `form:"includeDisabled,omitempty" json:"includeDisabled,omitempty"` + + // Feature Filtering by multiple feature ids/keys. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Channel Filtering by multiple notifiaction channel ids. + // + // Usage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3` + Channel *[]string `form:"channel,omitempty" json:"channel,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *NotificationRuleOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *NotificationRuleOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListPlansParams defines parameters for ListPlans. +type ListPlansParams struct { + // IncludeDeleted Include deleted plans in response. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Id Filter by plan.id attribute + Id *[]string `form:"id,omitempty" json:"id,omitempty"` + + // Key Filter by plan.key attribute + Key *[]string `form:"key,omitempty" json:"key,omitempty"` + + // KeyVersion Filter by plan.key and plan.version attributes + KeyVersion *map[string][]int `json:"keyVersion,omitempty"` + + // Status Only return plans with the given status. + // + // Usage: + // - `?status=active`: return only the currently active plan + // - `?status=draft`: return only the draft plan + // - `?status=archived`: return only the archived plans + Status *[]PlanStatus `form:"status,omitempty" json:"status,omitempty"` + + // Currency Filter by plan.currency attribute + Currency *[]CurrencyCode `form:"currency,omitempty" json:"currency,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *PlanOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *PlanOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetPlanParams defines parameters for GetPlan. +type GetPlanParams struct { + // IncludeLatest Include latest version of the Plan instead of the version in active state. + // + // Usage: `?includeLatest=true` + IncludeLatest *bool `form:"includeLatest,omitempty" json:"includeLatest,omitempty"` +} + +// ListPlanAddonsParams defines parameters for ListPlanAddons. +type ListPlanAddonsParams struct { + // IncludeDeleted Include deleted plan add-on assignments. + // + // Usage: `?includeDeleted=true` + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Id Filter by addon.id attribute. + Id *[]string `form:"id,omitempty" json:"id,omitempty"` + + // Key Filter by addon.key attribute. + Key *[]string `form:"key,omitempty" json:"key,omitempty"` + + // KeyVersion Filter by addon.key and addon.version attributes. + KeyVersion *map[string][]int `json:"keyVersion,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *PlanAddonOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *PlanAddonOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// QueryPortalMeterParams defines parameters for QueryPortalMeter. +type QueryPortalMeterParams struct { + // ClientId Client ID + // Useful to track progress of a query. + ClientId *MeterQueryClientId `form:"clientId,omitempty" json:"clientId,omitempty"` + + // From Start date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?from=2025-01-01T00%3A00%3A00.000Z + From *MeterQueryFrom `form:"from,omitempty" json:"from,omitempty"` + + // To End date-time in RFC 3339 format. + // + // Inclusive. + // + // For example: ?to=2025-02-01T00%3A00%3A00.000Z + To *MeterQueryTo `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + // + // For example: ?windowSize=DAY + WindowSize *MeterQueryWindowSize `form:"windowSize,omitempty" json:"windowSize,omitempty"` + + // WindowTimeZone The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + // If not specified, the UTC timezone will be used. + // + // For example: ?windowTimeZone=UTC + WindowTimeZone *MeterQueryWindowTimeZone `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` + + // FilterCustomerId Filtering by multiple customers. + // + // For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + FilterCustomerId *MeterQueryFilterCustomerId `form:"filterCustomerId,omitempty" json:"filterCustomerId,omitempty"` + + // FilterGroupBy Simple filter for group bys with exact match. + // + // For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + // + // ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + FilterGroupBy *MeterQueryFilterGroupBy `json:"filterGroupBy,omitempty"` + + // AdvancedMeterGroupByFilters Optional advanced meter group by filters. + // You can use this to filter for values of the meter groupBy fields. + AdvancedMeterGroupByFilters *MeterQueryAdvancedMeterGroupByFilters `form:"advancedMeterGroupByFilters,omitempty" json:"advancedMeterGroupByFilters,omitempty"` + + // GroupBy If not specified a single aggregate will be returned for each subject and time window. + // `subject` is a reserved group by value. + // + // For example: ?groupBy=subject&groupBy=model + GroupBy *MeterQueryGroupBy `form:"groupBy,omitempty" json:"groupBy,omitempty"` +} + +// ListPortalTokensParams defines parameters for ListPortalTokens. +type ListPortalTokensParams struct { + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// InvalidatePortalTokensJSONBody defines parameters for InvalidatePortalTokens. +type InvalidatePortalTokensJSONBody struct { + // Id Invalidate a portal token by ID. + Id *string `json:"id,omitempty"` + + // Subject Invalidate all portal tokens for a subject. + Subject *string `json:"subject,omitempty"` +} + +// UpsertSubjectJSONBody defines parameters for UpsertSubject. +type UpsertSubjectJSONBody = []SubjectUpsert + +// ListSubjectEntitlementsParams defines parameters for ListSubjectEntitlements. +type ListSubjectEntitlementsParams struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` +} + +// ListEntitlementGrantsParams defines parameters for ListEntitlementGrants. +type ListEntitlementGrantsParams struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + OrderBy *GrantOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetEntitlementValueParams defines parameters for GetEntitlementValue. +type GetEntitlementValueParams struct { + Time *time.Time `form:"time,omitempty" json:"time,omitempty"` +} + +// GetEntitlementHistoryParams defines parameters for GetEntitlementHistory. +type GetEntitlementHistoryParams struct { + // From Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + // If not now then gets truncated to the granularity of the underlying meter. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize Windowsize + WindowSize WindowSize `form:"windowSize" json:"windowSize"` + + // WindowTimeZone The timezone used when calculating the windows. + WindowTimeZone *string `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` +} + +// GetSubscriptionParams defines parameters for GetSubscription. +type GetSubscriptionParams struct { + // At The time at which the subscription should be queried. If not provided the current time is used. + At *time.Time `form:"at,omitempty" json:"at,omitempty"` +} + +// CancelSubscriptionJSONBody defines parameters for CancelSubscription. +type CancelSubscriptionJSONBody struct { + // Timing If not provided the subscription is canceled immediately. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// MigrateSubscriptionJSONBody defines parameters for MigrateSubscription. +type MigrateSubscriptionJSONBody struct { + // BillingAnchor The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + BillingAnchor *time.Time `json:"billingAnchor,omitempty"` + + // StartingPhase The key of the phase to start the subscription in. + // If not provided, the subscription will start in the first phase of the plan. + StartingPhase *string `json:"startingPhase,omitempty"` + + // TargetVersion The version of the plan to migrate to. + // If not provided, the subscription will migrate to the latest version of the current plan. + TargetVersion *int `json:"targetVersion,omitempty"` + + // Timing Timing configuration for the migration, when the migration should take effect. + // If not supported by the subscription, 400 will be returned. + Timing *SubscriptionTiming `json:"timing,omitempty"` +} + +// ListCustomerEntitlementsV2Params defines parameters for ListCustomerEntitlementsV2. +type ListCustomerEntitlementsV2Params struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Order The order direction. + Order *EntitlementOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *EntitlementOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListCustomerEntitlementGrantsV2Params defines parameters for ListCustomerEntitlementGrantsV2. +type ListCustomerEntitlementGrantsV2Params struct { + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *GrantOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *GrantOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// GetCustomerEntitlementHistoryV2Params defines parameters for GetCustomerEntitlementHistoryV2. +type GetCustomerEntitlementHistoryV2Params struct { + // From Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + From *time.Time `form:"from,omitempty" json:"from,omitempty"` + + // To End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + // If not now then gets truncated to the granularity of the underlying meter. + To *time.Time `form:"to,omitempty" json:"to,omitempty"` + + // WindowSize Windowsize + WindowSize WindowSize `form:"windowSize" json:"windowSize"` + + // WindowTimeZone The timezone used when calculating the windows. + WindowTimeZone *string `form:"windowTimeZone,omitempty" json:"windowTimeZone,omitempty"` +} + +// GetCustomerEntitlementValueV2Params defines parameters for GetCustomerEntitlementValueV2. +type GetCustomerEntitlementValueV2Params struct { + Time *time.Time `form:"time,omitempty" json:"time,omitempty"` +} + +// ListEntitlementsV2Params defines parameters for ListEntitlementsV2. +type ListEntitlementsV2Params struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // CustomerKeys Filtering by multiple customers. + // + // Usage: `?customerKeys=customer-1&customerKeys=customer-3` + CustomerKeys *[]string `form:"customerKeys,omitempty" json:"customerKeys,omitempty"` + + // CustomerIds Filtering by multiple customers. + // + // Usage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9` + CustomerIds *[]string `form:"customerIds,omitempty" json:"customerIds,omitempty"` + + // EntitlementType Filtering by multiple entitlement types. + // + // Usage: `?entitlementType=metered&entitlementType=boolean` + EntitlementType *[]EntitlementType `form:"entitlementType,omitempty" json:"entitlementType,omitempty"` + + // ExcludeInactive Exclude inactive entitlements in the response (those scheduled for later or earlier) + ExcludeInactive *bool `form:"excludeInactive,omitempty" json:"excludeInactive,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *EntitlementOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *EntitlementOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// ListEventsV2Params defines parameters for ListEventsV2. +type ListEventsV2Params struct { + // Cursor The cursor after which to start the pagination. + Cursor *CursorPaginationCursor `form:"cursor,omitempty" json:"cursor,omitempty"` + + // Limit The limit of the pagination. + Limit *CursorPaginationLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // ClientId Client ID + // Useful to track progress of a query. + ClientId *string `form:"clientId,omitempty" json:"clientId,omitempty"` + + // Filter The filter for the events encoded as JSON string. + Filter *struct { + // CustomerId A filter for a ID (ULID) field allowing only equality or inclusion. + CustomerId *FilterIDExact `json:"customerId,omitempty"` + + // Id A filter for a string field. + Id *FilterString `json:"id,omitempty"` + + // IngestedAt A filter for a time field. + IngestedAt *FilterTime `json:"ingestedAt,omitempty"` + + // Source A filter for a string field. + Source *FilterString `json:"source,omitempty"` + + // Subject A filter for a string field. + Subject *FilterString `json:"subject,omitempty"` + + // Time A filter for a time field. + Time *FilterTime `json:"time,omitempty"` + + // Type A filter for a string field. + Type *FilterString `json:"type,omitempty"` + } `form:"filter,omitempty" json:"filter,omitempty"` +} + +// ListGrantsV2Params defines parameters for ListGrantsV2. +type ListGrantsV2Params struct { + // Feature Filtering by multiple features. + // + // Usage: `?feature=feature-1&feature=feature-2` + Feature *[]string `form:"feature,omitempty" json:"feature,omitempty"` + + // Customer Filtering by multiple customers (either by ID or key). + // + // Usage: `?customer=customer-1&customer=customer-2` + Customer *[]ULIDOrExternalKey `form:"customer,omitempty" json:"customer,omitempty"` + + // IncludeDeleted Include deleted + IncludeDeleted *bool `form:"includeDeleted,omitempty" json:"includeDeleted,omitempty"` + + // Page Page index. + // + // Default is 1. + Page *PaginationPage `form:"page,omitempty" json:"page,omitempty"` + + // PageSize The maximum number of items per page. + // + // Default is 100. + PageSize *PaginationPageSize `form:"pageSize,omitempty" json:"pageSize,omitempty"` + + // Offset Number of items to skip. + // + // Default is 0. + Offset *LimitOffsetOffset `form:"offset,omitempty" json:"offset,omitempty"` + + // Limit Number of items to return. + // + // Default is 100. + Limit *LimitOffsetLimit `form:"limit,omitempty" json:"limit,omitempty"` + + // Order The order direction. + Order *GrantOrderByOrderingOrder `form:"order,omitempty" json:"order,omitempty"` + + // OrderBy The order by field. + OrderBy *GrantOrderByOrderingOrderBy `form:"orderBy,omitempty" json:"orderBy,omitempty"` +} + +// CreateAddonJSONRequestBody defines body for CreateAddon for application/json ContentType. +type CreateAddonJSONRequestBody = AddonCreate + +// UpdateAddonJSONRequestBody defines body for UpdateAddon for application/json ContentType. +type UpdateAddonJSONRequestBody = AddonReplaceUpdate + +// AppCustomInvoicingDraftSynchronizedJSONRequestBody defines body for AppCustomInvoicingDraftSynchronized for application/json ContentType. +type AppCustomInvoicingDraftSynchronizedJSONRequestBody = CustomInvoicingDraftSynchronizedRequest + +// AppCustomInvoicingIssuingSynchronizedJSONRequestBody defines body for AppCustomInvoicingIssuingSynchronized for application/json ContentType. +type AppCustomInvoicingIssuingSynchronizedJSONRequestBody = CustomInvoicingFinalizedRequest + +// AppCustomInvoicingUpdatePaymentStatusJSONRequestBody defines body for AppCustomInvoicingUpdatePaymentStatus for application/json ContentType. +type AppCustomInvoicingUpdatePaymentStatusJSONRequestBody = CustomInvoicingUpdatePaymentStatusRequest + +// UpdateAppJSONRequestBody defines body for UpdateApp for application/json ContentType. +type UpdateAppJSONRequestBody = AppReplaceUpdate + +// UpdateStripeAPIKeyJSONRequestBody defines body for UpdateStripeAPIKey for application/json ContentType. +type UpdateStripeAPIKeyJSONRequestBody = StripeAPIKeyInput + +// AppStripeWebhookJSONRequestBody defines body for AppStripeWebhook for application/json ContentType. +type AppStripeWebhookJSONRequestBody = StripeWebhookEvent + +// UpsertBillingProfileCustomerOverrideJSONRequestBody defines body for UpsertBillingProfileCustomerOverride for application/json ContentType. +type UpsertBillingProfileCustomerOverrideJSONRequestBody = BillingProfileCustomerOverrideCreate + +// CreatePendingInvoiceLineJSONRequestBody defines body for CreatePendingInvoiceLine for application/json ContentType. +type CreatePendingInvoiceLineJSONRequestBody = InvoicePendingLineCreateInput + +// SimulateInvoiceJSONRequestBody defines body for SimulateInvoice for application/json ContentType. +type SimulateInvoiceJSONRequestBody = InvoiceSimulationInput + +// InvoicePendingLinesActionJSONRequestBody defines body for InvoicePendingLinesAction for application/json ContentType. +type InvoicePendingLinesActionJSONRequestBody = InvoicePendingLinesActionInput + +// UpdateInvoiceJSONRequestBody defines body for UpdateInvoice for application/json ContentType. +type UpdateInvoiceJSONRequestBody = InvoiceReplaceUpdate + +// VoidInvoiceActionJSONRequestBody defines body for VoidInvoiceAction for application/json ContentType. +type VoidInvoiceActionJSONRequestBody = VoidInvoiceActionInput + +// CreateBillingProfileJSONRequestBody defines body for CreateBillingProfile for application/json ContentType. +type CreateBillingProfileJSONRequestBody = BillingProfileCreate + +// UpdateBillingProfileJSONRequestBody defines body for UpdateBillingProfile for application/json ContentType. +type UpdateBillingProfileJSONRequestBody = BillingProfileReplaceUpdateWithWorkflow + +// CreateCustomerJSONRequestBody defines body for CreateCustomer for application/json ContentType. +type CreateCustomerJSONRequestBody = CustomerCreate + +// UpdateCustomerJSONRequestBody defines body for UpdateCustomer for application/json ContentType. +type UpdateCustomerJSONRequestBody = CustomerReplaceUpdate + +// UpsertCustomerAppDataJSONRequestBody defines body for UpsertCustomerAppData for application/json ContentType. +type UpsertCustomerAppDataJSONRequestBody = UpsertCustomerAppDataJSONBody + +// UpsertCustomerStripeAppDataJSONRequestBody defines body for UpsertCustomerStripeAppData for application/json ContentType. +type UpsertCustomerStripeAppDataJSONRequestBody = StripeCustomerAppDataBase + +// CreateCustomerStripePortalSessionJSONRequestBody defines body for CreateCustomerStripePortalSession for application/json ContentType. +type CreateCustomerStripePortalSessionJSONRequestBody = CreateStripeCustomerPortalSessionParams + +// IngestEventsApplicationCloudeventsPlusJSONRequestBody defines body for IngestEvents for application/cloudevents+json ContentType. +type IngestEventsApplicationCloudeventsPlusJSONRequestBody = Event + +// IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody defines body for IngestEvents for application/cloudevents-batch+json ContentType. +type IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody = IngestEventsApplicationCloudeventsBatchPlusJSONBody + +// IngestEventsJSONRequestBody defines body for IngestEvents for application/json ContentType. +type IngestEventsJSONRequestBody = IngestEventsBody + +// CreateFeatureJSONRequestBody defines body for CreateFeature for application/json ContentType. +type CreateFeatureJSONRequestBody = FeatureCreateInputs + +// MarketplaceAppInstallJSONRequestBody defines body for MarketplaceAppInstall for application/json ContentType. +type MarketplaceAppInstallJSONRequestBody = MarketplaceInstallRequestPayload + +// MarketplaceAppAPIKeyInstallJSONRequestBody defines body for MarketplaceAppAPIKeyInstall for application/json ContentType. +type MarketplaceAppAPIKeyInstallJSONRequestBody MarketplaceAppAPIKeyInstallJSONBody + +// CreateMeterJSONRequestBody defines body for CreateMeter for application/json ContentType. +type CreateMeterJSONRequestBody = MeterCreate + +// UpdateMeterJSONRequestBody defines body for UpdateMeter for application/json ContentType. +type UpdateMeterJSONRequestBody = MeterUpdate + +// QueryMeterPostJSONRequestBody defines body for QueryMeterPost for application/json ContentType. +type QueryMeterPostJSONRequestBody = MeterQueryRequest + +// CreateNotificationChannelJSONRequestBody defines body for CreateNotificationChannel for application/json ContentType. +type CreateNotificationChannelJSONRequestBody = NotificationChannelCreateRequest + +// UpdateNotificationChannelJSONRequestBody defines body for UpdateNotificationChannel for application/json ContentType. +type UpdateNotificationChannelJSONRequestBody = NotificationChannelCreateRequest + +// ResendNotificationEventJSONRequestBody defines body for ResendNotificationEvent for application/json ContentType. +type ResendNotificationEventJSONRequestBody = NotificationEventResendRequest + +// CreateNotificationRuleJSONRequestBody defines body for CreateNotificationRule for application/json ContentType. +type CreateNotificationRuleJSONRequestBody = NotificationRuleCreateRequest + +// UpdateNotificationRuleJSONRequestBody defines body for UpdateNotificationRule for application/json ContentType. +type UpdateNotificationRuleJSONRequestBody = NotificationRuleCreateRequest + +// CreatePlanJSONRequestBody defines body for CreatePlan for application/json ContentType. +type CreatePlanJSONRequestBody = PlanCreate + +// UpdatePlanJSONRequestBody defines body for UpdatePlan for application/json ContentType. +type UpdatePlanJSONRequestBody = PlanReplaceUpdate + +// CreatePlanAddonJSONRequestBody defines body for CreatePlanAddon for application/json ContentType. +type CreatePlanAddonJSONRequestBody = PlanAddonCreate + +// UpdatePlanAddonJSONRequestBody defines body for UpdatePlanAddon for application/json ContentType. +type UpdatePlanAddonJSONRequestBody = PlanAddonReplaceUpdate + +// CreatePortalTokenJSONRequestBody defines body for CreatePortalToken for application/json ContentType. +type CreatePortalTokenJSONRequestBody = PortalToken + +// InvalidatePortalTokensJSONRequestBody defines body for InvalidatePortalTokens for application/json ContentType. +type InvalidatePortalTokensJSONRequestBody InvalidatePortalTokensJSONBody + +// CreateStripeCheckoutSessionJSONRequestBody defines body for CreateStripeCheckoutSession for application/json ContentType. +type CreateStripeCheckoutSessionJSONRequestBody = CreateStripeCheckoutSessionRequest + +// UpsertSubjectJSONRequestBody defines body for UpsertSubject for application/json ContentType. +type UpsertSubjectJSONRequestBody = UpsertSubjectJSONBody + +// CreateEntitlementJSONRequestBody defines body for CreateEntitlement for application/json ContentType. +type CreateEntitlementJSONRequestBody = EntitlementCreateInputs + +// CreateGrantJSONRequestBody defines body for CreateGrant for application/json ContentType. +type CreateGrantJSONRequestBody = EntitlementGrantCreateInput + +// OverrideEntitlementJSONRequestBody defines body for OverrideEntitlement for application/json ContentType. +type OverrideEntitlementJSONRequestBody = EntitlementCreateInputs + +// ResetEntitlementUsageJSONRequestBody defines body for ResetEntitlementUsage for application/json ContentType. +type ResetEntitlementUsageJSONRequestBody = ResetEntitlementUsageInput + +// CreateSubscriptionJSONRequestBody defines body for CreateSubscription for application/json ContentType. +type CreateSubscriptionJSONRequestBody = SubscriptionCreate + +// EditSubscriptionJSONRequestBody defines body for EditSubscription for application/json ContentType. +type EditSubscriptionJSONRequestBody = SubscriptionEdit + +// CreateSubscriptionAddonJSONRequestBody defines body for CreateSubscriptionAddon for application/json ContentType. +type CreateSubscriptionAddonJSONRequestBody = SubscriptionAddonCreate + +// UpdateSubscriptionAddonJSONRequestBody defines body for UpdateSubscriptionAddon for application/json ContentType. +type UpdateSubscriptionAddonJSONRequestBody = SubscriptionAddonUpdate + +// CancelSubscriptionJSONRequestBody defines body for CancelSubscription for application/json ContentType. +type CancelSubscriptionJSONRequestBody CancelSubscriptionJSONBody + +// ChangeSubscriptionJSONRequestBody defines body for ChangeSubscription for application/json ContentType. +type ChangeSubscriptionJSONRequestBody = SubscriptionChange + +// MigrateSubscriptionJSONRequestBody defines body for MigrateSubscription for application/json ContentType. +type MigrateSubscriptionJSONRequestBody MigrateSubscriptionJSONBody + +// CreateCustomerEntitlementV2JSONRequestBody defines body for CreateCustomerEntitlementV2 for application/json ContentType. +type CreateCustomerEntitlementV2JSONRequestBody = EntitlementV2CreateInputs + +// CreateCustomerEntitlementGrantV2JSONRequestBody defines body for CreateCustomerEntitlementGrantV2 for application/json ContentType. +type CreateCustomerEntitlementGrantV2JSONRequestBody = EntitlementGrantCreateInputV2 + +// OverrideCustomerEntitlementV2JSONRequestBody defines body for OverrideCustomerEntitlementV2 for application/json ContentType. +type OverrideCustomerEntitlementV2JSONRequestBody = EntitlementV2CreateInputs + +// ResetCustomerEntitlementUsageV2JSONRequestBody defines body for ResetCustomerEntitlementUsageV2 for application/json ContentType. +type ResetCustomerEntitlementUsageV2JSONRequestBody = ResetEntitlementUsageInput + +// Getter for additional properties for ErrorExtension. Returns the specified +// element and whether it was found +func (a ErrorExtension) Get(fieldName string) (value interface{}, found bool) { + if a.AdditionalProperties != nil { + value, found = a.AdditionalProperties[fieldName] + } + return +} + +// Setter for additional properties for ErrorExtension +func (a *ErrorExtension) Set(fieldName string, value interface{}) { + if a.AdditionalProperties == nil { + a.AdditionalProperties = make(map[string]interface{}) + } + a.AdditionalProperties[fieldName] = value +} + +// Override default JSON handling for ErrorExtension to handle AdditionalProperties +func (a *ErrorExtension) UnmarshalJSON(b []byte) error { + object := make(map[string]json.RawMessage) + err := json.Unmarshal(b, &object) + if err != nil { + return err + } + + if raw, found := object["code"]; found { + err = json.Unmarshal(raw, &a.Code) + if err != nil { + return fmt.Errorf("error reading 'code': %w", err) + } + delete(object, "code") + } + + if raw, found := object["field"]; found { + err = json.Unmarshal(raw, &a.Field) + if err != nil { + return fmt.Errorf("error reading 'field': %w", err) + } + delete(object, "field") + } + + if raw, found := object["message"]; found { + err = json.Unmarshal(raw, &a.Message) + if err != nil { + return fmt.Errorf("error reading 'message': %w", err) + } + delete(object, "message") + } + + if len(object) != 0 { + a.AdditionalProperties = make(map[string]interface{}) + for fieldName, fieldBuf := range object { + var fieldVal interface{} + err := json.Unmarshal(fieldBuf, &fieldVal) + if err != nil { + return fmt.Errorf("error unmarshaling field %s: %w", fieldName, err) + } + a.AdditionalProperties[fieldName] = fieldVal + } + } + return nil +} + +// Override default JSON handling for ErrorExtension to handle AdditionalProperties +func (a ErrorExtension) MarshalJSON() ([]byte, error) { + var err error + object := make(map[string]json.RawMessage) + + object["code"], err = json.Marshal(a.Code) + if err != nil { + return nil, fmt.Errorf("error marshaling 'code': %w", err) + } + + object["field"], err = json.Marshal(a.Field) + if err != nil { + return nil, fmt.Errorf("error marshaling 'field': %w", err) + } + + object["message"], err = json.Marshal(a.Message) + if err != nil { + return nil, fmt.Errorf("error marshaling 'message': %w", err) + } + + for fieldName, field := range a.AdditionalProperties { + object[fieldName], err = json.Marshal(field) + if err != nil { + return nil, fmt.Errorf("error marshaling '%s': %w", fieldName, err) + } + } + return json.Marshal(object) +} + +// AsStripeApp returns the union data inside the App as a StripeApp +func (t App) AsStripeApp() (StripeApp, error) { + var body StripeApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeApp overwrites any union data inside the App as the provided StripeApp +func (t *App) FromStripeApp(v StripeApp) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeApp performs a merge with any union data inside the App, using the provided StripeApp +func (t *App) MergeStripeApp(v StripeApp) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxApp returns the union data inside the App as a SandboxApp +func (t App) AsSandboxApp() (SandboxApp, error) { + var body SandboxApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxApp overwrites any union data inside the App as the provided SandboxApp +func (t *App) FromSandboxApp(v SandboxApp) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxApp performs a merge with any union data inside the App, using the provided SandboxApp +func (t *App) MergeSandboxApp(v SandboxApp) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingApp returns the union data inside the App as a CustomInvoicingApp +func (t App) AsCustomInvoicingApp() (CustomInvoicingApp, error) { + var body CustomInvoicingApp + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingApp overwrites any union data inside the App as the provided CustomInvoicingApp +func (t *App) FromCustomInvoicingApp(v CustomInvoicingApp) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingApp performs a merge with any union data inside the App, using the provided CustomInvoicingApp +func (t *App) MergeCustomInvoicingApp(v CustomInvoicingApp) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t App) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t App) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingApp() + case "sandbox": + return t.AsSandboxApp() + case "stripe": + return t.AsStripeApp() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t App) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *App) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeAppReplaceUpdate returns the union data inside the AppReplaceUpdate as a StripeAppReplaceUpdate +func (t AppReplaceUpdate) AsStripeAppReplaceUpdate() (StripeAppReplaceUpdate, error) { + var body StripeAppReplaceUpdate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeAppReplaceUpdate overwrites any union data inside the AppReplaceUpdate as the provided StripeAppReplaceUpdate +func (t *AppReplaceUpdate) FromStripeAppReplaceUpdate(v StripeAppReplaceUpdate) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeAppReplaceUpdate performs a merge with any union data inside the AppReplaceUpdate, using the provided StripeAppReplaceUpdate +func (t *AppReplaceUpdate) MergeStripeAppReplaceUpdate(v StripeAppReplaceUpdate) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxAppReplaceUpdate returns the union data inside the AppReplaceUpdate as a SandboxAppReplaceUpdate +func (t AppReplaceUpdate) AsSandboxAppReplaceUpdate() (SandboxAppReplaceUpdate, error) { + var body SandboxAppReplaceUpdate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxAppReplaceUpdate overwrites any union data inside the AppReplaceUpdate as the provided SandboxAppReplaceUpdate +func (t *AppReplaceUpdate) FromSandboxAppReplaceUpdate(v SandboxAppReplaceUpdate) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxAppReplaceUpdate performs a merge with any union data inside the AppReplaceUpdate, using the provided SandboxAppReplaceUpdate +func (t *AppReplaceUpdate) MergeSandboxAppReplaceUpdate(v SandboxAppReplaceUpdate) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingAppReplaceUpdate returns the union data inside the AppReplaceUpdate as a CustomInvoicingAppReplaceUpdate +func (t AppReplaceUpdate) AsCustomInvoicingAppReplaceUpdate() (CustomInvoicingAppReplaceUpdate, error) { + var body CustomInvoicingAppReplaceUpdate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingAppReplaceUpdate overwrites any union data inside the AppReplaceUpdate as the provided CustomInvoicingAppReplaceUpdate +func (t *AppReplaceUpdate) FromCustomInvoicingAppReplaceUpdate(v CustomInvoicingAppReplaceUpdate) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingAppReplaceUpdate performs a merge with any union data inside the AppReplaceUpdate, using the provided CustomInvoicingAppReplaceUpdate +func (t *AppReplaceUpdate) MergeCustomInvoicingAppReplaceUpdate(v CustomInvoicingAppReplaceUpdate) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t AppReplaceUpdate) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t AppReplaceUpdate) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingAppReplaceUpdate() + case "sandbox": + return t.AsSandboxAppReplaceUpdate() + case "stripe": + return t.AsStripeAppReplaceUpdate() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t AppReplaceUpdate) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *AppReplaceUpdate) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsDiscountReasonMaximumSpend returns the union data inside the BillingDiscountReason as a DiscountReasonMaximumSpend +func (t BillingDiscountReason) AsDiscountReasonMaximumSpend() (DiscountReasonMaximumSpend, error) { + var body DiscountReasonMaximumSpend + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscountReasonMaximumSpend overwrites any union data inside the BillingDiscountReason as the provided DiscountReasonMaximumSpend +func (t *BillingDiscountReason) FromDiscountReasonMaximumSpend(v DiscountReasonMaximumSpend) error { + v.Type = "maximum_spend" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscountReasonMaximumSpend performs a merge with any union data inside the BillingDiscountReason, using the provided DiscountReasonMaximumSpend +func (t *BillingDiscountReason) MergeDiscountReasonMaximumSpend(v DiscountReasonMaximumSpend) error { + v.Type = "maximum_spend" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDiscountReasonRatecardPercentage returns the union data inside the BillingDiscountReason as a DiscountReasonRatecardPercentage +func (t BillingDiscountReason) AsDiscountReasonRatecardPercentage() (DiscountReasonRatecardPercentage, error) { + var body DiscountReasonRatecardPercentage + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscountReasonRatecardPercentage overwrites any union data inside the BillingDiscountReason as the provided DiscountReasonRatecardPercentage +func (t *BillingDiscountReason) FromDiscountReasonRatecardPercentage(v DiscountReasonRatecardPercentage) error { + v.Type = "ratecard_percentage" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscountReasonRatecardPercentage performs a merge with any union data inside the BillingDiscountReason, using the provided DiscountReasonRatecardPercentage +func (t *BillingDiscountReason) MergeDiscountReasonRatecardPercentage(v DiscountReasonRatecardPercentage) error { + v.Type = "ratecard_percentage" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDiscountReasonRatecardUsage returns the union data inside the BillingDiscountReason as a DiscountReasonRatecardUsage +func (t BillingDiscountReason) AsDiscountReasonRatecardUsage() (DiscountReasonRatecardUsage, error) { + var body DiscountReasonRatecardUsage + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDiscountReasonRatecardUsage overwrites any union data inside the BillingDiscountReason as the provided DiscountReasonRatecardUsage +func (t *BillingDiscountReason) FromDiscountReasonRatecardUsage(v DiscountReasonRatecardUsage) error { + v.Type = "ratecard_usage" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDiscountReasonRatecardUsage performs a merge with any union data inside the BillingDiscountReason, using the provided DiscountReasonRatecardUsage +func (t *BillingDiscountReason) MergeDiscountReasonRatecardUsage(v DiscountReasonRatecardUsage) error { + v.Type = "ratecard_usage" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BillingDiscountReason) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t BillingDiscountReason) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "maximum_spend": + return t.AsDiscountReasonMaximumSpend() + case "ratecard_percentage": + return t.AsDiscountReasonRatecardPercentage() + case "ratecard_usage": + return t.AsDiscountReasonRatecardUsage() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t BillingDiscountReason) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BillingDiscountReason) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsBillingProfileApps returns the union data inside the BillingProfileAppsOrReference as a BillingProfileApps +func (t BillingProfileAppsOrReference) AsBillingProfileApps() (BillingProfileApps, error) { + var body BillingProfileApps + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingProfileApps overwrites any union data inside the BillingProfileAppsOrReference as the provided BillingProfileApps +func (t *BillingProfileAppsOrReference) FromBillingProfileApps(v BillingProfileApps) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingProfileApps performs a merge with any union data inside the BillingProfileAppsOrReference, using the provided BillingProfileApps +func (t *BillingProfileAppsOrReference) MergeBillingProfileApps(v BillingProfileApps) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsBillingProfileAppReferences returns the union data inside the BillingProfileAppsOrReference as a BillingProfileAppReferences +func (t BillingProfileAppsOrReference) AsBillingProfileAppReferences() (BillingProfileAppReferences, error) { + var body BillingProfileAppReferences + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingProfileAppReferences overwrites any union data inside the BillingProfileAppsOrReference as the provided BillingProfileAppReferences +func (t *BillingProfileAppsOrReference) FromBillingProfileAppReferences(v BillingProfileAppReferences) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingProfileAppReferences performs a merge with any union data inside the BillingProfileAppsOrReference, using the provided BillingProfileAppReferences +func (t *BillingProfileAppsOrReference) MergeBillingProfileAppReferences(v BillingProfileAppReferences) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BillingProfileAppsOrReference) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BillingProfileAppsOrReference) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsBillingWorkflowCollectionAlignmentSubscription returns the union data inside the BillingWorkflowCollectionAlignment as a BillingWorkflowCollectionAlignmentSubscription +func (t BillingWorkflowCollectionAlignment) AsBillingWorkflowCollectionAlignmentSubscription() (BillingWorkflowCollectionAlignmentSubscription, error) { + var body BillingWorkflowCollectionAlignmentSubscription + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingWorkflowCollectionAlignmentSubscription overwrites any union data inside the BillingWorkflowCollectionAlignment as the provided BillingWorkflowCollectionAlignmentSubscription +func (t *BillingWorkflowCollectionAlignment) FromBillingWorkflowCollectionAlignmentSubscription(v BillingWorkflowCollectionAlignmentSubscription) error { + v.Type = "subscription" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingWorkflowCollectionAlignmentSubscription performs a merge with any union data inside the BillingWorkflowCollectionAlignment, using the provided BillingWorkflowCollectionAlignmentSubscription +func (t *BillingWorkflowCollectionAlignment) MergeBillingWorkflowCollectionAlignmentSubscription(v BillingWorkflowCollectionAlignmentSubscription) error { + v.Type = "subscription" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsBillingWorkflowCollectionAlignmentAnchored returns the union data inside the BillingWorkflowCollectionAlignment as a BillingWorkflowCollectionAlignmentAnchored +func (t BillingWorkflowCollectionAlignment) AsBillingWorkflowCollectionAlignmentAnchored() (BillingWorkflowCollectionAlignmentAnchored, error) { + var body BillingWorkflowCollectionAlignmentAnchored + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromBillingWorkflowCollectionAlignmentAnchored overwrites any union data inside the BillingWorkflowCollectionAlignment as the provided BillingWorkflowCollectionAlignmentAnchored +func (t *BillingWorkflowCollectionAlignment) FromBillingWorkflowCollectionAlignmentAnchored(v BillingWorkflowCollectionAlignmentAnchored) error { + v.Type = "anchored" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeBillingWorkflowCollectionAlignmentAnchored performs a merge with any union data inside the BillingWorkflowCollectionAlignment, using the provided BillingWorkflowCollectionAlignmentAnchored +func (t *BillingWorkflowCollectionAlignment) MergeBillingWorkflowCollectionAlignmentAnchored(v BillingWorkflowCollectionAlignmentAnchored) error { + v.Type = "anchored" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t BillingWorkflowCollectionAlignment) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t BillingWorkflowCollectionAlignment) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "anchored": + return t.AsBillingWorkflowCollectionAlignmentAnchored() + case "subscription": + return t.AsBillingWorkflowCollectionAlignmentSubscription() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t BillingWorkflowCollectionAlignment) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *BillingWorkflowCollectionAlignment) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsCustomerId returns the union data inside the CreateStripeCheckoutSessionRequest_Customer as a CustomerId +func (t CreateStripeCheckoutSessionRequest_Customer) AsCustomerId() (CustomerId, error) { + var body CustomerId + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomerId overwrites any union data inside the CreateStripeCheckoutSessionRequest_Customer as the provided CustomerId +func (t *CreateStripeCheckoutSessionRequest_Customer) FromCustomerId(v CustomerId) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomerId performs a merge with any union data inside the CreateStripeCheckoutSessionRequest_Customer, using the provided CustomerId +func (t *CreateStripeCheckoutSessionRequest_Customer) MergeCustomerId(v CustomerId) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomerKey returns the union data inside the CreateStripeCheckoutSessionRequest_Customer as a CustomerKey +func (t CreateStripeCheckoutSessionRequest_Customer) AsCustomerKey() (CustomerKey, error) { + var body CustomerKey + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomerKey overwrites any union data inside the CreateStripeCheckoutSessionRequest_Customer as the provided CustomerKey +func (t *CreateStripeCheckoutSessionRequest_Customer) FromCustomerKey(v CustomerKey) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomerKey performs a merge with any union data inside the CreateStripeCheckoutSessionRequest_Customer, using the provided CustomerKey +func (t *CreateStripeCheckoutSessionRequest_Customer) MergeCustomerKey(v CustomerKey) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomerCreate returns the union data inside the CreateStripeCheckoutSessionRequest_Customer as a CustomerCreate +func (t CreateStripeCheckoutSessionRequest_Customer) AsCustomerCreate() (CustomerCreate, error) { + var body CustomerCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomerCreate overwrites any union data inside the CreateStripeCheckoutSessionRequest_Customer as the provided CustomerCreate +func (t *CreateStripeCheckoutSessionRequest_Customer) FromCustomerCreate(v CustomerCreate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomerCreate performs a merge with any union data inside the CreateStripeCheckoutSessionRequest_Customer, using the provided CustomerCreate +func (t *CreateStripeCheckoutSessionRequest_Customer) MergeCustomerCreate(v CustomerCreate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CreateStripeCheckoutSessionRequest_Customer) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CreateStripeCheckoutSessionRequest_Customer) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeCustomerAppData returns the union data inside the CustomerAppData as a StripeCustomerAppData +func (t CustomerAppData) AsStripeCustomerAppData() (StripeCustomerAppData, error) { + var body StripeCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeCustomerAppData overwrites any union data inside the CustomerAppData as the provided StripeCustomerAppData +func (t *CustomerAppData) FromStripeCustomerAppData(v StripeCustomerAppData) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeCustomerAppData performs a merge with any union data inside the CustomerAppData, using the provided StripeCustomerAppData +func (t *CustomerAppData) MergeStripeCustomerAppData(v StripeCustomerAppData) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxCustomerAppData returns the union data inside the CustomerAppData as a SandboxCustomerAppData +func (t CustomerAppData) AsSandboxCustomerAppData() (SandboxCustomerAppData, error) { + var body SandboxCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxCustomerAppData overwrites any union data inside the CustomerAppData as the provided SandboxCustomerAppData +func (t *CustomerAppData) FromSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxCustomerAppData performs a merge with any union data inside the CustomerAppData, using the provided SandboxCustomerAppData +func (t *CustomerAppData) MergeSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingCustomerAppData returns the union data inside the CustomerAppData as a CustomInvoicingCustomerAppData +func (t CustomerAppData) AsCustomInvoicingCustomerAppData() (CustomInvoicingCustomerAppData, error) { + var body CustomInvoicingCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingCustomerAppData overwrites any union data inside the CustomerAppData as the provided CustomInvoicingCustomerAppData +func (t *CustomerAppData) FromCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingCustomerAppData performs a merge with any union data inside the CustomerAppData, using the provided CustomInvoicingCustomerAppData +func (t *CustomerAppData) MergeCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CustomerAppData) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t CustomerAppData) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingCustomerAppData() + case "sandbox": + return t.AsSandboxCustomerAppData() + case "stripe": + return t.AsStripeCustomerAppData() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t CustomerAppData) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CustomerAppData) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsStripeCustomerAppDataCreateOrUpdateItem returns the union data inside the CustomerAppDataCreateOrUpdateItem as a StripeCustomerAppDataCreateOrUpdateItem +func (t CustomerAppDataCreateOrUpdateItem) AsStripeCustomerAppDataCreateOrUpdateItem() (StripeCustomerAppDataCreateOrUpdateItem, error) { + var body StripeCustomerAppDataCreateOrUpdateItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromStripeCustomerAppDataCreateOrUpdateItem overwrites any union data inside the CustomerAppDataCreateOrUpdateItem as the provided StripeCustomerAppDataCreateOrUpdateItem +func (t *CustomerAppDataCreateOrUpdateItem) FromStripeCustomerAppDataCreateOrUpdateItem(v StripeCustomerAppDataCreateOrUpdateItem) error { + v.Type = "stripe" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeStripeCustomerAppDataCreateOrUpdateItem performs a merge with any union data inside the CustomerAppDataCreateOrUpdateItem, using the provided StripeCustomerAppDataCreateOrUpdateItem +func (t *CustomerAppDataCreateOrUpdateItem) MergeStripeCustomerAppDataCreateOrUpdateItem(v StripeCustomerAppDataCreateOrUpdateItem) error { + v.Type = "stripe" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSandboxCustomerAppData returns the union data inside the CustomerAppDataCreateOrUpdateItem as a SandboxCustomerAppData +func (t CustomerAppDataCreateOrUpdateItem) AsSandboxCustomerAppData() (SandboxCustomerAppData, error) { + var body SandboxCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSandboxCustomerAppData overwrites any union data inside the CustomerAppDataCreateOrUpdateItem as the provided SandboxCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) FromSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSandboxCustomerAppData performs a merge with any union data inside the CustomerAppDataCreateOrUpdateItem, using the provided SandboxCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) MergeSandboxCustomerAppData(v SandboxCustomerAppData) error { + v.Type = "sandbox" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomInvoicingCustomerAppData returns the union data inside the CustomerAppDataCreateOrUpdateItem as a CustomInvoicingCustomerAppData +func (t CustomerAppDataCreateOrUpdateItem) AsCustomInvoicingCustomerAppData() (CustomInvoicingCustomerAppData, error) { + var body CustomInvoicingCustomerAppData + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomInvoicingCustomerAppData overwrites any union data inside the CustomerAppDataCreateOrUpdateItem as the provided CustomInvoicingCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) FromCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomInvoicingCustomerAppData performs a merge with any union data inside the CustomerAppDataCreateOrUpdateItem, using the provided CustomInvoicingCustomerAppData +func (t *CustomerAppDataCreateOrUpdateItem) MergeCustomInvoicingCustomerAppData(v CustomInvoicingCustomerAppData) error { + v.Type = "custom_invoicing" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t CustomerAppDataCreateOrUpdateItem) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t CustomerAppDataCreateOrUpdateItem) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "custom_invoicing": + return t.AsCustomInvoicingCustomerAppData() + case "sandbox": + return t.AsSandboxCustomerAppData() + case "stripe": + return t.AsStripeCustomerAppDataCreateOrUpdateItem() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t CustomerAppDataCreateOrUpdateItem) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *CustomerAppDataCreateOrUpdateItem) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMetered returns the union data inside the Entitlement as a EntitlementMetered +func (t Entitlement) AsEntitlementMetered() (EntitlementMetered, error) { + var body EntitlementMetered + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMetered overwrites any union data inside the Entitlement as the provided EntitlementMetered +func (t *Entitlement) FromEntitlementMetered(v EntitlementMetered) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMetered performs a merge with any union data inside the Entitlement, using the provided EntitlementMetered +func (t *Entitlement) MergeEntitlementMetered(v EntitlementMetered) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStatic returns the union data inside the Entitlement as a EntitlementStatic +func (t Entitlement) AsEntitlementStatic() (EntitlementStatic, error) { + var body EntitlementStatic + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStatic overwrites any union data inside the Entitlement as the provided EntitlementStatic +func (t *Entitlement) FromEntitlementStatic(v EntitlementStatic) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStatic performs a merge with any union data inside the Entitlement, using the provided EntitlementStatic +func (t *Entitlement) MergeEntitlementStatic(v EntitlementStatic) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBoolean returns the union data inside the Entitlement as a EntitlementBoolean +func (t Entitlement) AsEntitlementBoolean() (EntitlementBoolean, error) { + var body EntitlementBoolean + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBoolean overwrites any union data inside the Entitlement as the provided EntitlementBoolean +func (t *Entitlement) FromEntitlementBoolean(v EntitlementBoolean) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBoolean performs a merge with any union data inside the Entitlement, using the provided EntitlementBoolean +func (t *Entitlement) MergeEntitlementBoolean(v EntitlementBoolean) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t Entitlement) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t Entitlement) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBoolean() + case "metered": + return t.AsEntitlementMetered() + case "static": + return t.AsEntitlementStatic() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t Entitlement) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *Entitlement) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMeteredCreateInputs returns the union data inside the EntitlementCreateInputs as a EntitlementMeteredCreateInputs +func (t EntitlementCreateInputs) AsEntitlementMeteredCreateInputs() (EntitlementMeteredCreateInputs, error) { + var body EntitlementMeteredCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMeteredCreateInputs overwrites any union data inside the EntitlementCreateInputs as the provided EntitlementMeteredCreateInputs +func (t *EntitlementCreateInputs) FromEntitlementMeteredCreateInputs(v EntitlementMeteredCreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMeteredCreateInputs performs a merge with any union data inside the EntitlementCreateInputs, using the provided EntitlementMeteredCreateInputs +func (t *EntitlementCreateInputs) MergeEntitlementMeteredCreateInputs(v EntitlementMeteredCreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStaticCreateInputs returns the union data inside the EntitlementCreateInputs as a EntitlementStaticCreateInputs +func (t EntitlementCreateInputs) AsEntitlementStaticCreateInputs() (EntitlementStaticCreateInputs, error) { + var body EntitlementStaticCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStaticCreateInputs overwrites any union data inside the EntitlementCreateInputs as the provided EntitlementStaticCreateInputs +func (t *EntitlementCreateInputs) FromEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStaticCreateInputs performs a merge with any union data inside the EntitlementCreateInputs, using the provided EntitlementStaticCreateInputs +func (t *EntitlementCreateInputs) MergeEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBooleanCreateInputs returns the union data inside the EntitlementCreateInputs as a EntitlementBooleanCreateInputs +func (t EntitlementCreateInputs) AsEntitlementBooleanCreateInputs() (EntitlementBooleanCreateInputs, error) { + var body EntitlementBooleanCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBooleanCreateInputs overwrites any union data inside the EntitlementCreateInputs as the provided EntitlementBooleanCreateInputs +func (t *EntitlementCreateInputs) FromEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBooleanCreateInputs performs a merge with any union data inside the EntitlementCreateInputs, using the provided EntitlementBooleanCreateInputs +func (t *EntitlementCreateInputs) MergeEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t EntitlementCreateInputs) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t EntitlementCreateInputs) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBooleanCreateInputs() + case "metered": + return t.AsEntitlementMeteredCreateInputs() + case "static": + return t.AsEntitlementStaticCreateInputs() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t EntitlementCreateInputs) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *EntitlementCreateInputs) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMeteredV2 returns the union data inside the EntitlementV2 as a EntitlementMeteredV2 +func (t EntitlementV2) AsEntitlementMeteredV2() (EntitlementMeteredV2, error) { + var body EntitlementMeteredV2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMeteredV2 overwrites any union data inside the EntitlementV2 as the provided EntitlementMeteredV2 +func (t *EntitlementV2) FromEntitlementMeteredV2(v EntitlementMeteredV2) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMeteredV2 performs a merge with any union data inside the EntitlementV2, using the provided EntitlementMeteredV2 +func (t *EntitlementV2) MergeEntitlementMeteredV2(v EntitlementMeteredV2) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStaticV2 returns the union data inside the EntitlementV2 as a EntitlementStaticV2 +func (t EntitlementV2) AsEntitlementStaticV2() (EntitlementStaticV2, error) { + var body EntitlementStaticV2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStaticV2 overwrites any union data inside the EntitlementV2 as the provided EntitlementStaticV2 +func (t *EntitlementV2) FromEntitlementStaticV2(v EntitlementStaticV2) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStaticV2 performs a merge with any union data inside the EntitlementV2, using the provided EntitlementStaticV2 +func (t *EntitlementV2) MergeEntitlementStaticV2(v EntitlementStaticV2) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBooleanV2 returns the union data inside the EntitlementV2 as a EntitlementBooleanV2 +func (t EntitlementV2) AsEntitlementBooleanV2() (EntitlementBooleanV2, error) { + var body EntitlementBooleanV2 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBooleanV2 overwrites any union data inside the EntitlementV2 as the provided EntitlementBooleanV2 +func (t *EntitlementV2) FromEntitlementBooleanV2(v EntitlementBooleanV2) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBooleanV2 performs a merge with any union data inside the EntitlementV2, using the provided EntitlementBooleanV2 +func (t *EntitlementV2) MergeEntitlementBooleanV2(v EntitlementBooleanV2) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t EntitlementV2) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t EntitlementV2) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBooleanV2() + case "metered": + return t.AsEntitlementMeteredV2() + case "static": + return t.AsEntitlementStaticV2() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t EntitlementV2) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *EntitlementV2) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEntitlementMeteredV2CreateInputs returns the union data inside the EntitlementV2CreateInputs as a EntitlementMeteredV2CreateInputs +func (t EntitlementV2CreateInputs) AsEntitlementMeteredV2CreateInputs() (EntitlementMeteredV2CreateInputs, error) { + var body EntitlementMeteredV2CreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementMeteredV2CreateInputs overwrites any union data inside the EntitlementV2CreateInputs as the provided EntitlementMeteredV2CreateInputs +func (t *EntitlementV2CreateInputs) FromEntitlementMeteredV2CreateInputs(v EntitlementMeteredV2CreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementMeteredV2CreateInputs performs a merge with any union data inside the EntitlementV2CreateInputs, using the provided EntitlementMeteredV2CreateInputs +func (t *EntitlementV2CreateInputs) MergeEntitlementMeteredV2CreateInputs(v EntitlementMeteredV2CreateInputs) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementStaticCreateInputs returns the union data inside the EntitlementV2CreateInputs as a EntitlementStaticCreateInputs +func (t EntitlementV2CreateInputs) AsEntitlementStaticCreateInputs() (EntitlementStaticCreateInputs, error) { + var body EntitlementStaticCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementStaticCreateInputs overwrites any union data inside the EntitlementV2CreateInputs as the provided EntitlementStaticCreateInputs +func (t *EntitlementV2CreateInputs) FromEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementStaticCreateInputs performs a merge with any union data inside the EntitlementV2CreateInputs, using the provided EntitlementStaticCreateInputs +func (t *EntitlementV2CreateInputs) MergeEntitlementStaticCreateInputs(v EntitlementStaticCreateInputs) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementBooleanCreateInputs returns the union data inside the EntitlementV2CreateInputs as a EntitlementBooleanCreateInputs +func (t EntitlementV2CreateInputs) AsEntitlementBooleanCreateInputs() (EntitlementBooleanCreateInputs, error) { + var body EntitlementBooleanCreateInputs + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementBooleanCreateInputs overwrites any union data inside the EntitlementV2CreateInputs as the provided EntitlementBooleanCreateInputs +func (t *EntitlementV2CreateInputs) FromEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementBooleanCreateInputs performs a merge with any union data inside the EntitlementV2CreateInputs, using the provided EntitlementBooleanCreateInputs +func (t *EntitlementV2CreateInputs) MergeEntitlementBooleanCreateInputs(v EntitlementBooleanCreateInputs) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t EntitlementV2CreateInputs) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t EntitlementV2CreateInputs) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsEntitlementBooleanCreateInputs() + case "metered": + return t.AsEntitlementMeteredV2CreateInputs() + case "static": + return t.AsEntitlementStaticCreateInputs() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t EntitlementV2CreateInputs) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *EntitlementV2CreateInputs) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsFeatureManualUnitCost returns the union data inside the FeatureUnitCost as a FeatureManualUnitCost +func (t FeatureUnitCost) AsFeatureManualUnitCost() (FeatureManualUnitCost, error) { + var body FeatureManualUnitCost + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFeatureManualUnitCost overwrites any union data inside the FeatureUnitCost as the provided FeatureManualUnitCost +func (t *FeatureUnitCost) FromFeatureManualUnitCost(v FeatureManualUnitCost) error { + v.Type = "manual" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFeatureManualUnitCost performs a merge with any union data inside the FeatureUnitCost, using the provided FeatureManualUnitCost +func (t *FeatureUnitCost) MergeFeatureManualUnitCost(v FeatureManualUnitCost) error { + v.Type = "manual" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsFeatureLLMUnitCost returns the union data inside the FeatureUnitCost as a FeatureLLMUnitCost +func (t FeatureUnitCost) AsFeatureLLMUnitCost() (FeatureLLMUnitCost, error) { + var body FeatureLLMUnitCost + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFeatureLLMUnitCost overwrites any union data inside the FeatureUnitCost as the provided FeatureLLMUnitCost +func (t *FeatureUnitCost) FromFeatureLLMUnitCost(v FeatureLLMUnitCost) error { + v.Type = "llm" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFeatureLLMUnitCost performs a merge with any union data inside the FeatureUnitCost, using the provided FeatureLLMUnitCost +func (t *FeatureUnitCost) MergeFeatureLLMUnitCost(v FeatureLLMUnitCost) error { + v.Type = "llm" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t FeatureUnitCost) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t FeatureUnitCost) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "llm": + return t.AsFeatureLLMUnitCost() + case "manual": + return t.AsFeatureManualUnitCost() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t FeatureUnitCost) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *FeatureUnitCost) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEvent returns the union data inside the IngestEventsBody as a Event +func (t IngestEventsBody) AsEvent() (Event, error) { + var body Event + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEvent overwrites any union data inside the IngestEventsBody as the provided Event +func (t *IngestEventsBody) FromEvent(v Event) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEvent performs a merge with any union data inside the IngestEventsBody, using the provided Event +func (t *IngestEventsBody) MergeEvent(v Event) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsIngestEventsBody1 returns the union data inside the IngestEventsBody as a IngestEventsBody1 +func (t IngestEventsBody) AsIngestEventsBody1() (IngestEventsBody1, error) { + var body IngestEventsBody1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromIngestEventsBody1 overwrites any union data inside the IngestEventsBody as the provided IngestEventsBody1 +func (t *IngestEventsBody) FromIngestEventsBody1(v IngestEventsBody1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeIngestEventsBody1 performs a merge with any union data inside the IngestEventsBody, using the provided IngestEventsBody1 +func (t *IngestEventsBody) MergeIngestEventsBody1(v IngestEventsBody1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t IngestEventsBody) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *IngestEventsBody) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsListEntitlementsResult0 returns the union data inside the ListEntitlementsResult as a ListEntitlementsResult0 +func (t ListEntitlementsResult) AsListEntitlementsResult0() (ListEntitlementsResult0, error) { + var body ListEntitlementsResult0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromListEntitlementsResult0 overwrites any union data inside the ListEntitlementsResult as the provided ListEntitlementsResult0 +func (t *ListEntitlementsResult) FromListEntitlementsResult0(v ListEntitlementsResult0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeListEntitlementsResult0 performs a merge with any union data inside the ListEntitlementsResult, using the provided ListEntitlementsResult0 +func (t *ListEntitlementsResult) MergeListEntitlementsResult0(v ListEntitlementsResult0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEntitlementPaginatedResponse returns the union data inside the ListEntitlementsResult as a EntitlementPaginatedResponse +func (t ListEntitlementsResult) AsEntitlementPaginatedResponse() (EntitlementPaginatedResponse, error) { + var body EntitlementPaginatedResponse + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEntitlementPaginatedResponse overwrites any union data inside the ListEntitlementsResult as the provided EntitlementPaginatedResponse +func (t *ListEntitlementsResult) FromEntitlementPaginatedResponse(v EntitlementPaginatedResponse) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEntitlementPaginatedResponse performs a merge with any union data inside the ListEntitlementsResult, using the provided EntitlementPaginatedResponse +func (t *ListEntitlementsResult) MergeEntitlementPaginatedResponse(v EntitlementPaginatedResponse) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t ListEntitlementsResult) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *ListEntitlementsResult) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsListFeaturesResult0 returns the union data inside the ListFeaturesResult as a ListFeaturesResult0 +func (t ListFeaturesResult) AsListFeaturesResult0() (ListFeaturesResult0, error) { + var body ListFeaturesResult0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromListFeaturesResult0 overwrites any union data inside the ListFeaturesResult as the provided ListFeaturesResult0 +func (t *ListFeaturesResult) FromListFeaturesResult0(v ListFeaturesResult0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeListFeaturesResult0 performs a merge with any union data inside the ListFeaturesResult, using the provided ListFeaturesResult0 +func (t *ListFeaturesResult) MergeListFeaturesResult0(v ListFeaturesResult0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsFeaturePaginatedResponse returns the union data inside the ListFeaturesResult as a FeaturePaginatedResponse +func (t ListFeaturesResult) AsFeaturePaginatedResponse() (FeaturePaginatedResponse, error) { + var body FeaturePaginatedResponse + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFeaturePaginatedResponse overwrites any union data inside the ListFeaturesResult as the provided FeaturePaginatedResponse +func (t *ListFeaturesResult) FromFeaturePaginatedResponse(v FeaturePaginatedResponse) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFeaturePaginatedResponse performs a merge with any union data inside the ListFeaturesResult, using the provided FeaturePaginatedResponse +func (t *ListFeaturesResult) MergeFeaturePaginatedResponse(v FeaturePaginatedResponse) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t ListFeaturesResult) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *ListFeaturesResult) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsMeasureUsageFromPreset returns the union data inside the MeasureUsageFrom as a MeasureUsageFromPreset +func (t MeasureUsageFrom) AsMeasureUsageFromPreset() (MeasureUsageFromPreset, error) { + var body MeasureUsageFromPreset + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromMeasureUsageFromPreset overwrites any union data inside the MeasureUsageFrom as the provided MeasureUsageFromPreset +func (t *MeasureUsageFrom) FromMeasureUsageFromPreset(v MeasureUsageFromPreset) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeMeasureUsageFromPreset performs a merge with any union data inside the MeasureUsageFrom, using the provided MeasureUsageFromPreset +func (t *MeasureUsageFrom) MergeMeasureUsageFromPreset(v MeasureUsageFromPreset) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsMeasureUsageFromTime returns the union data inside the MeasureUsageFrom as a MeasureUsageFromTime +func (t MeasureUsageFrom) AsMeasureUsageFromTime() (MeasureUsageFromTime, error) { + var body MeasureUsageFromTime + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromMeasureUsageFromTime overwrites any union data inside the MeasureUsageFrom as the provided MeasureUsageFromTime +func (t *MeasureUsageFrom) FromMeasureUsageFromTime(v MeasureUsageFromTime) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeMeasureUsageFromTime performs a merge with any union data inside the MeasureUsageFrom, using the provided MeasureUsageFromTime +func (t *MeasureUsageFrom) MergeMeasureUsageFromTime(v MeasureUsageFromTime) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t MeasureUsageFrom) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *MeasureUsageFrom) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsNotificationEventResetPayload returns the union data inside the NotificationEventPayload as a NotificationEventResetPayload +func (t NotificationEventPayload) AsNotificationEventResetPayload() (NotificationEventResetPayload, error) { + var body NotificationEventResetPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventResetPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventResetPayload +func (t *NotificationEventPayload) FromNotificationEventResetPayload(v NotificationEventResetPayload) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventResetPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventResetPayload +func (t *NotificationEventPayload) MergeNotificationEventResetPayload(v NotificationEventResetPayload) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationEventBalanceThresholdPayload returns the union data inside the NotificationEventPayload as a NotificationEventBalanceThresholdPayload +func (t NotificationEventPayload) AsNotificationEventBalanceThresholdPayload() (NotificationEventBalanceThresholdPayload, error) { + var body NotificationEventBalanceThresholdPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventBalanceThresholdPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventBalanceThresholdPayload +func (t *NotificationEventPayload) FromNotificationEventBalanceThresholdPayload(v NotificationEventBalanceThresholdPayload) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventBalanceThresholdPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventBalanceThresholdPayload +func (t *NotificationEventPayload) MergeNotificationEventBalanceThresholdPayload(v NotificationEventBalanceThresholdPayload) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationEventInvoiceCreatedPayload returns the union data inside the NotificationEventPayload as a NotificationEventInvoiceCreatedPayload +func (t NotificationEventPayload) AsNotificationEventInvoiceCreatedPayload() (NotificationEventInvoiceCreatedPayload, error) { + var body NotificationEventInvoiceCreatedPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventInvoiceCreatedPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventInvoiceCreatedPayload +func (t *NotificationEventPayload) FromNotificationEventInvoiceCreatedPayload(v NotificationEventInvoiceCreatedPayload) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventInvoiceCreatedPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventInvoiceCreatedPayload +func (t *NotificationEventPayload) MergeNotificationEventInvoiceCreatedPayload(v NotificationEventInvoiceCreatedPayload) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationEventInvoiceUpdatedPayload returns the union data inside the NotificationEventPayload as a NotificationEventInvoiceUpdatedPayload +func (t NotificationEventPayload) AsNotificationEventInvoiceUpdatedPayload() (NotificationEventInvoiceUpdatedPayload, error) { + var body NotificationEventInvoiceUpdatedPayload + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationEventInvoiceUpdatedPayload overwrites any union data inside the NotificationEventPayload as the provided NotificationEventInvoiceUpdatedPayload +func (t *NotificationEventPayload) FromNotificationEventInvoiceUpdatedPayload(v NotificationEventInvoiceUpdatedPayload) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationEventInvoiceUpdatedPayload performs a merge with any union data inside the NotificationEventPayload, using the provided NotificationEventInvoiceUpdatedPayload +func (t *NotificationEventPayload) MergeNotificationEventInvoiceUpdatedPayload(v NotificationEventInvoiceUpdatedPayload) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t NotificationEventPayload) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t NotificationEventPayload) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "entitlements.balance.threshold": + return t.AsNotificationEventBalanceThresholdPayload() + case "entitlements.reset": + return t.AsNotificationEventResetPayload() + case "invoice.created": + return t.AsNotificationEventInvoiceCreatedPayload() + case "invoice.updated": + return t.AsNotificationEventInvoiceUpdatedPayload() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t NotificationEventPayload) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *NotificationEventPayload) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsNotificationRuleBalanceThreshold returns the union data inside the NotificationRule as a NotificationRuleBalanceThreshold +func (t NotificationRule) AsNotificationRuleBalanceThreshold() (NotificationRuleBalanceThreshold, error) { + var body NotificationRuleBalanceThreshold + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleBalanceThreshold overwrites any union data inside the NotificationRule as the provided NotificationRuleBalanceThreshold +func (t *NotificationRule) FromNotificationRuleBalanceThreshold(v NotificationRuleBalanceThreshold) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleBalanceThreshold performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleBalanceThreshold +func (t *NotificationRule) MergeNotificationRuleBalanceThreshold(v NotificationRuleBalanceThreshold) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleEntitlementReset returns the union data inside the NotificationRule as a NotificationRuleEntitlementReset +func (t NotificationRule) AsNotificationRuleEntitlementReset() (NotificationRuleEntitlementReset, error) { + var body NotificationRuleEntitlementReset + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleEntitlementReset overwrites any union data inside the NotificationRule as the provided NotificationRuleEntitlementReset +func (t *NotificationRule) FromNotificationRuleEntitlementReset(v NotificationRuleEntitlementReset) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleEntitlementReset performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleEntitlementReset +func (t *NotificationRule) MergeNotificationRuleEntitlementReset(v NotificationRuleEntitlementReset) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceCreated returns the union data inside the NotificationRule as a NotificationRuleInvoiceCreated +func (t NotificationRule) AsNotificationRuleInvoiceCreated() (NotificationRuleInvoiceCreated, error) { + var body NotificationRuleInvoiceCreated + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceCreated overwrites any union data inside the NotificationRule as the provided NotificationRuleInvoiceCreated +func (t *NotificationRule) FromNotificationRuleInvoiceCreated(v NotificationRuleInvoiceCreated) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceCreated performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleInvoiceCreated +func (t *NotificationRule) MergeNotificationRuleInvoiceCreated(v NotificationRuleInvoiceCreated) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceUpdated returns the union data inside the NotificationRule as a NotificationRuleInvoiceUpdated +func (t NotificationRule) AsNotificationRuleInvoiceUpdated() (NotificationRuleInvoiceUpdated, error) { + var body NotificationRuleInvoiceUpdated + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceUpdated overwrites any union data inside the NotificationRule as the provided NotificationRuleInvoiceUpdated +func (t *NotificationRule) FromNotificationRuleInvoiceUpdated(v NotificationRuleInvoiceUpdated) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceUpdated performs a merge with any union data inside the NotificationRule, using the provided NotificationRuleInvoiceUpdated +func (t *NotificationRule) MergeNotificationRuleInvoiceUpdated(v NotificationRuleInvoiceUpdated) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t NotificationRule) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t NotificationRule) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "entitlements.balance.threshold": + return t.AsNotificationRuleBalanceThreshold() + case "entitlements.reset": + return t.AsNotificationRuleEntitlementReset() + case "invoice.created": + return t.AsNotificationRuleInvoiceCreated() + case "invoice.updated": + return t.AsNotificationRuleInvoiceUpdated() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t NotificationRule) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *NotificationRule) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsNotificationRuleBalanceThresholdCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleBalanceThresholdCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleBalanceThresholdCreateRequest() (NotificationRuleBalanceThresholdCreateRequest, error) { + var body NotificationRuleBalanceThresholdCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleBalanceThresholdCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleBalanceThresholdCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleBalanceThresholdCreateRequest(v NotificationRuleBalanceThresholdCreateRequest) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleBalanceThresholdCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleBalanceThresholdCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleBalanceThresholdCreateRequest(v NotificationRuleBalanceThresholdCreateRequest) error { + v.Type = "entitlements.balance.threshold" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleEntitlementResetCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleEntitlementResetCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleEntitlementResetCreateRequest() (NotificationRuleEntitlementResetCreateRequest, error) { + var body NotificationRuleEntitlementResetCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleEntitlementResetCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleEntitlementResetCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleEntitlementResetCreateRequest(v NotificationRuleEntitlementResetCreateRequest) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleEntitlementResetCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleEntitlementResetCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleEntitlementResetCreateRequest(v NotificationRuleEntitlementResetCreateRequest) error { + v.Type = "entitlements.reset" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceCreatedCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleInvoiceCreatedCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleInvoiceCreatedCreateRequest() (NotificationRuleInvoiceCreatedCreateRequest, error) { + var body NotificationRuleInvoiceCreatedCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceCreatedCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleInvoiceCreatedCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleInvoiceCreatedCreateRequest(v NotificationRuleInvoiceCreatedCreateRequest) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceCreatedCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleInvoiceCreatedCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleInvoiceCreatedCreateRequest(v NotificationRuleInvoiceCreatedCreateRequest) error { + v.Type = "invoice.created" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsNotificationRuleInvoiceUpdatedCreateRequest returns the union data inside the NotificationRuleCreateRequest as a NotificationRuleInvoiceUpdatedCreateRequest +func (t NotificationRuleCreateRequest) AsNotificationRuleInvoiceUpdatedCreateRequest() (NotificationRuleInvoiceUpdatedCreateRequest, error) { + var body NotificationRuleInvoiceUpdatedCreateRequest + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromNotificationRuleInvoiceUpdatedCreateRequest overwrites any union data inside the NotificationRuleCreateRequest as the provided NotificationRuleInvoiceUpdatedCreateRequest +func (t *NotificationRuleCreateRequest) FromNotificationRuleInvoiceUpdatedCreateRequest(v NotificationRuleInvoiceUpdatedCreateRequest) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeNotificationRuleInvoiceUpdatedCreateRequest performs a merge with any union data inside the NotificationRuleCreateRequest, using the provided NotificationRuleInvoiceUpdatedCreateRequest +func (t *NotificationRuleCreateRequest) MergeNotificationRuleInvoiceUpdatedCreateRequest(v NotificationRuleInvoiceUpdatedCreateRequest) error { + v.Type = "invoice.updated" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t NotificationRuleCreateRequest) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t NotificationRuleCreateRequest) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "entitlements.balance.threshold": + return t.AsNotificationRuleBalanceThresholdCreateRequest() + case "entitlements.reset": + return t.AsNotificationRuleEntitlementResetCreateRequest() + case "invoice.created": + return t.AsNotificationRuleInvoiceCreatedCreateRequest() + case "invoice.updated": + return t.AsNotificationRuleInvoiceUpdatedCreateRequest() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t NotificationRuleCreateRequest) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *NotificationRuleCreateRequest) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsPaymentTermInstant returns the union data inside the PaymentTerms as a PaymentTermInstant +func (t PaymentTerms) AsPaymentTermInstant() (PaymentTermInstant, error) { + var body PaymentTermInstant + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPaymentTermInstant overwrites any union data inside the PaymentTerms as the provided PaymentTermInstant +func (t *PaymentTerms) FromPaymentTermInstant(v PaymentTermInstant) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePaymentTermInstant performs a merge with any union data inside the PaymentTerms, using the provided PaymentTermInstant +func (t *PaymentTerms) MergePaymentTermInstant(v PaymentTermInstant) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPaymentTermDueDate returns the union data inside the PaymentTerms as a PaymentTermDueDate +func (t PaymentTerms) AsPaymentTermDueDate() (PaymentTermDueDate, error) { + var body PaymentTermDueDate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPaymentTermDueDate overwrites any union data inside the PaymentTerms as the provided PaymentTermDueDate +func (t *PaymentTerms) FromPaymentTermDueDate(v PaymentTermDueDate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePaymentTermDueDate performs a merge with any union data inside the PaymentTerms, using the provided PaymentTermDueDate +func (t *PaymentTerms) MergePaymentTermDueDate(v PaymentTermDueDate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t PaymentTerms) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *PaymentTerms) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsRateCardFlatFee returns the union data inside the RateCard as a RateCardFlatFee +func (t RateCard) AsRateCardFlatFee() (RateCardFlatFee, error) { + var body RateCardFlatFee + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardFlatFee overwrites any union data inside the RateCard as the provided RateCardFlatFee +func (t *RateCard) FromRateCardFlatFee(v RateCardFlatFee) error { + v.Type = "flat_fee" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardFlatFee performs a merge with any union data inside the RateCard, using the provided RateCardFlatFee +func (t *RateCard) MergeRateCardFlatFee(v RateCardFlatFee) error { + v.Type = "flat_fee" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRateCardUsageBased returns the union data inside the RateCard as a RateCardUsageBased +func (t RateCard) AsRateCardUsageBased() (RateCardUsageBased, error) { + var body RateCardUsageBased + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardUsageBased overwrites any union data inside the RateCard as the provided RateCardUsageBased +func (t *RateCard) FromRateCardUsageBased(v RateCardUsageBased) error { + v.Type = "usage_based" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardUsageBased performs a merge with any union data inside the RateCard, using the provided RateCardUsageBased +func (t *RateCard) MergeRateCardUsageBased(v RateCardUsageBased) error { + v.Type = "usage_based" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RateCard) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t RateCard) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "flat_fee": + return t.AsRateCardFlatFee() + case "usage_based": + return t.AsRateCardUsageBased() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t RateCard) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RateCard) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsRateCardMeteredEntitlement returns the union data inside the RateCardEntitlement as a RateCardMeteredEntitlement +func (t RateCardEntitlement) AsRateCardMeteredEntitlement() (RateCardMeteredEntitlement, error) { + var body RateCardMeteredEntitlement + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardMeteredEntitlement overwrites any union data inside the RateCardEntitlement as the provided RateCardMeteredEntitlement +func (t *RateCardEntitlement) FromRateCardMeteredEntitlement(v RateCardMeteredEntitlement) error { + v.Type = "metered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardMeteredEntitlement performs a merge with any union data inside the RateCardEntitlement, using the provided RateCardMeteredEntitlement +func (t *RateCardEntitlement) MergeRateCardMeteredEntitlement(v RateCardMeteredEntitlement) error { + v.Type = "metered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRateCardStaticEntitlement returns the union data inside the RateCardEntitlement as a RateCardStaticEntitlement +func (t RateCardEntitlement) AsRateCardStaticEntitlement() (RateCardStaticEntitlement, error) { + var body RateCardStaticEntitlement + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardStaticEntitlement overwrites any union data inside the RateCardEntitlement as the provided RateCardStaticEntitlement +func (t *RateCardEntitlement) FromRateCardStaticEntitlement(v RateCardStaticEntitlement) error { + v.Type = "static" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardStaticEntitlement performs a merge with any union data inside the RateCardEntitlement, using the provided RateCardStaticEntitlement +func (t *RateCardEntitlement) MergeRateCardStaticEntitlement(v RateCardStaticEntitlement) error { + v.Type = "static" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRateCardBooleanEntitlement returns the union data inside the RateCardEntitlement as a RateCardBooleanEntitlement +func (t RateCardEntitlement) AsRateCardBooleanEntitlement() (RateCardBooleanEntitlement, error) { + var body RateCardBooleanEntitlement + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRateCardBooleanEntitlement overwrites any union data inside the RateCardEntitlement as the provided RateCardBooleanEntitlement +func (t *RateCardEntitlement) FromRateCardBooleanEntitlement(v RateCardBooleanEntitlement) error { + v.Type = "boolean" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRateCardBooleanEntitlement performs a merge with any union data inside the RateCardEntitlement, using the provided RateCardBooleanEntitlement +func (t *RateCardEntitlement) MergeRateCardBooleanEntitlement(v RateCardBooleanEntitlement) error { + v.Type = "boolean" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RateCardEntitlement) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t RateCardEntitlement) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "boolean": + return t.AsRateCardBooleanEntitlement() + case "metered": + return t.AsRateCardMeteredEntitlement() + case "static": + return t.AsRateCardStaticEntitlement() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t RateCardEntitlement) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RateCardEntitlement) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsFlatPriceWithPaymentTerm returns the union data inside the RateCardUsageBasedPrice as a FlatPriceWithPaymentTerm +func (t RateCardUsageBasedPrice) AsFlatPriceWithPaymentTerm() (FlatPriceWithPaymentTerm, error) { + var body FlatPriceWithPaymentTerm + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromFlatPriceWithPaymentTerm overwrites any union data inside the RateCardUsageBasedPrice as the provided FlatPriceWithPaymentTerm +func (t *RateCardUsageBasedPrice) FromFlatPriceWithPaymentTerm(v FlatPriceWithPaymentTerm) error { + v.Type = "flat" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeFlatPriceWithPaymentTerm performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided FlatPriceWithPaymentTerm +func (t *RateCardUsageBasedPrice) MergeFlatPriceWithPaymentTerm(v FlatPriceWithPaymentTerm) error { + v.Type = "flat" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsUnitPriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a UnitPriceWithCommitments +func (t RateCardUsageBasedPrice) AsUnitPriceWithCommitments() (UnitPriceWithCommitments, error) { + var body UnitPriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromUnitPriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided UnitPriceWithCommitments +func (t *RateCardUsageBasedPrice) FromUnitPriceWithCommitments(v UnitPriceWithCommitments) error { + v.Type = "unit" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeUnitPriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided UnitPriceWithCommitments +func (t *RateCardUsageBasedPrice) MergeUnitPriceWithCommitments(v UnitPriceWithCommitments) error { + v.Type = "unit" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsTieredPriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a TieredPriceWithCommitments +func (t RateCardUsageBasedPrice) AsTieredPriceWithCommitments() (TieredPriceWithCommitments, error) { + var body TieredPriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromTieredPriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided TieredPriceWithCommitments +func (t *RateCardUsageBasedPrice) FromTieredPriceWithCommitments(v TieredPriceWithCommitments) error { + v.Type = "tiered" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeTieredPriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided TieredPriceWithCommitments +func (t *RateCardUsageBasedPrice) MergeTieredPriceWithCommitments(v TieredPriceWithCommitments) error { + v.Type = "tiered" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsDynamicPriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a DynamicPriceWithCommitments +func (t RateCardUsageBasedPrice) AsDynamicPriceWithCommitments() (DynamicPriceWithCommitments, error) { + var body DynamicPriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromDynamicPriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided DynamicPriceWithCommitments +func (t *RateCardUsageBasedPrice) FromDynamicPriceWithCommitments(v DynamicPriceWithCommitments) error { + v.Type = "dynamic" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeDynamicPriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided DynamicPriceWithCommitments +func (t *RateCardUsageBasedPrice) MergeDynamicPriceWithCommitments(v DynamicPriceWithCommitments) error { + v.Type = "dynamic" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsPackagePriceWithCommitments returns the union data inside the RateCardUsageBasedPrice as a PackagePriceWithCommitments +func (t RateCardUsageBasedPrice) AsPackagePriceWithCommitments() (PackagePriceWithCommitments, error) { + var body PackagePriceWithCommitments + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPackagePriceWithCommitments overwrites any union data inside the RateCardUsageBasedPrice as the provided PackagePriceWithCommitments +func (t *RateCardUsageBasedPrice) FromPackagePriceWithCommitments(v PackagePriceWithCommitments) error { + v.Type = "package" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePackagePriceWithCommitments performs a merge with any union data inside the RateCardUsageBasedPrice, using the provided PackagePriceWithCommitments +func (t *RateCardUsageBasedPrice) MergePackagePriceWithCommitments(v PackagePriceWithCommitments) error { + v.Type = "package" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RateCardUsageBasedPrice) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t RateCardUsageBasedPrice) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "dynamic": + return t.AsDynamicPriceWithCommitments() + case "flat": + return t.AsFlatPriceWithPaymentTerm() + case "package": + return t.AsPackagePriceWithCommitments() + case "tiered": + return t.AsTieredPriceWithCommitments() + case "unit": + return t.AsUnitPriceWithCommitments() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t RateCardUsageBasedPrice) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RateCardUsageBasedPrice) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsRecurringPeriodInterval0 returns the union data inside the RecurringPeriodInterval as a RecurringPeriodInterval0 +func (t RecurringPeriodInterval) AsRecurringPeriodInterval0() (RecurringPeriodInterval0, error) { + var body RecurringPeriodInterval0 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRecurringPeriodInterval0 overwrites any union data inside the RecurringPeriodInterval as the provided RecurringPeriodInterval0 +func (t *RecurringPeriodInterval) FromRecurringPeriodInterval0(v RecurringPeriodInterval0) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRecurringPeriodInterval0 performs a merge with any union data inside the RecurringPeriodInterval, using the provided RecurringPeriodInterval0 +func (t *RecurringPeriodInterval) MergeRecurringPeriodInterval0(v RecurringPeriodInterval0) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsRecurringPeriodIntervalEnum returns the union data inside the RecurringPeriodInterval as a RecurringPeriodIntervalEnum +func (t RecurringPeriodInterval) AsRecurringPeriodIntervalEnum() (RecurringPeriodIntervalEnum, error) { + var body RecurringPeriodIntervalEnum + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromRecurringPeriodIntervalEnum overwrites any union data inside the RecurringPeriodInterval as the provided RecurringPeriodIntervalEnum +func (t *RecurringPeriodInterval) FromRecurringPeriodIntervalEnum(v RecurringPeriodIntervalEnum) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeRecurringPeriodIntervalEnum performs a merge with any union data inside the RecurringPeriodInterval, using the provided RecurringPeriodIntervalEnum +func (t *RecurringPeriodInterval) MergeRecurringPeriodIntervalEnum(v RecurringPeriodIntervalEnum) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t RecurringPeriodInterval) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *RecurringPeriodInterval) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsPlanSubscriptionChange returns the union data inside the SubscriptionChange as a PlanSubscriptionChange +func (t SubscriptionChange) AsPlanSubscriptionChange() (PlanSubscriptionChange, error) { + var body PlanSubscriptionChange + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPlanSubscriptionChange overwrites any union data inside the SubscriptionChange as the provided PlanSubscriptionChange +func (t *SubscriptionChange) FromPlanSubscriptionChange(v PlanSubscriptionChange) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePlanSubscriptionChange performs a merge with any union data inside the SubscriptionChange, using the provided PlanSubscriptionChange +func (t *SubscriptionChange) MergePlanSubscriptionChange(v PlanSubscriptionChange) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomSubscriptionChange returns the union data inside the SubscriptionChange as a CustomSubscriptionChange +func (t SubscriptionChange) AsCustomSubscriptionChange() (CustomSubscriptionChange, error) { + var body CustomSubscriptionChange + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomSubscriptionChange overwrites any union data inside the SubscriptionChange as the provided CustomSubscriptionChange +func (t *SubscriptionChange) FromCustomSubscriptionChange(v CustomSubscriptionChange) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomSubscriptionChange performs a merge with any union data inside the SubscriptionChange, using the provided CustomSubscriptionChange +func (t *SubscriptionChange) MergeCustomSubscriptionChange(v CustomSubscriptionChange) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionChange) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionChange) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsPlanSubscriptionCreate returns the union data inside the SubscriptionCreate as a PlanSubscriptionCreate +func (t SubscriptionCreate) AsPlanSubscriptionCreate() (PlanSubscriptionCreate, error) { + var body PlanSubscriptionCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromPlanSubscriptionCreate overwrites any union data inside the SubscriptionCreate as the provided PlanSubscriptionCreate +func (t *SubscriptionCreate) FromPlanSubscriptionCreate(v PlanSubscriptionCreate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergePlanSubscriptionCreate performs a merge with any union data inside the SubscriptionCreate, using the provided PlanSubscriptionCreate +func (t *SubscriptionCreate) MergePlanSubscriptionCreate(v PlanSubscriptionCreate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsCustomSubscriptionCreate returns the union data inside the SubscriptionCreate as a CustomSubscriptionCreate +func (t SubscriptionCreate) AsCustomSubscriptionCreate() (CustomSubscriptionCreate, error) { + var body CustomSubscriptionCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromCustomSubscriptionCreate overwrites any union data inside the SubscriptionCreate as the provided CustomSubscriptionCreate +func (t *SubscriptionCreate) FromCustomSubscriptionCreate(v CustomSubscriptionCreate) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeCustomSubscriptionCreate performs a merge with any union data inside the SubscriptionCreate, using the provided CustomSubscriptionCreate +func (t *SubscriptionCreate) MergeCustomSubscriptionCreate(v CustomSubscriptionCreate) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionCreate) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionCreate) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsEditSubscriptionAddItem returns the union data inside the SubscriptionEditOperation as a EditSubscriptionAddItem +func (t SubscriptionEditOperation) AsEditSubscriptionAddItem() (EditSubscriptionAddItem, error) { + var body EditSubscriptionAddItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionAddItem overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionAddItem +func (t *SubscriptionEditOperation) FromEditSubscriptionAddItem(v EditSubscriptionAddItem) error { + v.Op = "add_item" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionAddItem performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionAddItem +func (t *SubscriptionEditOperation) MergeEditSubscriptionAddItem(v EditSubscriptionAddItem) error { + v.Op = "add_item" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionRemoveItem returns the union data inside the SubscriptionEditOperation as a EditSubscriptionRemoveItem +func (t SubscriptionEditOperation) AsEditSubscriptionRemoveItem() (EditSubscriptionRemoveItem, error) { + var body EditSubscriptionRemoveItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionRemoveItem overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionRemoveItem +func (t *SubscriptionEditOperation) FromEditSubscriptionRemoveItem(v EditSubscriptionRemoveItem) error { + v.Op = "remove_item" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionRemoveItem performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionRemoveItem +func (t *SubscriptionEditOperation) MergeEditSubscriptionRemoveItem(v EditSubscriptionRemoveItem) error { + v.Op = "remove_item" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionAddPhase returns the union data inside the SubscriptionEditOperation as a EditSubscriptionAddPhase +func (t SubscriptionEditOperation) AsEditSubscriptionAddPhase() (EditSubscriptionAddPhase, error) { + var body EditSubscriptionAddPhase + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionAddPhase overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionAddPhase +func (t *SubscriptionEditOperation) FromEditSubscriptionAddPhase(v EditSubscriptionAddPhase) error { + v.Op = "add_phase" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionAddPhase performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionAddPhase +func (t *SubscriptionEditOperation) MergeEditSubscriptionAddPhase(v EditSubscriptionAddPhase) error { + v.Op = "add_phase" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionRemovePhase returns the union data inside the SubscriptionEditOperation as a EditSubscriptionRemovePhase +func (t SubscriptionEditOperation) AsEditSubscriptionRemovePhase() (EditSubscriptionRemovePhase, error) { + var body EditSubscriptionRemovePhase + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionRemovePhase overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionRemovePhase +func (t *SubscriptionEditOperation) FromEditSubscriptionRemovePhase(v EditSubscriptionRemovePhase) error { + v.Op = "remove_phase" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionRemovePhase performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionRemovePhase +func (t *SubscriptionEditOperation) MergeEditSubscriptionRemovePhase(v EditSubscriptionRemovePhase) error { + v.Op = "remove_phase" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionStretchPhase returns the union data inside the SubscriptionEditOperation as a EditSubscriptionStretchPhase +func (t SubscriptionEditOperation) AsEditSubscriptionStretchPhase() (EditSubscriptionStretchPhase, error) { + var body EditSubscriptionStretchPhase + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionStretchPhase overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionStretchPhase +func (t *SubscriptionEditOperation) FromEditSubscriptionStretchPhase(v EditSubscriptionStretchPhase) error { + v.Op = "stretch_phase" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionStretchPhase performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionStretchPhase +func (t *SubscriptionEditOperation) MergeEditSubscriptionStretchPhase(v EditSubscriptionStretchPhase) error { + v.Op = "stretch_phase" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsEditSubscriptionUnscheduleEdit returns the union data inside the SubscriptionEditOperation as a EditSubscriptionUnscheduleEdit +func (t SubscriptionEditOperation) AsEditSubscriptionUnscheduleEdit() (EditSubscriptionUnscheduleEdit, error) { + var body EditSubscriptionUnscheduleEdit + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromEditSubscriptionUnscheduleEdit overwrites any union data inside the SubscriptionEditOperation as the provided EditSubscriptionUnscheduleEdit +func (t *SubscriptionEditOperation) FromEditSubscriptionUnscheduleEdit(v EditSubscriptionUnscheduleEdit) error { + v.Op = "unschedule_edit" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeEditSubscriptionUnscheduleEdit performs a merge with any union data inside the SubscriptionEditOperation, using the provided EditSubscriptionUnscheduleEdit +func (t *SubscriptionEditOperation) MergeEditSubscriptionUnscheduleEdit(v EditSubscriptionUnscheduleEdit) error { + v.Op = "unschedule_edit" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionEditOperation) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"op"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t SubscriptionEditOperation) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "add_item": + return t.AsEditSubscriptionAddItem() + case "add_phase": + return t.AsEditSubscriptionAddPhase() + case "remove_item": + return t.AsEditSubscriptionRemoveItem() + case "remove_phase": + return t.AsEditSubscriptionRemovePhase() + case "stretch_phase": + return t.AsEditSubscriptionStretchPhase() + case "unschedule_edit": + return t.AsEditSubscriptionUnscheduleEdit() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t SubscriptionEditOperation) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionEditOperation) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsSubscriptionTimingEnum returns the union data inside the SubscriptionTiming as a SubscriptionTimingEnum +func (t SubscriptionTiming) AsSubscriptionTimingEnum() (SubscriptionTimingEnum, error) { + var body SubscriptionTimingEnum + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSubscriptionTimingEnum overwrites any union data inside the SubscriptionTiming as the provided SubscriptionTimingEnum +func (t *SubscriptionTiming) FromSubscriptionTimingEnum(v SubscriptionTimingEnum) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSubscriptionTimingEnum performs a merge with any union data inside the SubscriptionTiming, using the provided SubscriptionTimingEnum +func (t *SubscriptionTiming) MergeSubscriptionTimingEnum(v SubscriptionTimingEnum) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsSubscriptionTiming1 returns the union data inside the SubscriptionTiming as a SubscriptionTiming1 +func (t SubscriptionTiming) AsSubscriptionTiming1() (SubscriptionTiming1, error) { + var body SubscriptionTiming1 + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromSubscriptionTiming1 overwrites any union data inside the SubscriptionTiming as the provided SubscriptionTiming1 +func (t *SubscriptionTiming) FromSubscriptionTiming1(v SubscriptionTiming1) error { + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeSubscriptionTiming1 performs a merge with any union data inside the SubscriptionTiming, using the provided SubscriptionTiming1 +func (t *SubscriptionTiming) MergeSubscriptionTiming1(v SubscriptionTiming1) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t SubscriptionTiming) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *SubscriptionTiming) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsVoidInvoiceLineDiscardAction returns the union data inside the VoidInvoiceLineActionCreate as a VoidInvoiceLineDiscardAction +func (t VoidInvoiceLineActionCreate) AsVoidInvoiceLineDiscardAction() (VoidInvoiceLineDiscardAction, error) { + var body VoidInvoiceLineDiscardAction + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLineDiscardAction overwrites any union data inside the VoidInvoiceLineActionCreate as the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreate) FromVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLineDiscardAction performs a merge with any union data inside the VoidInvoiceLineActionCreate, using the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreate) MergeVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVoidInvoiceLinePendingActionCreate returns the union data inside the VoidInvoiceLineActionCreate as a VoidInvoiceLinePendingActionCreate +func (t VoidInvoiceLineActionCreate) AsVoidInvoiceLinePendingActionCreate() (VoidInvoiceLinePendingActionCreate, error) { + var body VoidInvoiceLinePendingActionCreate + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLinePendingActionCreate overwrites any union data inside the VoidInvoiceLineActionCreate as the provided VoidInvoiceLinePendingActionCreate +func (t *VoidInvoiceLineActionCreate) FromVoidInvoiceLinePendingActionCreate(v VoidInvoiceLinePendingActionCreate) error { + v.Type = "pending" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLinePendingActionCreate performs a merge with any union data inside the VoidInvoiceLineActionCreate, using the provided VoidInvoiceLinePendingActionCreate +func (t *VoidInvoiceLineActionCreate) MergeVoidInvoiceLinePendingActionCreate(v VoidInvoiceLinePendingActionCreate) error { + v.Type = "pending" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t VoidInvoiceLineActionCreate) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t VoidInvoiceLineActionCreate) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "discard": + return t.AsVoidInvoiceLineDiscardAction() + case "pending": + return t.AsVoidInvoiceLinePendingActionCreate() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t VoidInvoiceLineActionCreate) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *VoidInvoiceLineActionCreate) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// AsVoidInvoiceLineDiscardAction returns the union data inside the VoidInvoiceLineActionCreateItem as a VoidInvoiceLineDiscardAction +func (t VoidInvoiceLineActionCreateItem) AsVoidInvoiceLineDiscardAction() (VoidInvoiceLineDiscardAction, error) { + var body VoidInvoiceLineDiscardAction + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLineDiscardAction overwrites any union data inside the VoidInvoiceLineActionCreateItem as the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreateItem) FromVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLineDiscardAction performs a merge with any union data inside the VoidInvoiceLineActionCreateItem, using the provided VoidInvoiceLineDiscardAction +func (t *VoidInvoiceLineActionCreateItem) MergeVoidInvoiceLineDiscardAction(v VoidInvoiceLineDiscardAction) error { + v.Type = "discard" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +// AsVoidInvoiceLinePendingActionCreateItem returns the union data inside the VoidInvoiceLineActionCreateItem as a VoidInvoiceLinePendingActionCreateItem +func (t VoidInvoiceLineActionCreateItem) AsVoidInvoiceLinePendingActionCreateItem() (VoidInvoiceLinePendingActionCreateItem, error) { + var body VoidInvoiceLinePendingActionCreateItem + err := json.Unmarshal(t.union, &body) + return body, err +} + +// FromVoidInvoiceLinePendingActionCreateItem overwrites any union data inside the VoidInvoiceLineActionCreateItem as the provided VoidInvoiceLinePendingActionCreateItem +func (t *VoidInvoiceLineActionCreateItem) FromVoidInvoiceLinePendingActionCreateItem(v VoidInvoiceLinePendingActionCreateItem) error { + v.Type = "pending" + b, err := json.Marshal(v) + t.union = b + return err +} + +// MergeVoidInvoiceLinePendingActionCreateItem performs a merge with any union data inside the VoidInvoiceLineActionCreateItem, using the provided VoidInvoiceLinePendingActionCreateItem +func (t *VoidInvoiceLineActionCreateItem) MergeVoidInvoiceLinePendingActionCreateItem(v VoidInvoiceLinePendingActionCreateItem) error { + v.Type = "pending" + b, err := json.Marshal(v) + if err != nil { + return err + } + + merged, err := runtime.JSONMerge(t.union, b) + t.union = merged + return err +} + +func (t VoidInvoiceLineActionCreateItem) Discriminator() (string, error) { + var discriminator struct { + Discriminator string `json:"type"` + } + err := json.Unmarshal(t.union, &discriminator) + return discriminator.Discriminator, err +} + +func (t VoidInvoiceLineActionCreateItem) ValueByDiscriminator() (interface{}, error) { + discriminator, err := t.Discriminator() + if err != nil { + return nil, err + } + switch discriminator { + case "discard": + return t.AsVoidInvoiceLineDiscardAction() + case "pending": + return t.AsVoidInvoiceLinePendingActionCreateItem() + default: + return nil, errors.New("unknown discriminator value: " + discriminator) + } +} + +func (t VoidInvoiceLineActionCreateItem) MarshalJSON() ([]byte, error) { + b, err := t.union.MarshalJSON() + return b, err +} + +func (t *VoidInvoiceLineActionCreateItem) UnmarshalJSON(b []byte) error { + err := t.union.UnmarshalJSON(b) + return err +} + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + // ListAddons request + ListAddons(ctx context.Context, params *ListAddonsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateAddonWithBody request with any body + CreateAddonWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateAddon(ctx context.Context, body CreateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteAddon request + DeleteAddon(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetAddon request + GetAddon(ctx context.Context, addonId string, params *GetAddonParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateAddonWithBody request with any body + UpdateAddonWithBody(ctx context.Context, addonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateAddon(ctx context.Context, addonId string, body UpdateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ArchiveAddon request + ArchiveAddon(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PublishAddon request + PublishAddon(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListApps request + ListApps(ctx context.Context, params *ListAppsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AppCustomInvoicingDraftSynchronizedWithBody request with any body + AppCustomInvoicingDraftSynchronizedWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + AppCustomInvoicingDraftSynchronized(ctx context.Context, invoiceId string, body AppCustomInvoicingDraftSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AppCustomInvoicingIssuingSynchronizedWithBody request with any body + AppCustomInvoicingIssuingSynchronizedWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + AppCustomInvoicingIssuingSynchronized(ctx context.Context, invoiceId string, body AppCustomInvoicingIssuingSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AppCustomInvoicingUpdatePaymentStatusWithBody request with any body + AppCustomInvoicingUpdatePaymentStatusWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + AppCustomInvoicingUpdatePaymentStatus(ctx context.Context, invoiceId string, body AppCustomInvoicingUpdatePaymentStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UninstallApp request + UninstallApp(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetApp request + GetApp(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateAppWithBody request with any body + UpdateAppWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateApp(ctx context.Context, id string, body UpdateAppJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateStripeAPIKeyWithBody request with any body + UpdateStripeAPIKeyWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateStripeAPIKey(ctx context.Context, id string, body UpdateStripeAPIKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AppStripeWebhookWithBody request with any body + AppStripeWebhookWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + AppStripeWebhook(ctx context.Context, id string, body AppStripeWebhookJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListBillingProfileCustomerOverrides request + ListBillingProfileCustomerOverrides(ctx context.Context, params *ListBillingProfileCustomerOverridesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteBillingProfileCustomerOverride request + DeleteBillingProfileCustomerOverride(ctx context.Context, customerId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetBillingProfileCustomerOverride request + GetBillingProfileCustomerOverride(ctx context.Context, customerId string, params *GetBillingProfileCustomerOverrideParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpsertBillingProfileCustomerOverrideWithBody request with any body + UpsertBillingProfileCustomerOverrideWithBody(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpsertBillingProfileCustomerOverride(ctx context.Context, customerId string, body UpsertBillingProfileCustomerOverrideJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreatePendingInvoiceLineWithBody request with any body + CreatePendingInvoiceLineWithBody(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreatePendingInvoiceLine(ctx context.Context, customerId string, body CreatePendingInvoiceLineJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SimulateInvoiceWithBody request with any body + SimulateInvoiceWithBody(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + SimulateInvoice(ctx context.Context, customerId string, body SimulateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListInvoices request + ListInvoices(ctx context.Context, params *ListInvoicesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // InvoicePendingLinesActionWithBody request with any body + InvoicePendingLinesActionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + InvoicePendingLinesAction(ctx context.Context, body InvoicePendingLinesActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteInvoice request + DeleteInvoice(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetInvoice request + GetInvoice(ctx context.Context, invoiceId string, params *GetInvoiceParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateInvoiceWithBody request with any body + UpdateInvoiceWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateInvoice(ctx context.Context, invoiceId string, body UpdateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // AdvanceInvoiceAction request + AdvanceInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ApproveInvoiceAction request + ApproveInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RetryInvoiceAction request + RetryInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SnapshotQuantitiesInvoiceAction request + SnapshotQuantitiesInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RecalculateInvoiceTaxAction request + RecalculateInvoiceTaxAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // VoidInvoiceActionWithBody request with any body + VoidInvoiceActionWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + VoidInvoiceAction(ctx context.Context, invoiceId string, body VoidInvoiceActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListBillingProfiles request + ListBillingProfiles(ctx context.Context, params *ListBillingProfilesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateBillingProfileWithBody request with any body + CreateBillingProfileWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateBillingProfile(ctx context.Context, body CreateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteBillingProfile request + DeleteBillingProfile(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetBillingProfile request + GetBillingProfile(ctx context.Context, id string, params *GetBillingProfileParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateBillingProfileWithBody request with any body + UpdateBillingProfileWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateBillingProfile(ctx context.Context, id string, body UpdateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListCustomers request + ListCustomers(ctx context.Context, params *ListCustomersParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateCustomerWithBody request with any body + CreateCustomerWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateCustomer(ctx context.Context, body CreateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteCustomer request + DeleteCustomer(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomer request + GetCustomer(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *GetCustomerParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateCustomerWithBody request with any body + UpdateCustomerWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateCustomer(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpdateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomerAccess request + GetCustomerAccess(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListCustomerAppData request + ListCustomerAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerAppDataParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpsertCustomerAppDataWithBody request with any body + UpsertCustomerAppDataWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpsertCustomerAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteCustomerAppData request + DeleteCustomerAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, appId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomerEntitlementValue request + GetCustomerEntitlementValue(ctx context.Context, customerIdOrKey ULIDOrExternalKey, featureKey string, params *GetCustomerEntitlementValueParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomerStripeAppData request + GetCustomerStripeAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpsertCustomerStripeAppDataWithBody request with any body + UpsertCustomerStripeAppDataWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpsertCustomerStripeAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerStripeAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateCustomerStripePortalSessionWithBody request with any body + CreateCustomerStripePortalSessionWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateCustomerStripePortalSession(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerStripePortalSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListCustomerSubscriptions request + ListCustomerSubscriptions(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerSubscriptionsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetDebugMetrics request + GetDebugMetrics(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListEntitlements request + ListEntitlements(ctx context.Context, params *ListEntitlementsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEntitlementById request + GetEntitlementById(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListEvents request + ListEvents(ctx context.Context, params *ListEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // IngestEventsWithBody request with any body + IngestEventsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + IngestEventsWithApplicationCloudeventsPlusJSONBody(ctx context.Context, body IngestEventsApplicationCloudeventsPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + IngestEventsWithApplicationCloudeventsBatchPlusJSONBody(ctx context.Context, body IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + IngestEvents(ctx context.Context, body IngestEventsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListFeatures request + ListFeatures(ctx context.Context, params *ListFeaturesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateFeatureWithBody request with any body + CreateFeatureWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateFeature(ctx context.Context, body CreateFeatureJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteFeature request + DeleteFeature(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetFeature request + GetFeature(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListGrants request + ListGrants(ctx context.Context, params *ListGrantsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // VoidGrant request + VoidGrant(ctx context.Context, grantId string, params *VoidGrantParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListCurrencies request + ListCurrencies(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetProgress request + GetProgress(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMarketplaceListings request + ListMarketplaceListings(ctx context.Context, params *ListMarketplaceListingsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMarketplaceListing request + GetMarketplaceListing(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*http.Response, error) + + // MarketplaceAppInstallWithBody request with any body + MarketplaceAppInstallWithBody(ctx context.Context, pType MarketplaceInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + MarketplaceAppInstall(ctx context.Context, pType MarketplaceInstallRequestType, body MarketplaceAppInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // MarketplaceAppAPIKeyInstallWithBody request with any body + MarketplaceAppAPIKeyInstallWithBody(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + MarketplaceAppAPIKeyInstall(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, body MarketplaceAppAPIKeyInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // MarketplaceOAuth2InstallGetURL request + MarketplaceOAuth2InstallGetURL(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*http.Response, error) + + // MarketplaceOAuth2InstallAuthorize request + MarketplaceOAuth2InstallAuthorize(ctx context.Context, pType MarketplaceOAuth2InstallAuthorizeRequestType, params *MarketplaceOAuth2InstallAuthorizeParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMeters request + ListMeters(ctx context.Context, params *ListMetersParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateMeterWithBody request with any body + CreateMeterWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateMeter(ctx context.Context, body CreateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteMeter request + DeleteMeter(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetMeter request + GetMeter(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateMeterWithBody request with any body + UpdateMeterWithBody(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateMeter(ctx context.Context, meterIdOrSlug string, body UpdateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMeterGroupByValues request + ListMeterGroupByValues(ctx context.Context, meterIdOrSlug string, groupByKey string, params *ListMeterGroupByValuesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // QueryMeter request + QueryMeter(ctx context.Context, meterIdOrSlug string, params *QueryMeterParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // QueryMeterPostWithBody request with any body + QueryMeterPostWithBody(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + QueryMeterPost(ctx context.Context, meterIdOrSlug string, body QueryMeterPostJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListMeterSubjects request + ListMeterSubjects(ctx context.Context, meterIdOrSlug string, params *ListMeterSubjectsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListNotificationChannels request + ListNotificationChannels(ctx context.Context, params *ListNotificationChannelsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateNotificationChannelWithBody request with any body + CreateNotificationChannelWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateNotificationChannel(ctx context.Context, body CreateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteNotificationChannel request + DeleteNotificationChannel(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNotificationChannel request + GetNotificationChannel(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateNotificationChannelWithBody request with any body + UpdateNotificationChannelWithBody(ctx context.Context, channelId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateNotificationChannel(ctx context.Context, channelId string, body UpdateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListNotificationEvents request + ListNotificationEvents(ctx context.Context, params *ListNotificationEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNotificationEvent request + GetNotificationEvent(ctx context.Context, eventId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ResendNotificationEventWithBody request with any body + ResendNotificationEventWithBody(ctx context.Context, eventId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ResendNotificationEvent(ctx context.Context, eventId string, body ResendNotificationEventJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListNotificationRules request + ListNotificationRules(ctx context.Context, params *ListNotificationRulesParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateNotificationRuleWithBody request with any body + CreateNotificationRuleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateNotificationRule(ctx context.Context, body CreateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteNotificationRule request + DeleteNotificationRule(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetNotificationRule request + GetNotificationRule(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateNotificationRuleWithBody request with any body + UpdateNotificationRuleWithBody(ctx context.Context, ruleId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateNotificationRule(ctx context.Context, ruleId string, body UpdateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // TestNotificationRule request + TestNotificationRule(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListPlans request + ListPlans(ctx context.Context, params *ListPlansParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreatePlanWithBody request with any body + CreatePlanWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreatePlan(ctx context.Context, body CreatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // NextPlan request + NextPlan(ctx context.Context, planIdOrKey string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeletePlan request + DeletePlan(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetPlan request + GetPlan(ctx context.Context, planId string, params *GetPlanParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdatePlanWithBody request with any body + UpdatePlanWithBody(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdatePlan(ctx context.Context, planId string, body UpdatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListPlanAddons request + ListPlanAddons(ctx context.Context, planId string, params *ListPlanAddonsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreatePlanAddonWithBody request with any body + CreatePlanAddonWithBody(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreatePlanAddon(ctx context.Context, planId string, body CreatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeletePlanAddon request + DeletePlanAddon(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetPlanAddon request + GetPlanAddon(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdatePlanAddonWithBody request with any body + UpdatePlanAddonWithBody(ctx context.Context, planId string, planAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdatePlanAddon(ctx context.Context, planId string, planAddonId string, body UpdatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ArchivePlan request + ArchivePlan(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // PublishPlan request + PublishPlan(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // QueryPortalMeter request + QueryPortalMeter(ctx context.Context, meterSlug string, params *QueryPortalMeterParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListPortalTokens request + ListPortalTokens(ctx context.Context, params *ListPortalTokensParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreatePortalTokenWithBody request with any body + CreatePortalTokenWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreatePortalToken(ctx context.Context, body CreatePortalTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // InvalidatePortalTokensWithBody request with any body + InvalidatePortalTokensWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + InvalidatePortalTokens(ctx context.Context, body InvalidatePortalTokensJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateStripeCheckoutSessionWithBody request with any body + CreateStripeCheckoutSessionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateStripeCheckoutSession(ctx context.Context, body CreateStripeCheckoutSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListSubjects request + ListSubjects(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpsertSubjectWithBody request with any body + UpsertSubjectWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpsertSubject(ctx context.Context, body UpsertSubjectJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteSubject request + DeleteSubject(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetSubject request + GetSubject(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListSubjectEntitlements request + ListSubjectEntitlements(ctx context.Context, subjectIdOrKey string, params *ListSubjectEntitlementsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateEntitlementWithBody request with any body + CreateEntitlementWithBody(ctx context.Context, subjectIdOrKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateEntitlement(ctx context.Context, subjectIdOrKey string, body CreateEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListEntitlementGrants request + ListEntitlementGrants(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *ListEntitlementGrantsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateGrantWithBody request with any body + CreateGrantWithBody(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateGrant(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body CreateGrantJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // OverrideEntitlementWithBody request with any body + OverrideEntitlementWithBody(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + OverrideEntitlement(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body OverrideEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEntitlementValue request + GetEntitlementValue(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *GetEntitlementValueParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteEntitlement request + DeleteEntitlement(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEntitlement request + GetEntitlement(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEntitlementHistory request + GetEntitlementHistory(ctx context.Context, subjectIdOrKey string, entitlementId string, params *GetEntitlementHistoryParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ResetEntitlementUsageWithBody request with any body + ResetEntitlementUsageWithBody(ctx context.Context, subjectIdOrKey string, entitlementId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ResetEntitlementUsage(ctx context.Context, subjectIdOrKey string, entitlementId string, body ResetEntitlementUsageJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateSubscriptionWithBody request with any body + CreateSubscriptionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateSubscription(ctx context.Context, body CreateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteSubscription request + DeleteSubscription(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetSubscription request + GetSubscription(ctx context.Context, subscriptionId string, params *GetSubscriptionParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // EditSubscriptionWithBody request with any body + EditSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + EditSubscription(ctx context.Context, subscriptionId string, body EditSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListSubscriptionAddons request + ListSubscriptionAddons(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateSubscriptionAddonWithBody request with any body + CreateSubscriptionAddonWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateSubscriptionAddon(ctx context.Context, subscriptionId string, body CreateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetSubscriptionAddon request + GetSubscriptionAddon(ctx context.Context, subscriptionId string, subscriptionAddonId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UpdateSubscriptionAddonWithBody request with any body + UpdateSubscriptionAddonWithBody(ctx context.Context, subscriptionId string, subscriptionAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + UpdateSubscriptionAddon(ctx context.Context, subscriptionId string, subscriptionAddonId string, body UpdateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CancelSubscriptionWithBody request with any body + CancelSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CancelSubscription(ctx context.Context, subscriptionId string, body CancelSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ChangeSubscriptionWithBody request with any body + ChangeSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ChangeSubscription(ctx context.Context, subscriptionId string, body ChangeSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // MigrateSubscriptionWithBody request with any body + MigrateSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + MigrateSubscription(ctx context.Context, subscriptionId string, body MigrateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // RestoreSubscription request + RestoreSubscription(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // UnscheduleCancelation request + UnscheduleCancelation(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListCustomerEntitlementsV2 request + ListCustomerEntitlementsV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerEntitlementsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateCustomerEntitlementV2WithBody request with any body + CreateCustomerEntitlementV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // DeleteCustomerEntitlementV2 request + DeleteCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomerEntitlementV2 request + GetCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListCustomerEntitlementGrantsV2 request + ListCustomerEntitlementGrantsV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *ListCustomerEntitlementGrantsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateCustomerEntitlementGrantV2WithBody request with any body + CreateCustomerEntitlementGrantV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + CreateCustomerEntitlementGrantV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body CreateCustomerEntitlementGrantV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomerEntitlementHistoryV2 request + GetCustomerEntitlementHistoryV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementHistoryV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) + + // OverrideCustomerEntitlementV2WithBody request with any body + OverrideCustomerEntitlementV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + OverrideCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, body OverrideCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ResetCustomerEntitlementUsageV2WithBody request with any body + ResetCustomerEntitlementUsageV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + ResetCustomerEntitlementUsageV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body ResetCustomerEntitlementUsageV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetCustomerEntitlementValueV2 request + GetCustomerEntitlementValueV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementValueV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListEntitlementsV2 request + ListEntitlementsV2(ctx context.Context, params *ListEntitlementsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetEntitlementByIdV2 request + GetEntitlementByIdV2(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListEventsV2 request + ListEventsV2(ctx context.Context, params *ListEventsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListGrantsV2 request + ListGrantsV2(ctx context.Context, params *ListGrantsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +func (c *Client) ListAddons(ctx context.Context, params *ListAddonsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListAddonsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateAddonWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateAddonRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateAddon(ctx context.Context, body CreateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateAddonRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteAddon(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteAddonRequest(c.Server, addonId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetAddon(ctx context.Context, addonId string, params *GetAddonParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetAddonRequest(c.Server, addonId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateAddonWithBody(ctx context.Context, addonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateAddonRequestWithBody(c.Server, addonId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateAddon(ctx context.Context, addonId string, body UpdateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateAddonRequest(c.Server, addonId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ArchiveAddon(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewArchiveAddonRequest(c.Server, addonId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PublishAddon(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPublishAddonRequest(c.Server, addonId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListApps(ctx context.Context, params *ListAppsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListAppsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppCustomInvoicingDraftSynchronizedWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppCustomInvoicingDraftSynchronizedRequestWithBody(c.Server, invoiceId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppCustomInvoicingDraftSynchronized(ctx context.Context, invoiceId string, body AppCustomInvoicingDraftSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppCustomInvoicingDraftSynchronizedRequest(c.Server, invoiceId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppCustomInvoicingIssuingSynchronizedWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppCustomInvoicingIssuingSynchronizedRequestWithBody(c.Server, invoiceId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppCustomInvoicingIssuingSynchronized(ctx context.Context, invoiceId string, body AppCustomInvoicingIssuingSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppCustomInvoicingIssuingSynchronizedRequest(c.Server, invoiceId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppCustomInvoicingUpdatePaymentStatusWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppCustomInvoicingUpdatePaymentStatusRequestWithBody(c.Server, invoiceId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppCustomInvoicingUpdatePaymentStatus(ctx context.Context, invoiceId string, body AppCustomInvoicingUpdatePaymentStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppCustomInvoicingUpdatePaymentStatusRequest(c.Server, invoiceId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UninstallApp(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUninstallAppRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetApp(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetAppRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateAppWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateAppRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateApp(ctx context.Context, id string, body UpdateAppJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateAppRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateStripeAPIKeyWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateStripeAPIKeyRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateStripeAPIKey(ctx context.Context, id string, body UpdateStripeAPIKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateStripeAPIKeyRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppStripeWebhookWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppStripeWebhookRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AppStripeWebhook(ctx context.Context, id string, body AppStripeWebhookJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAppStripeWebhookRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListBillingProfileCustomerOverrides(ctx context.Context, params *ListBillingProfileCustomerOverridesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListBillingProfileCustomerOverridesRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteBillingProfileCustomerOverride(ctx context.Context, customerId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteBillingProfileCustomerOverrideRequest(c.Server, customerId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetBillingProfileCustomerOverride(ctx context.Context, customerId string, params *GetBillingProfileCustomerOverrideParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetBillingProfileCustomerOverrideRequest(c.Server, customerId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertBillingProfileCustomerOverrideWithBody(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertBillingProfileCustomerOverrideRequestWithBody(c.Server, customerId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertBillingProfileCustomerOverride(ctx context.Context, customerId string, body UpsertBillingProfileCustomerOverrideJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertBillingProfileCustomerOverrideRequest(c.Server, customerId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePendingInvoiceLineWithBody(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePendingInvoiceLineRequestWithBody(c.Server, customerId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePendingInvoiceLine(ctx context.Context, customerId string, body CreatePendingInvoiceLineJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePendingInvoiceLineRequest(c.Server, customerId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SimulateInvoiceWithBody(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSimulateInvoiceRequestWithBody(c.Server, customerId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SimulateInvoice(ctx context.Context, customerId string, body SimulateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSimulateInvoiceRequest(c.Server, customerId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListInvoices(ctx context.Context, params *ListInvoicesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListInvoicesRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) InvoicePendingLinesActionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewInvoicePendingLinesActionRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) InvoicePendingLinesAction(ctx context.Context, body InvoicePendingLinesActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewInvoicePendingLinesActionRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteInvoice(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteInvoiceRequest(c.Server, invoiceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetInvoice(ctx context.Context, invoiceId string, params *GetInvoiceParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetInvoiceRequest(c.Server, invoiceId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateInvoiceWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateInvoiceRequestWithBody(c.Server, invoiceId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateInvoice(ctx context.Context, invoiceId string, body UpdateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateInvoiceRequest(c.Server, invoiceId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) AdvanceInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewAdvanceInvoiceActionRequest(c.Server, invoiceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ApproveInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewApproveInvoiceActionRequest(c.Server, invoiceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RetryInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRetryInvoiceActionRequest(c.Server, invoiceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) SnapshotQuantitiesInvoiceAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSnapshotQuantitiesInvoiceActionRequest(c.Server, invoiceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RecalculateInvoiceTaxAction(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRecalculateInvoiceTaxActionRequest(c.Server, invoiceId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) VoidInvoiceActionWithBody(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewVoidInvoiceActionRequestWithBody(c.Server, invoiceId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) VoidInvoiceAction(ctx context.Context, invoiceId string, body VoidInvoiceActionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewVoidInvoiceActionRequest(c.Server, invoiceId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListBillingProfiles(ctx context.Context, params *ListBillingProfilesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListBillingProfilesRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateBillingProfileWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateBillingProfileRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateBillingProfile(ctx context.Context, body CreateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateBillingProfileRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteBillingProfile(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteBillingProfileRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetBillingProfile(ctx context.Context, id string, params *GetBillingProfileParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetBillingProfileRequest(c.Server, id, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateBillingProfileWithBody(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateBillingProfileRequestWithBody(c.Server, id, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateBillingProfile(ctx context.Context, id string, body UpdateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateBillingProfileRequest(c.Server, id, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListCustomers(ctx context.Context, params *ListCustomersParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListCustomersRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomer(ctx context.Context, body CreateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteCustomer(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteCustomerRequest(c.Server, customerIdOrKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomer(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *GetCustomerParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerRequest(c.Server, customerIdOrKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateCustomerWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateCustomerRequestWithBody(c.Server, customerIdOrKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateCustomer(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpdateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateCustomerRequest(c.Server, customerIdOrKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomerAccess(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerAccessRequest(c.Server, customerIdOrKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListCustomerAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerAppDataParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListCustomerAppDataRequest(c.Server, customerIdOrKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertCustomerAppDataWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertCustomerAppDataRequestWithBody(c.Server, customerIdOrKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertCustomerAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertCustomerAppDataRequest(c.Server, customerIdOrKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteCustomerAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, appId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteCustomerAppDataRequest(c.Server, customerIdOrKey, appId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomerEntitlementValue(ctx context.Context, customerIdOrKey ULIDOrExternalKey, featureKey string, params *GetCustomerEntitlementValueParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerEntitlementValueRequest(c.Server, customerIdOrKey, featureKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomerStripeAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerStripeAppDataRequest(c.Server, customerIdOrKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertCustomerStripeAppDataWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertCustomerStripeAppDataRequestWithBody(c.Server, customerIdOrKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertCustomerStripeAppData(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerStripeAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertCustomerStripeAppDataRequest(c.Server, customerIdOrKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerStripePortalSessionWithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerStripePortalSessionRequestWithBody(c.Server, customerIdOrKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerStripePortalSession(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerStripePortalSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerStripePortalSessionRequest(c.Server, customerIdOrKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListCustomerSubscriptions(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerSubscriptionsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListCustomerSubscriptionsRequest(c.Server, customerIdOrKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetDebugMetrics(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetDebugMetricsRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListEntitlements(ctx context.Context, params *ListEntitlementsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListEntitlementsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEntitlementById(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEntitlementByIdRequest(c.Server, entitlementId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListEvents(ctx context.Context, params *ListEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListEventsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) IngestEventsWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewIngestEventsRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) IngestEventsWithApplicationCloudeventsPlusJSONBody(ctx context.Context, body IngestEventsApplicationCloudeventsPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewIngestEventsRequestWithApplicationCloudeventsPlusJSONBody(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) IngestEventsWithApplicationCloudeventsBatchPlusJSONBody(ctx context.Context, body IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewIngestEventsRequestWithApplicationCloudeventsBatchPlusJSONBody(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) IngestEvents(ctx context.Context, body IngestEventsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewIngestEventsRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListFeatures(ctx context.Context, params *ListFeaturesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListFeaturesRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateFeatureWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateFeatureRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateFeature(ctx context.Context, body CreateFeatureJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateFeatureRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteFeature(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteFeatureRequest(c.Server, featureId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetFeature(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetFeatureRequest(c.Server, featureId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListGrants(ctx context.Context, params *ListGrantsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListGrantsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) VoidGrant(ctx context.Context, grantId string, params *VoidGrantParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewVoidGrantRequest(c.Server, grantId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListCurrencies(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListCurrenciesRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetProgress(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetProgressRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMarketplaceListings(ctx context.Context, params *ListMarketplaceListingsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMarketplaceListingsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMarketplaceListing(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMarketplaceListingRequest(c.Server, pType) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarketplaceAppInstallWithBody(ctx context.Context, pType MarketplaceInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarketplaceAppInstallRequestWithBody(c.Server, pType, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarketplaceAppInstall(ctx context.Context, pType MarketplaceInstallRequestType, body MarketplaceAppInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarketplaceAppInstallRequest(c.Server, pType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarketplaceAppAPIKeyInstallWithBody(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarketplaceAppAPIKeyInstallRequestWithBody(c.Server, pType, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarketplaceAppAPIKeyInstall(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, body MarketplaceAppAPIKeyInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarketplaceAppAPIKeyInstallRequest(c.Server, pType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarketplaceOAuth2InstallGetURL(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarketplaceOAuth2InstallGetURLRequest(c.Server, pType) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarketplaceOAuth2InstallAuthorize(ctx context.Context, pType MarketplaceOAuth2InstallAuthorizeRequestType, params *MarketplaceOAuth2InstallAuthorizeParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarketplaceOAuth2InstallAuthorizeRequest(c.Server, pType, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMeters(ctx context.Context, params *ListMetersParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMetersRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateMeterWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateMeterRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateMeter(ctx context.Context, body CreateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateMeterRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteMeter(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteMeterRequest(c.Server, meterIdOrSlug) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetMeter(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetMeterRequest(c.Server, meterIdOrSlug) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateMeterWithBody(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateMeterRequestWithBody(c.Server, meterIdOrSlug, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateMeter(ctx context.Context, meterIdOrSlug string, body UpdateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateMeterRequest(c.Server, meterIdOrSlug, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMeterGroupByValues(ctx context.Context, meterIdOrSlug string, groupByKey string, params *ListMeterGroupByValuesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMeterGroupByValuesRequest(c.Server, meterIdOrSlug, groupByKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) QueryMeter(ctx context.Context, meterIdOrSlug string, params *QueryMeterParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewQueryMeterRequest(c.Server, meterIdOrSlug, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) QueryMeterPostWithBody(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewQueryMeterPostRequestWithBody(c.Server, meterIdOrSlug, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) QueryMeterPost(ctx context.Context, meterIdOrSlug string, body QueryMeterPostJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewQueryMeterPostRequest(c.Server, meterIdOrSlug, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListMeterSubjects(ctx context.Context, meterIdOrSlug string, params *ListMeterSubjectsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListMeterSubjectsRequest(c.Server, meterIdOrSlug, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListNotificationChannels(ctx context.Context, params *ListNotificationChannelsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListNotificationChannelsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateNotificationChannelWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateNotificationChannelRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateNotificationChannel(ctx context.Context, body CreateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateNotificationChannelRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteNotificationChannel(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteNotificationChannelRequest(c.Server, channelId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNotificationChannel(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNotificationChannelRequest(c.Server, channelId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateNotificationChannelWithBody(ctx context.Context, channelId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateNotificationChannelRequestWithBody(c.Server, channelId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateNotificationChannel(ctx context.Context, channelId string, body UpdateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateNotificationChannelRequest(c.Server, channelId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListNotificationEvents(ctx context.Context, params *ListNotificationEventsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListNotificationEventsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNotificationEvent(ctx context.Context, eventId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNotificationEventRequest(c.Server, eventId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResendNotificationEventWithBody(ctx context.Context, eventId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResendNotificationEventRequestWithBody(c.Server, eventId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResendNotificationEvent(ctx context.Context, eventId string, body ResendNotificationEventJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResendNotificationEventRequest(c.Server, eventId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListNotificationRules(ctx context.Context, params *ListNotificationRulesParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListNotificationRulesRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateNotificationRuleWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateNotificationRuleRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateNotificationRule(ctx context.Context, body CreateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateNotificationRuleRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteNotificationRule(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteNotificationRuleRequest(c.Server, ruleId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetNotificationRule(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetNotificationRuleRequest(c.Server, ruleId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateNotificationRuleWithBody(ctx context.Context, ruleId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateNotificationRuleRequestWithBody(c.Server, ruleId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateNotificationRule(ctx context.Context, ruleId string, body UpdateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateNotificationRuleRequest(c.Server, ruleId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) TestNotificationRule(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewTestNotificationRuleRequest(c.Server, ruleId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListPlans(ctx context.Context, params *ListPlansParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListPlansRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePlanWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePlanRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePlan(ctx context.Context, body CreatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePlanRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) NextPlan(ctx context.Context, planIdOrKey string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewNextPlanRequest(c.Server, planIdOrKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeletePlan(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeletePlanRequest(c.Server, planId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetPlan(ctx context.Context, planId string, params *GetPlanParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetPlanRequest(c.Server, planId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdatePlanWithBody(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdatePlanRequestWithBody(c.Server, planId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdatePlan(ctx context.Context, planId string, body UpdatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdatePlanRequest(c.Server, planId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListPlanAddons(ctx context.Context, planId string, params *ListPlanAddonsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListPlanAddonsRequest(c.Server, planId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePlanAddonWithBody(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePlanAddonRequestWithBody(c.Server, planId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePlanAddon(ctx context.Context, planId string, body CreatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePlanAddonRequest(c.Server, planId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeletePlanAddon(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeletePlanAddonRequest(c.Server, planId, planAddonId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetPlanAddon(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetPlanAddonRequest(c.Server, planId, planAddonId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdatePlanAddonWithBody(ctx context.Context, planId string, planAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdatePlanAddonRequestWithBody(c.Server, planId, planAddonId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdatePlanAddon(ctx context.Context, planId string, planAddonId string, body UpdatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdatePlanAddonRequest(c.Server, planId, planAddonId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ArchivePlan(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewArchivePlanRequest(c.Server, planId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) PublishPlan(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewPublishPlanRequest(c.Server, planId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) QueryPortalMeter(ctx context.Context, meterSlug string, params *QueryPortalMeterParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewQueryPortalMeterRequest(c.Server, meterSlug, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListPortalTokens(ctx context.Context, params *ListPortalTokensParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListPortalTokensRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePortalTokenWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePortalTokenRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreatePortalToken(ctx context.Context, body CreatePortalTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreatePortalTokenRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) InvalidatePortalTokensWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewInvalidatePortalTokensRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) InvalidatePortalTokens(ctx context.Context, body InvalidatePortalTokensJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewInvalidatePortalTokensRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateStripeCheckoutSessionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateStripeCheckoutSessionRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateStripeCheckoutSession(ctx context.Context, body CreateStripeCheckoutSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateStripeCheckoutSessionRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListSubjects(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListSubjectsRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertSubjectWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertSubjectRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpsertSubject(ctx context.Context, body UpsertSubjectJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpsertSubjectRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteSubject(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteSubjectRequest(c.Server, subjectIdOrKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetSubject(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSubjectRequest(c.Server, subjectIdOrKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListSubjectEntitlements(ctx context.Context, subjectIdOrKey string, params *ListSubjectEntitlementsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListSubjectEntitlementsRequest(c.Server, subjectIdOrKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateEntitlementWithBody(ctx context.Context, subjectIdOrKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateEntitlementRequestWithBody(c.Server, subjectIdOrKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateEntitlement(ctx context.Context, subjectIdOrKey string, body CreateEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateEntitlementRequest(c.Server, subjectIdOrKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListEntitlementGrants(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *ListEntitlementGrantsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListEntitlementGrantsRequest(c.Server, subjectIdOrKey, entitlementIdOrFeatureKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateGrantWithBody(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateGrantRequestWithBody(c.Server, subjectIdOrKey, entitlementIdOrFeatureKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateGrant(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body CreateGrantJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateGrantRequest(c.Server, subjectIdOrKey, entitlementIdOrFeatureKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) OverrideEntitlementWithBody(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewOverrideEntitlementRequestWithBody(c.Server, subjectIdOrKey, entitlementIdOrFeatureKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) OverrideEntitlement(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body OverrideEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewOverrideEntitlementRequest(c.Server, subjectIdOrKey, entitlementIdOrFeatureKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEntitlementValue(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *GetEntitlementValueParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEntitlementValueRequest(c.Server, subjectIdOrKey, entitlementIdOrFeatureKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteEntitlement(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteEntitlementRequest(c.Server, subjectIdOrKey, entitlementId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEntitlement(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEntitlementRequest(c.Server, subjectIdOrKey, entitlementId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEntitlementHistory(ctx context.Context, subjectIdOrKey string, entitlementId string, params *GetEntitlementHistoryParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEntitlementHistoryRequest(c.Server, subjectIdOrKey, entitlementId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResetEntitlementUsageWithBody(ctx context.Context, subjectIdOrKey string, entitlementId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResetEntitlementUsageRequestWithBody(c.Server, subjectIdOrKey, entitlementId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResetEntitlementUsage(ctx context.Context, subjectIdOrKey string, entitlementId string, body ResetEntitlementUsageJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResetEntitlementUsageRequest(c.Server, subjectIdOrKey, entitlementId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateSubscriptionWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateSubscriptionRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateSubscription(ctx context.Context, body CreateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateSubscriptionRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteSubscription(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteSubscriptionRequest(c.Server, subscriptionId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetSubscription(ctx context.Context, subscriptionId string, params *GetSubscriptionParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSubscriptionRequest(c.Server, subscriptionId, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) EditSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewEditSubscriptionRequestWithBody(c.Server, subscriptionId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) EditSubscription(ctx context.Context, subscriptionId string, body EditSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewEditSubscriptionRequest(c.Server, subscriptionId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListSubscriptionAddons(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListSubscriptionAddonsRequest(c.Server, subscriptionId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateSubscriptionAddonWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateSubscriptionAddonRequestWithBody(c.Server, subscriptionId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateSubscriptionAddon(ctx context.Context, subscriptionId string, body CreateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateSubscriptionAddonRequest(c.Server, subscriptionId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetSubscriptionAddon(ctx context.Context, subscriptionId string, subscriptionAddonId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSubscriptionAddonRequest(c.Server, subscriptionId, subscriptionAddonId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateSubscriptionAddonWithBody(ctx context.Context, subscriptionId string, subscriptionAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateSubscriptionAddonRequestWithBody(c.Server, subscriptionId, subscriptionAddonId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UpdateSubscriptionAddon(ctx context.Context, subscriptionId string, subscriptionAddonId string, body UpdateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUpdateSubscriptionAddonRequest(c.Server, subscriptionId, subscriptionAddonId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CancelSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCancelSubscriptionRequestWithBody(c.Server, subscriptionId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CancelSubscription(ctx context.Context, subscriptionId string, body CancelSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCancelSubscriptionRequest(c.Server, subscriptionId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ChangeSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewChangeSubscriptionRequestWithBody(c.Server, subscriptionId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ChangeSubscription(ctx context.Context, subscriptionId string, body ChangeSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewChangeSubscriptionRequest(c.Server, subscriptionId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MigrateSubscriptionWithBody(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMigrateSubscriptionRequestWithBody(c.Server, subscriptionId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MigrateSubscription(ctx context.Context, subscriptionId string, body MigrateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMigrateSubscriptionRequest(c.Server, subscriptionId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) RestoreSubscription(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewRestoreSubscriptionRequest(c.Server, subscriptionId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) UnscheduleCancelation(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewUnscheduleCancelationRequest(c.Server, subscriptionId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListCustomerEntitlementsV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerEntitlementsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListCustomerEntitlementsV2Request(c.Server, customerIdOrKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerEntitlementV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerEntitlementV2RequestWithBody(c.Server, customerIdOrKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerEntitlementV2Request(c.Server, customerIdOrKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) DeleteCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewDeleteCustomerEntitlementV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerEntitlementV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListCustomerEntitlementGrantsV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *ListCustomerEntitlementGrantsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListCustomerEntitlementGrantsV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerEntitlementGrantV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerEntitlementGrantV2RequestWithBody(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) CreateCustomerEntitlementGrantV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body CreateCustomerEntitlementGrantV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateCustomerEntitlementGrantV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomerEntitlementHistoryV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementHistoryV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerEntitlementHistoryV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) OverrideCustomerEntitlementV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewOverrideCustomerEntitlementV2RequestWithBody(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) OverrideCustomerEntitlementV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, body OverrideCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewOverrideCustomerEntitlementV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResetCustomerEntitlementUsageV2WithBody(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResetCustomerEntitlementUsageV2RequestWithBody(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ResetCustomerEntitlementUsageV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body ResetCustomerEntitlementUsageV2JSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewResetCustomerEntitlementUsageV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetCustomerEntitlementValueV2(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementValueV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetCustomerEntitlementValueV2Request(c.Server, customerIdOrKey, entitlementIdOrFeatureKey, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListEntitlementsV2(ctx context.Context, params *ListEntitlementsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListEntitlementsV2Request(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) GetEntitlementByIdV2(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetEntitlementByIdV2Request(c.Server, entitlementId) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListEventsV2(ctx context.Context, params *ListEventsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListEventsV2Request(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) ListGrantsV2(ctx context.Context, params *ListGrantsV2Params, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListGrantsV2Request(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewListAddonsRequest generates requests for ListAddons +func NewListAddonsRequest(server string, params *ListAddonsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Id != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "id", *params.Id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Key != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "key", *params.Key, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.KeyVersion != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "keyVersion", *params.KeyVersion, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Currency != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "currency", *params.Currency, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateAddonRequest calls the generic CreateAddon builder with application/json body +func NewCreateAddonRequest(server string, body CreateAddonJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateAddonRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateAddonRequestWithBody generates requests for CreateAddon with any type of body +func NewCreateAddonRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteAddonRequest generates requests for DeleteAddon +func NewDeleteAddonRequest(server string, addonId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "addonId", addonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetAddonRequest generates requests for GetAddon +func NewGetAddonRequest(server string, addonId string, params *GetAddonParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "addonId", addonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeLatest != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeLatest", *params.IncludeLatest, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateAddonRequest calls the generic UpdateAddon builder with application/json body +func NewUpdateAddonRequest(server string, addonId string, body UpdateAddonJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateAddonRequestWithBody(server, addonId, "application/json", bodyReader) +} + +// NewUpdateAddonRequestWithBody generates requests for UpdateAddon with any type of body +func NewUpdateAddonRequestWithBody(server string, addonId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "addonId", addonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewArchiveAddonRequest generates requests for ArchiveAddon +func NewArchiveAddonRequest(server string, addonId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "addonId", addonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons/%s/archive", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewPublishAddonRequest generates requests for PublishAddon +func NewPublishAddonRequest(server string, addonId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "addonId", addonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/addons/%s/publish", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListAppsRequest generates requests for ListApps +func NewListAppsRequest(server string, params *ListAppsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewAppCustomInvoicingDraftSynchronizedRequest calls the generic AppCustomInvoicingDraftSynchronized builder with application/json body +func NewAppCustomInvoicingDraftSynchronizedRequest(server string, invoiceId string, body AppCustomInvoicingDraftSynchronizedJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewAppCustomInvoicingDraftSynchronizedRequestWithBody(server, invoiceId, "application/json", bodyReader) +} + +// NewAppCustomInvoicingDraftSynchronizedRequestWithBody generates requests for AppCustomInvoicingDraftSynchronized with any type of body +func NewAppCustomInvoicingDraftSynchronizedRequestWithBody(server string, invoiceId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/custom-invoicing/%s/draft/synchronized", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewAppCustomInvoicingIssuingSynchronizedRequest calls the generic AppCustomInvoicingIssuingSynchronized builder with application/json body +func NewAppCustomInvoicingIssuingSynchronizedRequest(server string, invoiceId string, body AppCustomInvoicingIssuingSynchronizedJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewAppCustomInvoicingIssuingSynchronizedRequestWithBody(server, invoiceId, "application/json", bodyReader) +} + +// NewAppCustomInvoicingIssuingSynchronizedRequestWithBody generates requests for AppCustomInvoicingIssuingSynchronized with any type of body +func NewAppCustomInvoicingIssuingSynchronizedRequestWithBody(server string, invoiceId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/custom-invoicing/%s/issuing/synchronized", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewAppCustomInvoicingUpdatePaymentStatusRequest calls the generic AppCustomInvoicingUpdatePaymentStatus builder with application/json body +func NewAppCustomInvoicingUpdatePaymentStatusRequest(server string, invoiceId string, body AppCustomInvoicingUpdatePaymentStatusJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewAppCustomInvoicingUpdatePaymentStatusRequestWithBody(server, invoiceId, "application/json", bodyReader) +} + +// NewAppCustomInvoicingUpdatePaymentStatusRequestWithBody generates requests for AppCustomInvoicingUpdatePaymentStatus with any type of body +func NewAppCustomInvoicingUpdatePaymentStatusRequestWithBody(server string, invoiceId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/custom-invoicing/%s/payment/status", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewUninstallAppRequest generates requests for UninstallApp +func NewUninstallAppRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetAppRequest generates requests for GetApp +func NewGetAppRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateAppRequest calls the generic UpdateApp builder with application/json body +func NewUpdateAppRequest(server string, id string, body UpdateAppJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateAppRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewUpdateAppRequestWithBody generates requests for UpdateApp with any type of body +func NewUpdateAppRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewUpdateStripeAPIKeyRequest calls the generic UpdateStripeAPIKey builder with application/json body +func NewUpdateStripeAPIKeyRequest(server string, id string, body UpdateStripeAPIKeyJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateStripeAPIKeyRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewUpdateStripeAPIKeyRequestWithBody generates requests for UpdateStripeAPIKey with any type of body +func NewUpdateStripeAPIKeyRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/%s/stripe/api-key", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewAppStripeWebhookRequest calls the generic AppStripeWebhook builder with application/json body +func NewAppStripeWebhookRequest(server string, id string, body AppStripeWebhookJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewAppStripeWebhookRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewAppStripeWebhookRequestWithBody generates requests for AppStripeWebhook with any type of body +func NewAppStripeWebhookRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/apps/%s/stripe/webhook", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListBillingProfileCustomerOverridesRequest generates requests for ListBillingProfileCustomerOverrides +func NewListBillingProfileCustomerOverridesRequest(server string, params *ListBillingProfileCustomerOverridesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/customers") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.BillingProfile != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "billingProfile", *params.BillingProfile, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomersWithoutPinnedProfile != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customersWithoutPinnedProfile", *params.CustomersWithoutPinnedProfile, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeAllCustomers != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "includeAllCustomers", *params.IncludeAllCustomers, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customerId", *params.CustomerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerName != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "customerName", *params.CustomerName, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerKey != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "customerKey", *params.CustomerKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerPrimaryEmail != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "customerPrimaryEmail", *params.CustomerPrimaryEmail, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewDeleteBillingProfileCustomerOverrideRequest generates requests for DeleteBillingProfileCustomerOverride +func NewDeleteBillingProfileCustomerOverrideRequest(server string, customerId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerId", customerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/customers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetBillingProfileCustomerOverrideRequest generates requests for GetBillingProfileCustomerOverride +func NewGetBillingProfileCustomerOverrideRequest(server string, customerId string, params *GetBillingProfileCustomerOverrideParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerId", customerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/customers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpsertBillingProfileCustomerOverrideRequest calls the generic UpsertBillingProfileCustomerOverride builder with application/json body +func NewUpsertBillingProfileCustomerOverrideRequest(server string, customerId string, body UpsertBillingProfileCustomerOverrideJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpsertBillingProfileCustomerOverrideRequestWithBody(server, customerId, "application/json", bodyReader) +} + +// NewUpsertBillingProfileCustomerOverrideRequestWithBody generates requests for UpsertBillingProfileCustomerOverride with any type of body +func NewUpsertBillingProfileCustomerOverrideRequestWithBody(server string, customerId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerId", customerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/customers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCreatePendingInvoiceLineRequest calls the generic CreatePendingInvoiceLine builder with application/json body +func NewCreatePendingInvoiceLineRequest(server string, customerId string, body CreatePendingInvoiceLineJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreatePendingInvoiceLineRequestWithBody(server, customerId, "application/json", bodyReader) +} + +// NewCreatePendingInvoiceLineRequestWithBody generates requests for CreatePendingInvoiceLine with any type of body +func NewCreatePendingInvoiceLineRequestWithBody(server string, customerId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerId", customerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/customers/%s/invoices/pending-lines", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewSimulateInvoiceRequest calls the generic SimulateInvoice builder with application/json body +func NewSimulateInvoiceRequest(server string, customerId string, body SimulateInvoiceJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewSimulateInvoiceRequestWithBody(server, customerId, "application/json", bodyReader) +} + +// NewSimulateInvoiceRequestWithBody generates requests for SimulateInvoice with any type of body +func NewSimulateInvoiceRequestWithBody(server string, customerId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerId", customerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/customers/%s/invoices/simulate", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListInvoicesRequest generates requests for ListInvoices +func NewListInvoicesRequest(server string, params *ListInvoicesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Statuses != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "statuses", *params.Statuses, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.ExtendedStatuses != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "extendedStatuses", *params.ExtendedStatuses, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IssuedAfter != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "issuedAfter", *params.IssuedAfter, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IssuedBefore != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "issuedBefore", *params.IssuedBefore, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PeriodStartAfter != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "periodStartAfter", *params.PeriodStartAfter, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PeriodStartBefore != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "periodStartBefore", *params.PeriodStartBefore, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CreatedAfter != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "createdAfter", *params.CreatedAfter, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CreatedBefore != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "createdBefore", *params.CreatedBefore, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Customers != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customers", *params.Customers, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewInvoicePendingLinesActionRequest calls the generic InvoicePendingLinesAction builder with application/json body +func NewInvoicePendingLinesActionRequest(server string, body InvoicePendingLinesActionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewInvoicePendingLinesActionRequestWithBody(server, "application/json", bodyReader) +} + +// NewInvoicePendingLinesActionRequestWithBody generates requests for InvoicePendingLinesAction with any type of body +func NewInvoicePendingLinesActionRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/invoice") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteInvoiceRequest generates requests for DeleteInvoice +func NewDeleteInvoiceRequest(server string, invoiceId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetInvoiceRequest generates requests for GetInvoice +func NewGetInvoiceRequest(server string, invoiceId string, params *GetInvoiceParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDeletedLines != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeletedLines", *params.IncludeDeletedLines, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateInvoiceRequest calls the generic UpdateInvoice builder with application/json body +func NewUpdateInvoiceRequest(server string, invoiceId string, body UpdateInvoiceJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateInvoiceRequestWithBody(server, invoiceId, "application/json", bodyReader) +} + +// NewUpdateInvoiceRequestWithBody generates requests for UpdateInvoice with any type of body +func NewUpdateInvoiceRequestWithBody(server string, invoiceId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewAdvanceInvoiceActionRequest generates requests for AdvanceInvoiceAction +func NewAdvanceInvoiceActionRequest(server string, invoiceId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s/advance", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewApproveInvoiceActionRequest generates requests for ApproveInvoiceAction +func NewApproveInvoiceActionRequest(server string, invoiceId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s/approve", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRetryInvoiceActionRequest generates requests for RetryInvoiceAction +func NewRetryInvoiceActionRequest(server string, invoiceId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s/retry", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSnapshotQuantitiesInvoiceActionRequest generates requests for SnapshotQuantitiesInvoiceAction +func NewSnapshotQuantitiesInvoiceActionRequest(server string, invoiceId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s/snapshot-quantities", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewRecalculateInvoiceTaxActionRequest generates requests for RecalculateInvoiceTaxAction +func NewRecalculateInvoiceTaxActionRequest(server string, invoiceId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s/taxes/recalculate", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewVoidInvoiceActionRequest calls the generic VoidInvoiceAction builder with application/json body +func NewVoidInvoiceActionRequest(server string, invoiceId string, body VoidInvoiceActionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewVoidInvoiceActionRequestWithBody(server, invoiceId, "application/json", bodyReader) +} + +// NewVoidInvoiceActionRequestWithBody generates requests for VoidInvoiceAction with any type of body +func NewVoidInvoiceActionRequestWithBody(server string, invoiceId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "invoiceId", invoiceId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/invoices/%s/void", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListBillingProfilesRequest generates requests for ListBillingProfiles +func NewListBillingProfilesRequest(server string, params *ListBillingProfilesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/profiles") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeArchived != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeArchived", *params.IncludeArchived, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateBillingProfileRequest calls the generic CreateBillingProfile builder with application/json body +func NewCreateBillingProfileRequest(server string, body CreateBillingProfileJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateBillingProfileRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateBillingProfileRequestWithBody generates requests for CreateBillingProfile with any type of body +func NewCreateBillingProfileRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/profiles") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteBillingProfileRequest generates requests for DeleteBillingProfile +func NewDeleteBillingProfileRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/profiles/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetBillingProfileRequest generates requests for GetBillingProfile +func NewGetBillingProfileRequest(server string, id string, params *GetBillingProfileParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/profiles/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateBillingProfileRequest calls the generic UpdateBillingProfile builder with application/json body +func NewUpdateBillingProfileRequest(server string, id string, body UpdateBillingProfileJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateBillingProfileRequestWithBody(server, id, "application/json", bodyReader) +} + +// NewUpdateBillingProfileRequestWithBody generates requests for UpdateBillingProfile with any type of body +func NewUpdateBillingProfileRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/billing/profiles/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListCustomersRequest generates requests for ListCustomers +func NewListCustomersRequest(server string, params *ListCustomersParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Key != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "key", *params.Key, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Name != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "name", *params.Name, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PrimaryEmail != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "primaryEmail", *params.PrimaryEmail, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Subject != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "subject", *params.Subject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PlanKey != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "planKey", *params.PlanKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateCustomerRequest calls the generic CreateCustomer builder with application/json body +func NewCreateCustomerRequest(server string, body CreateCustomerJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateCustomerRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateCustomerRequestWithBody generates requests for CreateCustomer with any type of body +func NewCreateCustomerRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteCustomerRequest generates requests for DeleteCustomer +func NewDeleteCustomerRequest(server string, customerIdOrKey ULIDOrExternalKey) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetCustomerRequest generates requests for GetCustomer +func NewGetCustomerRequest(server string, customerIdOrKey ULIDOrExternalKey, params *GetCustomerParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Expand != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "expand", *params.Expand, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateCustomerRequest calls the generic UpdateCustomer builder with application/json body +func NewUpdateCustomerRequest(server string, customerIdOrKey ULIDOrExternalKey, body UpdateCustomerJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateCustomerRequestWithBody(server, customerIdOrKey, "application/json", bodyReader) +} + +// NewUpdateCustomerRequestWithBody generates requests for UpdateCustomer with any type of body +func NewUpdateCustomerRequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetCustomerAccessRequest generates requests for GetCustomerAccess +func NewGetCustomerAccessRequest(server string, customerIdOrKey ULIDOrExternalKey) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/access", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListCustomerAppDataRequest generates requests for ListCustomerAppData +func NewListCustomerAppDataRequest(server string, customerIdOrKey ULIDOrExternalKey, params *ListCustomerAppDataParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/apps", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Type != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "type", *params.Type, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpsertCustomerAppDataRequest calls the generic UpsertCustomerAppData builder with application/json body +func NewUpsertCustomerAppDataRequest(server string, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerAppDataJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpsertCustomerAppDataRequestWithBody(server, customerIdOrKey, "application/json", bodyReader) +} + +// NewUpsertCustomerAppDataRequestWithBody generates requests for UpsertCustomerAppData with any type of body +func NewUpsertCustomerAppDataRequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/apps", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteCustomerAppDataRequest generates requests for DeleteCustomerAppData +func NewDeleteCustomerAppDataRequest(server string, customerIdOrKey ULIDOrExternalKey, appId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "appId", appId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/apps/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetCustomerEntitlementValueRequest generates requests for GetCustomerEntitlementValue +func NewGetCustomerEntitlementValueRequest(server string, customerIdOrKey ULIDOrExternalKey, featureKey string, params *GetCustomerEntitlementValueParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "featureKey", featureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/entitlements/%s/value", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Time != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "time", *params.Time, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetCustomerStripeAppDataRequest generates requests for GetCustomerStripeAppData +func NewGetCustomerStripeAppDataRequest(server string, customerIdOrKey ULIDOrExternalKey) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/stripe", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpsertCustomerStripeAppDataRequest calls the generic UpsertCustomerStripeAppData builder with application/json body +func NewUpsertCustomerStripeAppDataRequest(server string, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerStripeAppDataJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpsertCustomerStripeAppDataRequestWithBody(server, customerIdOrKey, "application/json", bodyReader) +} + +// NewUpsertCustomerStripeAppDataRequestWithBody generates requests for UpsertCustomerStripeAppData with any type of body +func NewUpsertCustomerStripeAppDataRequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/stripe", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCreateCustomerStripePortalSessionRequest calls the generic CreateCustomerStripePortalSession builder with application/json body +func NewCreateCustomerStripePortalSessionRequest(server string, customerIdOrKey ULIDOrExternalKey, body CreateCustomerStripePortalSessionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateCustomerStripePortalSessionRequestWithBody(server, customerIdOrKey, "application/json", bodyReader) +} + +// NewCreateCustomerStripePortalSessionRequestWithBody generates requests for CreateCustomerStripePortalSession with any type of body +func NewCreateCustomerStripePortalSessionRequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/stripe/portal", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListCustomerSubscriptionsRequest generates requests for ListCustomerSubscriptions +func NewListCustomerSubscriptionsRequest(server string, customerIdOrKey ULIDOrExternalKey, params *ListCustomerSubscriptionsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/customers/%s/subscriptions", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetDebugMetricsRequest generates requests for GetDebugMetrics +func NewGetDebugMetricsRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/debug/metrics") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListEntitlementsRequest generates requests for ListEntitlements +func NewListEntitlementsRequest(server string, params *ListEntitlementsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/entitlements") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Feature != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "feature", *params.Feature, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Subject != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "subject", *params.Subject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.EntitlementType != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "entitlementType", *params.EntitlementType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.ExcludeInactive != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "excludeInactive", *params.ExcludeInactive, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetEntitlementByIdRequest generates requests for GetEntitlementById +func NewGetEntitlementByIdRequest(server string, entitlementId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "entitlementId", entitlementId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/entitlements/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListEventsRequest generates requests for ListEvents +func NewListEventsRequest(server string, params *ListEventsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/events") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.ClientId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "clientId", *params.ClientId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IngestedAtFrom != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ingestedAtFrom", *params.IngestedAtFrom, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IngestedAtTo != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "ingestedAtTo", *params.IngestedAtTo, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Id != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "id", *params.Id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Subject != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "subject", *params.Subject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customerId", *params.CustomerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewIngestEventsRequestWithApplicationCloudeventsPlusJSONBody calls the generic IngestEvents builder with application/cloudevents+json body +func NewIngestEventsRequestWithApplicationCloudeventsPlusJSONBody(server string, body IngestEventsApplicationCloudeventsPlusJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewIngestEventsRequestWithBody(server, "application/cloudevents+json", bodyReader) +} + +// NewIngestEventsRequestWithApplicationCloudeventsBatchPlusJSONBody calls the generic IngestEvents builder with application/cloudevents-batch+json body +func NewIngestEventsRequestWithApplicationCloudeventsBatchPlusJSONBody(server string, body IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewIngestEventsRequestWithBody(server, "application/cloudevents-batch+json", bodyReader) +} + +// NewIngestEventsRequest calls the generic IngestEvents builder with application/json body +func NewIngestEventsRequest(server string, body IngestEventsJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewIngestEventsRequestWithBody(server, "application/json", bodyReader) +} + +// NewIngestEventsRequestWithBody generates requests for IngestEvents with any type of body +func NewIngestEventsRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/events") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListFeaturesRequest generates requests for ListFeatures +func NewListFeaturesRequest(server string, params *ListFeaturesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/features") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.MeterSlug != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "meterSlug", *params.MeterSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeArchived != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeArchived", *params.IncludeArchived, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateFeatureRequest calls the generic CreateFeature builder with application/json body +func NewCreateFeatureRequest(server string, body CreateFeatureJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateFeatureRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateFeatureRequestWithBody generates requests for CreateFeature with any type of body +func NewCreateFeatureRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/features") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteFeatureRequest generates requests for DeleteFeature +func NewDeleteFeatureRequest(server string, featureId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "featureId", featureId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/features/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetFeatureRequest generates requests for GetFeature +func NewGetFeatureRequest(server string, featureId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "featureId", featureId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/features/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListGrantsRequest generates requests for ListGrants +func NewListGrantsRequest(server string, params *ListGrantsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/grants") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Feature != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "feature", *params.Feature, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Subject != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "subject", *params.Subject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewVoidGrantRequest generates requests for VoidGrant +func NewVoidGrantRequest(server string, grantId string, params *VoidGrantParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "grantId", grantId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/grants/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.At != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "at", *params.At, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListCurrenciesRequest generates requests for ListCurrencies +func NewListCurrenciesRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/info/currencies") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetProgressRequest generates requests for GetProgress +func NewGetProgressRequest(server string, id string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/info/progress/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListMarketplaceListingsRequest generates requests for ListMarketplaceListings +func NewListMarketplaceListingsRequest(server string, params *ListMarketplaceListingsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/marketplace/listings") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetMarketplaceListingRequest generates requests for GetMarketplaceListing +func NewGetMarketplaceListingRequest(server string, pType AppType) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "type", pType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/marketplace/listings/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewMarketplaceAppInstallRequest calls the generic MarketplaceAppInstall builder with application/json body +func NewMarketplaceAppInstallRequest(server string, pType MarketplaceInstallRequestType, body MarketplaceAppInstallJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewMarketplaceAppInstallRequestWithBody(server, pType, "application/json", bodyReader) +} + +// NewMarketplaceAppInstallRequestWithBody generates requests for MarketplaceAppInstall with any type of body +func NewMarketplaceAppInstallRequestWithBody(server string, pType MarketplaceInstallRequestType, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "type", pType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/marketplace/listings/%s/install", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewMarketplaceAppAPIKeyInstallRequest calls the generic MarketplaceAppAPIKeyInstall builder with application/json body +func NewMarketplaceAppAPIKeyInstallRequest(server string, pType MarketplaceApiKeyInstallRequestType, body MarketplaceAppAPIKeyInstallJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewMarketplaceAppAPIKeyInstallRequestWithBody(server, pType, "application/json", bodyReader) +} + +// NewMarketplaceAppAPIKeyInstallRequestWithBody generates requests for MarketplaceAppAPIKeyInstall with any type of body +func NewMarketplaceAppAPIKeyInstallRequestWithBody(server string, pType MarketplaceApiKeyInstallRequestType, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "type", pType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/marketplace/listings/%s/install/apikey", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewMarketplaceOAuth2InstallGetURLRequest generates requests for MarketplaceOAuth2InstallGetURL +func NewMarketplaceOAuth2InstallGetURLRequest(server string, pType AppType) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "type", pType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/marketplace/listings/%s/install/oauth2", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewMarketplaceOAuth2InstallAuthorizeRequest generates requests for MarketplaceOAuth2InstallAuthorize +func NewMarketplaceOAuth2InstallAuthorizeRequest(server string, pType MarketplaceOAuth2InstallAuthorizeRequestType, params *MarketplaceOAuth2InstallAuthorizeParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "type", pType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/marketplace/listings/%s/install/oauth2/authorize", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.State != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "state", *params.State, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Code != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "code", *params.Code, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Error != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "error", *params.Error, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.ErrorDescription != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "error_description", *params.ErrorDescription, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.ErrorUri != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "error_uri", *params.ErrorUri, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListMetersRequest generates requests for ListMeters +func NewListMetersRequest(server string, params *ListMetersParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateMeterRequest calls the generic CreateMeter builder with application/json body +func NewCreateMeterRequest(server string, body CreateMeterJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateMeterRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateMeterRequestWithBody generates requests for CreateMeter with any type of body +func NewCreateMeterRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteMeterRequest generates requests for DeleteMeter +func NewDeleteMeterRequest(server string, meterIdOrSlug string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetMeterRequest generates requests for GetMeter +func NewGetMeterRequest(server string, meterIdOrSlug string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateMeterRequest calls the generic UpdateMeter builder with application/json body +func NewUpdateMeterRequest(server string, meterIdOrSlug string, body UpdateMeterJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateMeterRequestWithBody(server, meterIdOrSlug, "application/json", bodyReader) +} + +// NewUpdateMeterRequestWithBody generates requests for UpdateMeter with any type of body +func NewUpdateMeterRequestWithBody(server string, meterIdOrSlug string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListMeterGroupByValuesRequest generates requests for ListMeterGroupByValues +func NewListMeterGroupByValuesRequest(server string, meterIdOrSlug string, groupByKey string, params *ListMeterGroupByValuesParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "groupByKey", groupByKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s/group-by/%s/values", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewQueryMeterRequest generates requests for QueryMeter +func NewQueryMeterRequest(server string, meterIdOrSlug string, params *QueryMeterParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s/query", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.ClientId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "clientId", *params.ClientId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.WindowSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowSize", *params.WindowSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.WindowTimeZone != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowTimeZone", *params.WindowTimeZone, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Subject != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "subject", *params.Subject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.FilterCustomerId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "filterCustomerId", *params.FilterCustomerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.FilterGroupBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "filterGroupBy", *params.FilterGroupBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.AdvancedMeterGroupByFilters != nil { + + if queryParamBuf, err := json.Marshal(*params.AdvancedMeterGroupByFilters); err != nil { + return nil, err + } else { + queryValues.Add("advancedMeterGroupByFilters", string(queryParamBuf)) + } + + } + + if params.GroupBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "groupBy", *params.GroupBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewQueryMeterPostRequest calls the generic QueryMeterPost builder with application/json body +func NewQueryMeterPostRequest(server string, meterIdOrSlug string, body QueryMeterPostJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewQueryMeterPostRequestWithBody(server, meterIdOrSlug, "application/json", bodyReader) +} + +// NewQueryMeterPostRequestWithBody generates requests for QueryMeterPost with any type of body +func NewQueryMeterPostRequestWithBody(server string, meterIdOrSlug string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s/query", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListMeterSubjectsRequest generates requests for ListMeterSubjects +func NewListMeterSubjectsRequest(server string, meterIdOrSlug string, params *ListMeterSubjectsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterIdOrSlug", meterIdOrSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/meters/%s/subjects", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListNotificationChannelsRequest generates requests for ListNotificationChannels +func NewListNotificationChannelsRequest(server string, params *ListNotificationChannelsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/channels") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDisabled != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDisabled", *params.IncludeDisabled, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateNotificationChannelRequest calls the generic CreateNotificationChannel builder with application/json body +func NewCreateNotificationChannelRequest(server string, body CreateNotificationChannelJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateNotificationChannelRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateNotificationChannelRequestWithBody generates requests for CreateNotificationChannel with any type of body +func NewCreateNotificationChannelRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/channels") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteNotificationChannelRequest generates requests for DeleteNotificationChannel +func NewDeleteNotificationChannelRequest(server string, channelId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "channelId", channelId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/channels/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNotificationChannelRequest generates requests for GetNotificationChannel +func NewGetNotificationChannelRequest(server string, channelId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "channelId", channelId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/channels/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateNotificationChannelRequest calls the generic UpdateNotificationChannel builder with application/json body +func NewUpdateNotificationChannelRequest(server string, channelId string, body UpdateNotificationChannelJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateNotificationChannelRequestWithBody(server, channelId, "application/json", bodyReader) +} + +// NewUpdateNotificationChannelRequestWithBody generates requests for UpdateNotificationChannel with any type of body +func NewUpdateNotificationChannelRequestWithBody(server string, channelId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "channelId", channelId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/channels/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListNotificationEventsRequest generates requests for ListNotificationEvents +func NewListNotificationEventsRequest(server string, params *ListNotificationEventsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/events") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Feature != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "feature", *params.Feature, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Subject != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "subject", *params.Subject, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Rule != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "rule", *params.Rule, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Channel != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "channel", *params.Channel, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNotificationEventRequest generates requests for GetNotificationEvent +func NewGetNotificationEventRequest(server string, eventId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "eventId", eventId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/events/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewResendNotificationEventRequest calls the generic ResendNotificationEvent builder with application/json body +func NewResendNotificationEventRequest(server string, eventId string, body ResendNotificationEventJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewResendNotificationEventRequestWithBody(server, eventId, "application/json", bodyReader) +} + +// NewResendNotificationEventRequestWithBody generates requests for ResendNotificationEvent with any type of body +func NewResendNotificationEventRequestWithBody(server string, eventId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "eventId", eventId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/events/%s/resend", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListNotificationRulesRequest generates requests for ListNotificationRules +func NewListNotificationRulesRequest(server string, params *ListNotificationRulesParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/rules") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDisabled != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDisabled", *params.IncludeDisabled, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Feature != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "feature", *params.Feature, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Channel != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "channel", *params.Channel, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateNotificationRuleRequest calls the generic CreateNotificationRule builder with application/json body +func NewCreateNotificationRuleRequest(server string, body CreateNotificationRuleJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateNotificationRuleRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateNotificationRuleRequestWithBody generates requests for CreateNotificationRule with any type of body +func NewCreateNotificationRuleRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/rules") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteNotificationRuleRequest generates requests for DeleteNotificationRule +func NewDeleteNotificationRuleRequest(server string, ruleId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "ruleId", ruleId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/rules/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetNotificationRuleRequest generates requests for GetNotificationRule +func NewGetNotificationRuleRequest(server string, ruleId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "ruleId", ruleId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/rules/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateNotificationRuleRequest calls the generic UpdateNotificationRule builder with application/json body +func NewUpdateNotificationRuleRequest(server string, ruleId string, body UpdateNotificationRuleJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateNotificationRuleRequestWithBody(server, ruleId, "application/json", bodyReader) +} + +// NewUpdateNotificationRuleRequestWithBody generates requests for UpdateNotificationRule with any type of body +func NewUpdateNotificationRuleRequestWithBody(server string, ruleId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "ruleId", ruleId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/rules/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewTestNotificationRuleRequest generates requests for TestNotificationRule +func NewTestNotificationRuleRequest(server string, ruleId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "ruleId", ruleId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/notification/rules/%s/test", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListPlansRequest generates requests for ListPlans +func NewListPlansRequest(server string, params *ListPlansParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Id != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "id", *params.Id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Key != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "key", *params.Key, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.KeyVersion != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "keyVersion", *params.KeyVersion, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Currency != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "currency", *params.Currency, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreatePlanRequest calls the generic CreatePlan builder with application/json body +func NewCreatePlanRequest(server string, body CreatePlanJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreatePlanRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreatePlanRequestWithBody generates requests for CreatePlan with any type of body +func NewCreatePlanRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewNextPlanRequest generates requests for NextPlan +func NewNextPlanRequest(server string, planIdOrKey string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planIdOrKey", planIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/next", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewDeletePlanRequest generates requests for DeletePlan +func NewDeletePlanRequest(server string, planId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetPlanRequest generates requests for GetPlan +func NewGetPlanRequest(server string, planId string, params *GetPlanParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeLatest != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeLatest", *params.IncludeLatest, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdatePlanRequest calls the generic UpdatePlan builder with application/json body +func NewUpdatePlanRequest(server string, planId string, body UpdatePlanJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdatePlanRequestWithBody(server, planId, "application/json", bodyReader) +} + +// NewUpdatePlanRequestWithBody generates requests for UpdatePlan with any type of body +func NewUpdatePlanRequestWithBody(server string, planId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListPlanAddonsRequest generates requests for ListPlanAddons +func NewListPlanAddonsRequest(server string, planId string, params *ListPlanAddonsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/addons", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Id != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "id", *params.Id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Key != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "key", *params.Key, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.KeyVersion != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "keyVersion", *params.KeyVersion, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreatePlanAddonRequest calls the generic CreatePlanAddon builder with application/json body +func NewCreatePlanAddonRequest(server string, planId string, body CreatePlanAddonJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreatePlanAddonRequestWithBody(server, planId, "application/json", bodyReader) +} + +// NewCreatePlanAddonRequestWithBody generates requests for CreatePlanAddon with any type of body +func NewCreatePlanAddonRequestWithBody(server string, planId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/addons", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeletePlanAddonRequest generates requests for DeletePlanAddon +func NewDeletePlanAddonRequest(server string, planId string, planAddonId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "planAddonId", planAddonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/addons/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetPlanAddonRequest generates requests for GetPlanAddon +func NewGetPlanAddonRequest(server string, planId string, planAddonId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "planAddonId", planAddonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/addons/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdatePlanAddonRequest calls the generic UpdatePlanAddon builder with application/json body +func NewUpdatePlanAddonRequest(server string, planId string, planAddonId string, body UpdatePlanAddonJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdatePlanAddonRequestWithBody(server, planId, planAddonId, "application/json", bodyReader) +} + +// NewUpdatePlanAddonRequestWithBody generates requests for UpdatePlanAddon with any type of body +func NewUpdatePlanAddonRequestWithBody(server string, planId string, planAddonId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "planAddonId", planAddonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/addons/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewArchivePlanRequest generates requests for ArchivePlan +func NewArchivePlanRequest(server string, planId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/archive", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewPublishPlanRequest generates requests for PublishPlan +func NewPublishPlanRequest(server string, planId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "planId", planId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/plans/%s/publish", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewQueryPortalMeterRequest generates requests for QueryPortalMeter +func NewQueryPortalMeterRequest(server string, meterSlug string, params *QueryPortalMeterParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "meterSlug", meterSlug, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/portal/meters/%s/query", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.ClientId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "clientId", *params.ClientId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.WindowSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowSize", *params.WindowSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.WindowTimeZone != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowTimeZone", *params.WindowTimeZone, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.FilterCustomerId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "filterCustomerId", *params.FilterCustomerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.FilterGroupBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("deepObject", true, "filterGroupBy", *params.FilterGroupBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "object", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.AdvancedMeterGroupByFilters != nil { + + if queryParamBuf, err := json.Marshal(*params.AdvancedMeterGroupByFilters); err != nil { + return nil, err + } else { + queryValues.Add("advancedMeterGroupByFilters", string(queryParamBuf)) + } + + } + + if params.GroupBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "groupBy", *params.GroupBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListPortalTokensRequest generates requests for ListPortalTokens +func NewListPortalTokensRequest(server string, params *ListPortalTokensParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/portal/tokens") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreatePortalTokenRequest calls the generic CreatePortalToken builder with application/json body +func NewCreatePortalTokenRequest(server string, body CreatePortalTokenJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreatePortalTokenRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreatePortalTokenRequestWithBody generates requests for CreatePortalToken with any type of body +func NewCreatePortalTokenRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/portal/tokens") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewInvalidatePortalTokensRequest calls the generic InvalidatePortalTokens builder with application/json body +func NewInvalidatePortalTokensRequest(server string, body InvalidatePortalTokensJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewInvalidatePortalTokensRequestWithBody(server, "application/json", bodyReader) +} + +// NewInvalidatePortalTokensRequestWithBody generates requests for InvalidatePortalTokens with any type of body +func NewInvalidatePortalTokensRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/portal/tokens/invalidate") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCreateStripeCheckoutSessionRequest calls the generic CreateStripeCheckoutSession builder with application/json body +func NewCreateStripeCheckoutSessionRequest(server string, body CreateStripeCheckoutSessionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateStripeCheckoutSessionRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateStripeCheckoutSessionRequestWithBody generates requests for CreateStripeCheckoutSession with any type of body +func NewCreateStripeCheckoutSessionRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/stripe/checkout/sessions") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListSubjectsRequest generates requests for ListSubjects +func NewListSubjectsRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpsertSubjectRequest calls the generic UpsertSubject builder with application/json body +func NewUpsertSubjectRequest(server string, body UpsertSubjectJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpsertSubjectRequestWithBody(server, "application/json", bodyReader) +} + +// NewUpsertSubjectRequestWithBody generates requests for UpsertSubject with any type of body +func NewUpsertSubjectRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteSubjectRequest generates requests for DeleteSubject +func NewDeleteSubjectRequest(server string, subjectIdOrKey string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetSubjectRequest generates requests for GetSubject +func NewGetSubjectRequest(server string, subjectIdOrKey string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListSubjectEntitlementsRequest generates requests for ListSubjectEntitlements +func NewListSubjectEntitlementsRequest(server string, subjectIdOrKey string, params *ListSubjectEntitlementsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateEntitlementRequest calls the generic CreateEntitlement builder with application/json body +func NewCreateEntitlementRequest(server string, subjectIdOrKey string, body CreateEntitlementJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateEntitlementRequestWithBody(server, subjectIdOrKey, "application/json", bodyReader) +} + +// NewCreateEntitlementRequestWithBody generates requests for CreateEntitlement with any type of body +func NewCreateEntitlementRequestWithBody(server string, subjectIdOrKey string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListEntitlementGrantsRequest generates requests for ListEntitlementGrants +func NewListEntitlementGrantsRequest(server string, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *ListEntitlementGrantsParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s/grants", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateGrantRequest calls the generic CreateGrant builder with application/json body +func NewCreateGrantRequest(server string, subjectIdOrKey string, entitlementIdOrFeatureKey string, body CreateGrantJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateGrantRequestWithBody(server, subjectIdOrKey, entitlementIdOrFeatureKey, "application/json", bodyReader) +} + +// NewCreateGrantRequestWithBody generates requests for CreateGrant with any type of body +func NewCreateGrantRequestWithBody(server string, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s/grants", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewOverrideEntitlementRequest calls the generic OverrideEntitlement builder with application/json body +func NewOverrideEntitlementRequest(server string, subjectIdOrKey string, entitlementIdOrFeatureKey string, body OverrideEntitlementJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewOverrideEntitlementRequestWithBody(server, subjectIdOrKey, entitlementIdOrFeatureKey, "application/json", bodyReader) +} + +// NewOverrideEntitlementRequestWithBody generates requests for OverrideEntitlement with any type of body +func NewOverrideEntitlementRequestWithBody(server string, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s/override", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetEntitlementValueRequest generates requests for GetEntitlementValue +func NewGetEntitlementValueRequest(server string, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *GetEntitlementValueParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s/value", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Time != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "time", *params.Time, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewDeleteEntitlementRequest generates requests for DeleteEntitlement +func NewDeleteEntitlementRequest(server string, subjectIdOrKey string, entitlementId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementId", entitlementId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetEntitlementRequest generates requests for GetEntitlement +func NewGetEntitlementRequest(server string, subjectIdOrKey string, entitlementId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementId", entitlementId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetEntitlementHistoryRequest generates requests for GetEntitlementHistory +func NewGetEntitlementHistoryRequest(server string, subjectIdOrKey string, entitlementId string, params *GetEntitlementHistoryParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementId", entitlementId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s/history", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowSize", params.WindowSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + if params.WindowTimeZone != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowTimeZone", *params.WindowTimeZone, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewResetEntitlementUsageRequest calls the generic ResetEntitlementUsage builder with application/json body +func NewResetEntitlementUsageRequest(server string, subjectIdOrKey string, entitlementId string, body ResetEntitlementUsageJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewResetEntitlementUsageRequestWithBody(server, subjectIdOrKey, entitlementId, "application/json", bodyReader) +} + +// NewResetEntitlementUsageRequestWithBody generates requests for ResetEntitlementUsage with any type of body +func NewResetEntitlementUsageRequestWithBody(server string, subjectIdOrKey string, entitlementId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subjectIdOrKey", subjectIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementId", entitlementId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subjects/%s/entitlements/%s/reset", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCreateSubscriptionRequest calls the generic CreateSubscription builder with application/json body +func NewCreateSubscriptionRequest(server string, body CreateSubscriptionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateSubscriptionRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateSubscriptionRequestWithBody generates requests for CreateSubscription with any type of body +func NewCreateSubscriptionRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteSubscriptionRequest generates requests for DeleteSubscription +func NewDeleteSubscriptionRequest(server string, subscriptionId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetSubscriptionRequest generates requests for GetSubscription +func NewGetSubscriptionRequest(server string, subscriptionId string, params *GetSubscriptionParams) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.At != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "at", *params.At, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewEditSubscriptionRequest calls the generic EditSubscription builder with application/json body +func NewEditSubscriptionRequest(server string, subscriptionId string, body EditSubscriptionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewEditSubscriptionRequestWithBody(server, subscriptionId, "application/json", bodyReader) +} + +// NewEditSubscriptionRequestWithBody generates requests for EditSubscription with any type of body +func NewEditSubscriptionRequestWithBody(server string, subscriptionId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPatch, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewListSubscriptionAddonsRequest generates requests for ListSubscriptionAddons +func NewListSubscriptionAddonsRequest(server string, subscriptionId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/addons", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateSubscriptionAddonRequest calls the generic CreateSubscriptionAddon builder with application/json body +func NewCreateSubscriptionAddonRequest(server string, subscriptionId string, body CreateSubscriptionAddonJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateSubscriptionAddonRequestWithBody(server, subscriptionId, "application/json", bodyReader) +} + +// NewCreateSubscriptionAddonRequestWithBody generates requests for CreateSubscriptionAddon with any type of body +func NewCreateSubscriptionAddonRequestWithBody(server string, subscriptionId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/addons", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetSubscriptionAddonRequest generates requests for GetSubscriptionAddon +func NewGetSubscriptionAddonRequest(server string, subscriptionId string, subscriptionAddonId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "subscriptionAddonId", subscriptionAddonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/addons/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUpdateSubscriptionAddonRequest calls the generic UpdateSubscriptionAddon builder with application/json body +func NewUpdateSubscriptionAddonRequest(server string, subscriptionId string, subscriptionAddonId string, body UpdateSubscriptionAddonJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewUpdateSubscriptionAddonRequestWithBody(server, subscriptionId, subscriptionAddonId, "application/json", bodyReader) +} + +// NewUpdateSubscriptionAddonRequestWithBody generates requests for UpdateSubscriptionAddon with any type of body +func NewUpdateSubscriptionAddonRequestWithBody(server string, subscriptionId string, subscriptionAddonId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "subscriptionAddonId", subscriptionAddonId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/addons/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPatch, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCancelSubscriptionRequest calls the generic CancelSubscription builder with application/json body +func NewCancelSubscriptionRequest(server string, subscriptionId string, body CancelSubscriptionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCancelSubscriptionRequestWithBody(server, subscriptionId, "application/json", bodyReader) +} + +// NewCancelSubscriptionRequestWithBody generates requests for CancelSubscription with any type of body +func NewCancelSubscriptionRequestWithBody(server string, subscriptionId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/cancel", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewChangeSubscriptionRequest calls the generic ChangeSubscription builder with application/json body +func NewChangeSubscriptionRequest(server string, subscriptionId string, body ChangeSubscriptionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewChangeSubscriptionRequestWithBody(server, subscriptionId, "application/json", bodyReader) +} + +// NewChangeSubscriptionRequestWithBody generates requests for ChangeSubscription with any type of body +func NewChangeSubscriptionRequestWithBody(server string, subscriptionId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/change", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewMigrateSubscriptionRequest calls the generic MigrateSubscription builder with application/json body +func NewMigrateSubscriptionRequest(server string, subscriptionId string, body MigrateSubscriptionJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewMigrateSubscriptionRequestWithBody(server, subscriptionId, "application/json", bodyReader) +} + +// NewMigrateSubscriptionRequestWithBody generates requests for MigrateSubscription with any type of body +func NewMigrateSubscriptionRequestWithBody(server string, subscriptionId string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/migrate", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewRestoreSubscriptionRequest generates requests for RestoreSubscription +func NewRestoreSubscriptionRequest(server string, subscriptionId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/restore", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewUnscheduleCancelationRequest generates requests for UnscheduleCancelation +func NewUnscheduleCancelationRequest(server string, subscriptionId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "subscriptionId", subscriptionId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v1/subscriptions/%s/unschedule-cancelation", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListCustomerEntitlementsV2Request generates requests for ListCustomerEntitlementsV2 +func NewListCustomerEntitlementsV2Request(server string, customerIdOrKey ULIDOrExternalKey, params *ListCustomerEntitlementsV2Params) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateCustomerEntitlementV2Request calls the generic CreateCustomerEntitlementV2 builder with application/json body +func NewCreateCustomerEntitlementV2Request(server string, customerIdOrKey ULIDOrExternalKey, body CreateCustomerEntitlementV2JSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateCustomerEntitlementV2RequestWithBody(server, customerIdOrKey, "application/json", bodyReader) +} + +// NewCreateCustomerEntitlementV2RequestWithBody generates requests for CreateCustomerEntitlementV2 with any type of body +func NewCreateCustomerEntitlementV2RequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewDeleteCustomerEntitlementV2Request generates requests for DeleteCustomerEntitlementV2 +func NewDeleteCustomerEntitlementV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetCustomerEntitlementV2Request generates requests for GetCustomerEntitlementV2 +func NewGetCustomerEntitlementV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListCustomerEntitlementGrantsV2Request generates requests for ListCustomerEntitlementGrantsV2 +func NewListCustomerEntitlementGrantsV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *ListCustomerEntitlementGrantsV2Params) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s/grants", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateCustomerEntitlementGrantV2Request calls the generic CreateCustomerEntitlementGrantV2 builder with application/json body +func NewCreateCustomerEntitlementGrantV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body CreateCustomerEntitlementGrantV2JSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateCustomerEntitlementGrantV2RequestWithBody(server, customerIdOrKey, entitlementIdOrFeatureKey, "application/json", bodyReader) +} + +// NewCreateCustomerEntitlementGrantV2RequestWithBody generates requests for CreateCustomerEntitlementGrantV2 with any type of body +func NewCreateCustomerEntitlementGrantV2RequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s/grants", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetCustomerEntitlementHistoryV2Request generates requests for GetCustomerEntitlementHistoryV2 +func NewGetCustomerEntitlementHistoryV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementHistoryV2Params) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s/history", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.From != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "from", *params.From, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.To != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "to", *params.To, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowSize", params.WindowSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + if params.WindowTimeZone != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "windowTimeZone", *params.WindowTimeZone, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewOverrideCustomerEntitlementV2Request calls the generic OverrideCustomerEntitlementV2 builder with application/json body +func NewOverrideCustomerEntitlementV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, body OverrideCustomerEntitlementV2JSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewOverrideCustomerEntitlementV2RequestWithBody(server, customerIdOrKey, entitlementIdOrFeatureKey, "application/json", bodyReader) +} + +// NewOverrideCustomerEntitlementV2RequestWithBody generates requests for OverrideCustomerEntitlementV2 with any type of body +func NewOverrideCustomerEntitlementV2RequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s/override", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPut, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewResetCustomerEntitlementUsageV2Request calls the generic ResetCustomerEntitlementUsageV2 builder with application/json body +func NewResetCustomerEntitlementUsageV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body ResetCustomerEntitlementUsageV2JSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewResetCustomerEntitlementUsageV2RequestWithBody(server, customerIdOrKey, entitlementIdOrFeatureKey, "application/json", bodyReader) +} + +// NewResetCustomerEntitlementUsageV2RequestWithBody generates requests for ResetCustomerEntitlementUsageV2 with any type of body +func NewResetCustomerEntitlementUsageV2RequestWithBody(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s/reset", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetCustomerEntitlementValueV2Request generates requests for GetCustomerEntitlementValueV2 +func NewGetCustomerEntitlementValueV2Request(server string, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementValueV2Params) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "customerIdOrKey", customerIdOrKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "entitlementIdOrFeatureKey", entitlementIdOrFeatureKey, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/customers/%s/entitlements/%s/value", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Time != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "time", *params.Time, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: "date-time"}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListEntitlementsV2Request generates requests for ListEntitlementsV2 +func NewListEntitlementsV2Request(server string, params *ListEntitlementsV2Params) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/entitlements") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Feature != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "feature", *params.Feature, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerKeys != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customerKeys", *params.CustomerKeys, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.CustomerIds != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customerIds", *params.CustomerIds, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.EntitlementType != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "entitlementType", *params.EntitlementType, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.ExcludeInactive != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "excludeInactive", *params.ExcludeInactive, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetEntitlementByIdV2Request generates requests for GetEntitlementByIdV2 +func NewGetEntitlementByIdV2Request(server string, entitlementId string) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "entitlementId", entitlementId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/entitlements/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListEventsV2Request generates requests for ListEventsV2 +func NewListEventsV2Request(server string, params *ListEventsV2Params) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/events") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.ClientId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "clientId", *params.ClientId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Filter != nil { + + if queryParamBuf, err := json.Marshal(*params.Filter); err != nil { + return nil, err + } else { + queryValues.Add("filter", string(queryParamBuf)) + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListGrantsV2Request generates requests for ListGrantsV2 +func NewListGrantsV2Request(server string, params *ListGrantsV2Params) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/api/v2/grants") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Feature != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "feature", *params.Feature, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Customer != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "customer", *params.Customer, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "array", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.IncludeDeleted != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "includeDeleted", *params.IncludeDeleted, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Page != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "page", *params.Page, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.PageSize != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "pageSize", *params.PageSize, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Offset != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "offset", *params.Offset, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Order != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "order", *params.Order, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.OrderBy != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", false, "orderBy", *params.OrderBy, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + // ListAddonsWithResponse request + ListAddonsWithResponse(ctx context.Context, params *ListAddonsParams, reqEditors ...RequestEditorFn) (*ListAddonsResponse, error) + + // CreateAddonWithBodyWithResponse request with any body + CreateAddonWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateAddonResponse, error) + + CreateAddonWithResponse(ctx context.Context, body CreateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateAddonResponse, error) + + // DeleteAddonWithResponse request + DeleteAddonWithResponse(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*DeleteAddonResponse, error) + + // GetAddonWithResponse request + GetAddonWithResponse(ctx context.Context, addonId string, params *GetAddonParams, reqEditors ...RequestEditorFn) (*GetAddonResponse, error) + + // UpdateAddonWithBodyWithResponse request with any body + UpdateAddonWithBodyWithResponse(ctx context.Context, addonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateAddonResponse, error) + + UpdateAddonWithResponse(ctx context.Context, addonId string, body UpdateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateAddonResponse, error) + + // ArchiveAddonWithResponse request + ArchiveAddonWithResponse(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*ArchiveAddonResponse, error) + + // PublishAddonWithResponse request + PublishAddonWithResponse(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*PublishAddonResponse, error) + + // ListAppsWithResponse request + ListAppsWithResponse(ctx context.Context, params *ListAppsParams, reqEditors ...RequestEditorFn) (*ListAppsResponse, error) + + // AppCustomInvoicingDraftSynchronizedWithBodyWithResponse request with any body + AppCustomInvoicingDraftSynchronizedWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppCustomInvoicingDraftSynchronizedResponse, error) + + AppCustomInvoicingDraftSynchronizedWithResponse(ctx context.Context, invoiceId string, body AppCustomInvoicingDraftSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*AppCustomInvoicingDraftSynchronizedResponse, error) + + // AppCustomInvoicingIssuingSynchronizedWithBodyWithResponse request with any body + AppCustomInvoicingIssuingSynchronizedWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppCustomInvoicingIssuingSynchronizedResponse, error) + + AppCustomInvoicingIssuingSynchronizedWithResponse(ctx context.Context, invoiceId string, body AppCustomInvoicingIssuingSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*AppCustomInvoicingIssuingSynchronizedResponse, error) + + // AppCustomInvoicingUpdatePaymentStatusWithBodyWithResponse request with any body + AppCustomInvoicingUpdatePaymentStatusWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppCustomInvoicingUpdatePaymentStatusResponse, error) + + AppCustomInvoicingUpdatePaymentStatusWithResponse(ctx context.Context, invoiceId string, body AppCustomInvoicingUpdatePaymentStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*AppCustomInvoicingUpdatePaymentStatusResponse, error) + + // UninstallAppWithResponse request + UninstallAppWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*UninstallAppResponse, error) + + // GetAppWithResponse request + GetAppWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetAppResponse, error) + + // UpdateAppWithBodyWithResponse request with any body + UpdateAppWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateAppResponse, error) + + UpdateAppWithResponse(ctx context.Context, id string, body UpdateAppJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateAppResponse, error) + + // UpdateStripeAPIKeyWithBodyWithResponse request with any body + UpdateStripeAPIKeyWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateStripeAPIKeyResponse, error) + + UpdateStripeAPIKeyWithResponse(ctx context.Context, id string, body UpdateStripeAPIKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateStripeAPIKeyResponse, error) + + // AppStripeWebhookWithBodyWithResponse request with any body + AppStripeWebhookWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppStripeWebhookResponse, error) + + AppStripeWebhookWithResponse(ctx context.Context, id string, body AppStripeWebhookJSONRequestBody, reqEditors ...RequestEditorFn) (*AppStripeWebhookResponse, error) + + // ListBillingProfileCustomerOverridesWithResponse request + ListBillingProfileCustomerOverridesWithResponse(ctx context.Context, params *ListBillingProfileCustomerOverridesParams, reqEditors ...RequestEditorFn) (*ListBillingProfileCustomerOverridesResponse, error) + + // DeleteBillingProfileCustomerOverrideWithResponse request + DeleteBillingProfileCustomerOverrideWithResponse(ctx context.Context, customerId string, reqEditors ...RequestEditorFn) (*DeleteBillingProfileCustomerOverrideResponse, error) + + // GetBillingProfileCustomerOverrideWithResponse request + GetBillingProfileCustomerOverrideWithResponse(ctx context.Context, customerId string, params *GetBillingProfileCustomerOverrideParams, reqEditors ...RequestEditorFn) (*GetBillingProfileCustomerOverrideResponse, error) + + // UpsertBillingProfileCustomerOverrideWithBodyWithResponse request with any body + UpsertBillingProfileCustomerOverrideWithBodyWithResponse(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertBillingProfileCustomerOverrideResponse, error) + + UpsertBillingProfileCustomerOverrideWithResponse(ctx context.Context, customerId string, body UpsertBillingProfileCustomerOverrideJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertBillingProfileCustomerOverrideResponse, error) + + // CreatePendingInvoiceLineWithBodyWithResponse request with any body + CreatePendingInvoiceLineWithBodyWithResponse(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePendingInvoiceLineResponse, error) + + CreatePendingInvoiceLineWithResponse(ctx context.Context, customerId string, body CreatePendingInvoiceLineJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePendingInvoiceLineResponse, error) + + // SimulateInvoiceWithBodyWithResponse request with any body + SimulateInvoiceWithBodyWithResponse(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SimulateInvoiceResponse, error) + + SimulateInvoiceWithResponse(ctx context.Context, customerId string, body SimulateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*SimulateInvoiceResponse, error) + + // ListInvoicesWithResponse request + ListInvoicesWithResponse(ctx context.Context, params *ListInvoicesParams, reqEditors ...RequestEditorFn) (*ListInvoicesResponse, error) + + // InvoicePendingLinesActionWithBodyWithResponse request with any body + InvoicePendingLinesActionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*InvoicePendingLinesActionResponse, error) + + InvoicePendingLinesActionWithResponse(ctx context.Context, body InvoicePendingLinesActionJSONRequestBody, reqEditors ...RequestEditorFn) (*InvoicePendingLinesActionResponse, error) + + // DeleteInvoiceWithResponse request + DeleteInvoiceWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*DeleteInvoiceResponse, error) + + // GetInvoiceWithResponse request + GetInvoiceWithResponse(ctx context.Context, invoiceId string, params *GetInvoiceParams, reqEditors ...RequestEditorFn) (*GetInvoiceResponse, error) + + // UpdateInvoiceWithBodyWithResponse request with any body + UpdateInvoiceWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateInvoiceResponse, error) + + UpdateInvoiceWithResponse(ctx context.Context, invoiceId string, body UpdateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateInvoiceResponse, error) + + // AdvanceInvoiceActionWithResponse request + AdvanceInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*AdvanceInvoiceActionResponse, error) + + // ApproveInvoiceActionWithResponse request + ApproveInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*ApproveInvoiceActionResponse, error) + + // RetryInvoiceActionWithResponse request + RetryInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*RetryInvoiceActionResponse, error) + + // SnapshotQuantitiesInvoiceActionWithResponse request + SnapshotQuantitiesInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*SnapshotQuantitiesInvoiceActionResponse, error) + + // RecalculateInvoiceTaxActionWithResponse request + RecalculateInvoiceTaxActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*RecalculateInvoiceTaxActionResponse, error) + + // VoidInvoiceActionWithBodyWithResponse request with any body + VoidInvoiceActionWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VoidInvoiceActionResponse, error) + + VoidInvoiceActionWithResponse(ctx context.Context, invoiceId string, body VoidInvoiceActionJSONRequestBody, reqEditors ...RequestEditorFn) (*VoidInvoiceActionResponse, error) + + // ListBillingProfilesWithResponse request + ListBillingProfilesWithResponse(ctx context.Context, params *ListBillingProfilesParams, reqEditors ...RequestEditorFn) (*ListBillingProfilesResponse, error) + + // CreateBillingProfileWithBodyWithResponse request with any body + CreateBillingProfileWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateBillingProfileResponse, error) + + CreateBillingProfileWithResponse(ctx context.Context, body CreateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateBillingProfileResponse, error) + + // DeleteBillingProfileWithResponse request + DeleteBillingProfileWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*DeleteBillingProfileResponse, error) + + // GetBillingProfileWithResponse request + GetBillingProfileWithResponse(ctx context.Context, id string, params *GetBillingProfileParams, reqEditors ...RequestEditorFn) (*GetBillingProfileResponse, error) + + // UpdateBillingProfileWithBodyWithResponse request with any body + UpdateBillingProfileWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateBillingProfileResponse, error) + + UpdateBillingProfileWithResponse(ctx context.Context, id string, body UpdateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateBillingProfileResponse, error) + + // ListCustomersWithResponse request + ListCustomersWithResponse(ctx context.Context, params *ListCustomersParams, reqEditors ...RequestEditorFn) (*ListCustomersResponse, error) + + // CreateCustomerWithBodyWithResponse request with any body + CreateCustomerWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerResponse, error) + + CreateCustomerWithResponse(ctx context.Context, body CreateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerResponse, error) + + // DeleteCustomerWithResponse request + DeleteCustomerWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*DeleteCustomerResponse, error) + + // GetCustomerWithResponse request + GetCustomerWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *GetCustomerParams, reqEditors ...RequestEditorFn) (*GetCustomerResponse, error) + + // UpdateCustomerWithBodyWithResponse request with any body + UpdateCustomerWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateCustomerResponse, error) + + UpdateCustomerWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpdateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateCustomerResponse, error) + + // GetCustomerAccessWithResponse request + GetCustomerAccessWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*GetCustomerAccessResponse, error) + + // ListCustomerAppDataWithResponse request + ListCustomerAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerAppDataParams, reqEditors ...RequestEditorFn) (*ListCustomerAppDataResponse, error) + + // UpsertCustomerAppDataWithBodyWithResponse request with any body + UpsertCustomerAppDataWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertCustomerAppDataResponse, error) + + UpsertCustomerAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertCustomerAppDataResponse, error) + + // DeleteCustomerAppDataWithResponse request + DeleteCustomerAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, appId string, reqEditors ...RequestEditorFn) (*DeleteCustomerAppDataResponse, error) + + // GetCustomerEntitlementValueWithResponse request + GetCustomerEntitlementValueWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, featureKey string, params *GetCustomerEntitlementValueParams, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementValueResponse, error) + + // GetCustomerStripeAppDataWithResponse request + GetCustomerStripeAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*GetCustomerStripeAppDataResponse, error) + + // UpsertCustomerStripeAppDataWithBodyWithResponse request with any body + UpsertCustomerStripeAppDataWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertCustomerStripeAppDataResponse, error) + + UpsertCustomerStripeAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerStripeAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertCustomerStripeAppDataResponse, error) + + // CreateCustomerStripePortalSessionWithBodyWithResponse request with any body + CreateCustomerStripePortalSessionWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerStripePortalSessionResponse, error) + + CreateCustomerStripePortalSessionWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerStripePortalSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerStripePortalSessionResponse, error) + + // ListCustomerSubscriptionsWithResponse request + ListCustomerSubscriptionsWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerSubscriptionsParams, reqEditors ...RequestEditorFn) (*ListCustomerSubscriptionsResponse, error) + + // GetDebugMetricsWithResponse request + GetDebugMetricsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetDebugMetricsResponse, error) + + // ListEntitlementsWithResponse request + ListEntitlementsWithResponse(ctx context.Context, params *ListEntitlementsParams, reqEditors ...RequestEditorFn) (*ListEntitlementsResponse, error) + + // GetEntitlementByIdWithResponse request + GetEntitlementByIdWithResponse(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*GetEntitlementByIdResponse, error) + + // ListEventsWithResponse request + ListEventsWithResponse(ctx context.Context, params *ListEventsParams, reqEditors ...RequestEditorFn) (*ListEventsResponse, error) + + // IngestEventsWithBodyWithResponse request with any body + IngestEventsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) + + IngestEventsWithApplicationCloudeventsPlusJSONBodyWithResponse(ctx context.Context, body IngestEventsApplicationCloudeventsPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) + + IngestEventsWithApplicationCloudeventsBatchPlusJSONBodyWithResponse(ctx context.Context, body IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) + + IngestEventsWithResponse(ctx context.Context, body IngestEventsJSONRequestBody, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) + + // ListFeaturesWithResponse request + ListFeaturesWithResponse(ctx context.Context, params *ListFeaturesParams, reqEditors ...RequestEditorFn) (*ListFeaturesResponse, error) + + // CreateFeatureWithBodyWithResponse request with any body + CreateFeatureWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateFeatureResponse, error) + + CreateFeatureWithResponse(ctx context.Context, body CreateFeatureJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateFeatureResponse, error) + + // DeleteFeatureWithResponse request + DeleteFeatureWithResponse(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*DeleteFeatureResponse, error) + + // GetFeatureWithResponse request + GetFeatureWithResponse(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*GetFeatureResponse, error) + + // ListGrantsWithResponse request + ListGrantsWithResponse(ctx context.Context, params *ListGrantsParams, reqEditors ...RequestEditorFn) (*ListGrantsResponse, error) + + // VoidGrantWithResponse request + VoidGrantWithResponse(ctx context.Context, grantId string, params *VoidGrantParams, reqEditors ...RequestEditorFn) (*VoidGrantResponse, error) + + // ListCurrenciesWithResponse request + ListCurrenciesWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListCurrenciesResponse, error) + + // GetProgressWithResponse request + GetProgressWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetProgressResponse, error) + + // ListMarketplaceListingsWithResponse request + ListMarketplaceListingsWithResponse(ctx context.Context, params *ListMarketplaceListingsParams, reqEditors ...RequestEditorFn) (*ListMarketplaceListingsResponse, error) + + // GetMarketplaceListingWithResponse request + GetMarketplaceListingWithResponse(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*GetMarketplaceListingResponse, error) + + // MarketplaceAppInstallWithBodyWithResponse request with any body + MarketplaceAppInstallWithBodyWithResponse(ctx context.Context, pType MarketplaceInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MarketplaceAppInstallResponse, error) + + MarketplaceAppInstallWithResponse(ctx context.Context, pType MarketplaceInstallRequestType, body MarketplaceAppInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*MarketplaceAppInstallResponse, error) + + // MarketplaceAppAPIKeyInstallWithBodyWithResponse request with any body + MarketplaceAppAPIKeyInstallWithBodyWithResponse(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MarketplaceAppAPIKeyInstallResponse, error) + + MarketplaceAppAPIKeyInstallWithResponse(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, body MarketplaceAppAPIKeyInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*MarketplaceAppAPIKeyInstallResponse, error) + + // MarketplaceOAuth2InstallGetURLWithResponse request + MarketplaceOAuth2InstallGetURLWithResponse(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*MarketplaceOAuth2InstallGetURLResponse, error) + + // MarketplaceOAuth2InstallAuthorizeWithResponse request + MarketplaceOAuth2InstallAuthorizeWithResponse(ctx context.Context, pType MarketplaceOAuth2InstallAuthorizeRequestType, params *MarketplaceOAuth2InstallAuthorizeParams, reqEditors ...RequestEditorFn) (*MarketplaceOAuth2InstallAuthorizeResponse, error) + + // ListMetersWithResponse request + ListMetersWithResponse(ctx context.Context, params *ListMetersParams, reqEditors ...RequestEditorFn) (*ListMetersResponse, error) + + // CreateMeterWithBodyWithResponse request with any body + CreateMeterWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateMeterResponse, error) + + CreateMeterWithResponse(ctx context.Context, body CreateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateMeterResponse, error) + + // DeleteMeterWithResponse request + DeleteMeterWithResponse(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*DeleteMeterResponse, error) + + // GetMeterWithResponse request + GetMeterWithResponse(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*GetMeterResponse, error) + + // UpdateMeterWithBodyWithResponse request with any body + UpdateMeterWithBodyWithResponse(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateMeterResponse, error) + + UpdateMeterWithResponse(ctx context.Context, meterIdOrSlug string, body UpdateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateMeterResponse, error) + + // ListMeterGroupByValuesWithResponse request + ListMeterGroupByValuesWithResponse(ctx context.Context, meterIdOrSlug string, groupByKey string, params *ListMeterGroupByValuesParams, reqEditors ...RequestEditorFn) (*ListMeterGroupByValuesResponse, error) + + // QueryMeterWithResponse request + QueryMeterWithResponse(ctx context.Context, meterIdOrSlug string, params *QueryMeterParams, reqEditors ...RequestEditorFn) (*QueryMeterResponse, error) + + // QueryMeterPostWithBodyWithResponse request with any body + QueryMeterPostWithBodyWithResponse(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*QueryMeterPostResponse, error) + + QueryMeterPostWithResponse(ctx context.Context, meterIdOrSlug string, body QueryMeterPostJSONRequestBody, reqEditors ...RequestEditorFn) (*QueryMeterPostResponse, error) + + // ListMeterSubjectsWithResponse request + ListMeterSubjectsWithResponse(ctx context.Context, meterIdOrSlug string, params *ListMeterSubjectsParams, reqEditors ...RequestEditorFn) (*ListMeterSubjectsResponse, error) + + // ListNotificationChannelsWithResponse request + ListNotificationChannelsWithResponse(ctx context.Context, params *ListNotificationChannelsParams, reqEditors ...RequestEditorFn) (*ListNotificationChannelsResponse, error) + + // CreateNotificationChannelWithBodyWithResponse request with any body + CreateNotificationChannelWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateNotificationChannelResponse, error) + + CreateNotificationChannelWithResponse(ctx context.Context, body CreateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateNotificationChannelResponse, error) + + // DeleteNotificationChannelWithResponse request + DeleteNotificationChannelWithResponse(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*DeleteNotificationChannelResponse, error) + + // GetNotificationChannelWithResponse request + GetNotificationChannelWithResponse(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*GetNotificationChannelResponse, error) + + // UpdateNotificationChannelWithBodyWithResponse request with any body + UpdateNotificationChannelWithBodyWithResponse(ctx context.Context, channelId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateNotificationChannelResponse, error) + + UpdateNotificationChannelWithResponse(ctx context.Context, channelId string, body UpdateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateNotificationChannelResponse, error) + + // ListNotificationEventsWithResponse request + ListNotificationEventsWithResponse(ctx context.Context, params *ListNotificationEventsParams, reqEditors ...RequestEditorFn) (*ListNotificationEventsResponse, error) + + // GetNotificationEventWithResponse request + GetNotificationEventWithResponse(ctx context.Context, eventId string, reqEditors ...RequestEditorFn) (*GetNotificationEventResponse, error) + + // ResendNotificationEventWithBodyWithResponse request with any body + ResendNotificationEventWithBodyWithResponse(ctx context.Context, eventId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ResendNotificationEventResponse, error) + + ResendNotificationEventWithResponse(ctx context.Context, eventId string, body ResendNotificationEventJSONRequestBody, reqEditors ...RequestEditorFn) (*ResendNotificationEventResponse, error) + + // ListNotificationRulesWithResponse request + ListNotificationRulesWithResponse(ctx context.Context, params *ListNotificationRulesParams, reqEditors ...RequestEditorFn) (*ListNotificationRulesResponse, error) + + // CreateNotificationRuleWithBodyWithResponse request with any body + CreateNotificationRuleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateNotificationRuleResponse, error) + + CreateNotificationRuleWithResponse(ctx context.Context, body CreateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateNotificationRuleResponse, error) + + // DeleteNotificationRuleWithResponse request + DeleteNotificationRuleWithResponse(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*DeleteNotificationRuleResponse, error) + + // GetNotificationRuleWithResponse request + GetNotificationRuleWithResponse(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*GetNotificationRuleResponse, error) + + // UpdateNotificationRuleWithBodyWithResponse request with any body + UpdateNotificationRuleWithBodyWithResponse(ctx context.Context, ruleId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateNotificationRuleResponse, error) + + UpdateNotificationRuleWithResponse(ctx context.Context, ruleId string, body UpdateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateNotificationRuleResponse, error) + + // TestNotificationRuleWithResponse request + TestNotificationRuleWithResponse(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*TestNotificationRuleResponse, error) + + // ListPlansWithResponse request + ListPlansWithResponse(ctx context.Context, params *ListPlansParams, reqEditors ...RequestEditorFn) (*ListPlansResponse, error) + + // CreatePlanWithBodyWithResponse request with any body + CreatePlanWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePlanResponse, error) + + CreatePlanWithResponse(ctx context.Context, body CreatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePlanResponse, error) + + // NextPlanWithResponse request + NextPlanWithResponse(ctx context.Context, planIdOrKey string, reqEditors ...RequestEditorFn) (*NextPlanResponse, error) + + // DeletePlanWithResponse request + DeletePlanWithResponse(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*DeletePlanResponse, error) + + // GetPlanWithResponse request + GetPlanWithResponse(ctx context.Context, planId string, params *GetPlanParams, reqEditors ...RequestEditorFn) (*GetPlanResponse, error) + + // UpdatePlanWithBodyWithResponse request with any body + UpdatePlanWithBodyWithResponse(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdatePlanResponse, error) + + UpdatePlanWithResponse(ctx context.Context, planId string, body UpdatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdatePlanResponse, error) + + // ListPlanAddonsWithResponse request + ListPlanAddonsWithResponse(ctx context.Context, planId string, params *ListPlanAddonsParams, reqEditors ...RequestEditorFn) (*ListPlanAddonsResponse, error) + + // CreatePlanAddonWithBodyWithResponse request with any body + CreatePlanAddonWithBodyWithResponse(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePlanAddonResponse, error) + + CreatePlanAddonWithResponse(ctx context.Context, planId string, body CreatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePlanAddonResponse, error) + + // DeletePlanAddonWithResponse request + DeletePlanAddonWithResponse(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*DeletePlanAddonResponse, error) + + // GetPlanAddonWithResponse request + GetPlanAddonWithResponse(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*GetPlanAddonResponse, error) + + // UpdatePlanAddonWithBodyWithResponse request with any body + UpdatePlanAddonWithBodyWithResponse(ctx context.Context, planId string, planAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdatePlanAddonResponse, error) + + UpdatePlanAddonWithResponse(ctx context.Context, planId string, planAddonId string, body UpdatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdatePlanAddonResponse, error) + + // ArchivePlanWithResponse request + ArchivePlanWithResponse(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*ArchivePlanResponse, error) + + // PublishPlanWithResponse request + PublishPlanWithResponse(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*PublishPlanResponse, error) + + // QueryPortalMeterWithResponse request + QueryPortalMeterWithResponse(ctx context.Context, meterSlug string, params *QueryPortalMeterParams, reqEditors ...RequestEditorFn) (*QueryPortalMeterResponse, error) + + // ListPortalTokensWithResponse request + ListPortalTokensWithResponse(ctx context.Context, params *ListPortalTokensParams, reqEditors ...RequestEditorFn) (*ListPortalTokensResponse, error) + + // CreatePortalTokenWithBodyWithResponse request with any body + CreatePortalTokenWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePortalTokenResponse, error) + + CreatePortalTokenWithResponse(ctx context.Context, body CreatePortalTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePortalTokenResponse, error) + + // InvalidatePortalTokensWithBodyWithResponse request with any body + InvalidatePortalTokensWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*InvalidatePortalTokensResponse, error) + + InvalidatePortalTokensWithResponse(ctx context.Context, body InvalidatePortalTokensJSONRequestBody, reqEditors ...RequestEditorFn) (*InvalidatePortalTokensResponse, error) + + // CreateStripeCheckoutSessionWithBodyWithResponse request with any body + CreateStripeCheckoutSessionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateStripeCheckoutSessionResponse, error) + + CreateStripeCheckoutSessionWithResponse(ctx context.Context, body CreateStripeCheckoutSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateStripeCheckoutSessionResponse, error) + + // ListSubjectsWithResponse request + ListSubjectsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListSubjectsResponse, error) + + // UpsertSubjectWithBodyWithResponse request with any body + UpsertSubjectWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertSubjectResponse, error) + + UpsertSubjectWithResponse(ctx context.Context, body UpsertSubjectJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertSubjectResponse, error) + + // DeleteSubjectWithResponse request + DeleteSubjectWithResponse(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*DeleteSubjectResponse, error) + + // GetSubjectWithResponse request + GetSubjectWithResponse(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*GetSubjectResponse, error) + + // ListSubjectEntitlementsWithResponse request + ListSubjectEntitlementsWithResponse(ctx context.Context, subjectIdOrKey string, params *ListSubjectEntitlementsParams, reqEditors ...RequestEditorFn) (*ListSubjectEntitlementsResponse, error) + + // CreateEntitlementWithBodyWithResponse request with any body + CreateEntitlementWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateEntitlementResponse, error) + + CreateEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, body CreateEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateEntitlementResponse, error) + + // ListEntitlementGrantsWithResponse request + ListEntitlementGrantsWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *ListEntitlementGrantsParams, reqEditors ...RequestEditorFn) (*ListEntitlementGrantsResponse, error) + + // CreateGrantWithBodyWithResponse request with any body + CreateGrantWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateGrantResponse, error) + + CreateGrantWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body CreateGrantJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateGrantResponse, error) + + // OverrideEntitlementWithBodyWithResponse request with any body + OverrideEntitlementWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*OverrideEntitlementResponse, error) + + OverrideEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body OverrideEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*OverrideEntitlementResponse, error) + + // GetEntitlementValueWithResponse request + GetEntitlementValueWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *GetEntitlementValueParams, reqEditors ...RequestEditorFn) (*GetEntitlementValueResponse, error) + + // DeleteEntitlementWithResponse request + DeleteEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*DeleteEntitlementResponse, error) + + // GetEntitlementWithResponse request + GetEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*GetEntitlementResponse, error) + + // GetEntitlementHistoryWithResponse request + GetEntitlementHistoryWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, params *GetEntitlementHistoryParams, reqEditors ...RequestEditorFn) (*GetEntitlementHistoryResponse, error) + + // ResetEntitlementUsageWithBodyWithResponse request with any body + ResetEntitlementUsageWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ResetEntitlementUsageResponse, error) + + ResetEntitlementUsageWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, body ResetEntitlementUsageJSONRequestBody, reqEditors ...RequestEditorFn) (*ResetEntitlementUsageResponse, error) + + // CreateSubscriptionWithBodyWithResponse request with any body + CreateSubscriptionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateSubscriptionResponse, error) + + CreateSubscriptionWithResponse(ctx context.Context, body CreateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateSubscriptionResponse, error) + + // DeleteSubscriptionWithResponse request + DeleteSubscriptionWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*DeleteSubscriptionResponse, error) + + // GetSubscriptionWithResponse request + GetSubscriptionWithResponse(ctx context.Context, subscriptionId string, params *GetSubscriptionParams, reqEditors ...RequestEditorFn) (*GetSubscriptionResponse, error) + + // EditSubscriptionWithBodyWithResponse request with any body + EditSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*EditSubscriptionResponse, error) + + EditSubscriptionWithResponse(ctx context.Context, subscriptionId string, body EditSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*EditSubscriptionResponse, error) + + // ListSubscriptionAddonsWithResponse request + ListSubscriptionAddonsWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*ListSubscriptionAddonsResponse, error) + + // CreateSubscriptionAddonWithBodyWithResponse request with any body + CreateSubscriptionAddonWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateSubscriptionAddonResponse, error) + + CreateSubscriptionAddonWithResponse(ctx context.Context, subscriptionId string, body CreateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateSubscriptionAddonResponse, error) + + // GetSubscriptionAddonWithResponse request + GetSubscriptionAddonWithResponse(ctx context.Context, subscriptionId string, subscriptionAddonId string, reqEditors ...RequestEditorFn) (*GetSubscriptionAddonResponse, error) + + // UpdateSubscriptionAddonWithBodyWithResponse request with any body + UpdateSubscriptionAddonWithBodyWithResponse(ctx context.Context, subscriptionId string, subscriptionAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateSubscriptionAddonResponse, error) + + UpdateSubscriptionAddonWithResponse(ctx context.Context, subscriptionId string, subscriptionAddonId string, body UpdateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateSubscriptionAddonResponse, error) + + // CancelSubscriptionWithBodyWithResponse request with any body + CancelSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CancelSubscriptionResponse, error) + + CancelSubscriptionWithResponse(ctx context.Context, subscriptionId string, body CancelSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*CancelSubscriptionResponse, error) + + // ChangeSubscriptionWithBodyWithResponse request with any body + ChangeSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ChangeSubscriptionResponse, error) + + ChangeSubscriptionWithResponse(ctx context.Context, subscriptionId string, body ChangeSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*ChangeSubscriptionResponse, error) + + // MigrateSubscriptionWithBodyWithResponse request with any body + MigrateSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MigrateSubscriptionResponse, error) + + MigrateSubscriptionWithResponse(ctx context.Context, subscriptionId string, body MigrateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*MigrateSubscriptionResponse, error) + + // RestoreSubscriptionWithResponse request + RestoreSubscriptionWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*RestoreSubscriptionResponse, error) + + // UnscheduleCancelationWithResponse request + UnscheduleCancelationWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*UnscheduleCancelationResponse, error) + + // ListCustomerEntitlementsV2WithResponse request + ListCustomerEntitlementsV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerEntitlementsV2Params, reqEditors ...RequestEditorFn) (*ListCustomerEntitlementsV2Response, error) + + // CreateCustomerEntitlementV2WithBodyWithResponse request with any body + CreateCustomerEntitlementV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementV2Response, error) + + CreateCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementV2Response, error) + + // DeleteCustomerEntitlementV2WithResponse request + DeleteCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*DeleteCustomerEntitlementV2Response, error) + + // GetCustomerEntitlementV2WithResponse request + GetCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementV2Response, error) + + // ListCustomerEntitlementGrantsV2WithResponse request + ListCustomerEntitlementGrantsV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *ListCustomerEntitlementGrantsV2Params, reqEditors ...RequestEditorFn) (*ListCustomerEntitlementGrantsV2Response, error) + + // CreateCustomerEntitlementGrantV2WithBodyWithResponse request with any body + CreateCustomerEntitlementGrantV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementGrantV2Response, error) + + CreateCustomerEntitlementGrantV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body CreateCustomerEntitlementGrantV2JSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementGrantV2Response, error) + + // GetCustomerEntitlementHistoryV2WithResponse request + GetCustomerEntitlementHistoryV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementHistoryV2Params, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementHistoryV2Response, error) + + // OverrideCustomerEntitlementV2WithBodyWithResponse request with any body + OverrideCustomerEntitlementV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*OverrideCustomerEntitlementV2Response, error) + + OverrideCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, body OverrideCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*OverrideCustomerEntitlementV2Response, error) + + // ResetCustomerEntitlementUsageV2WithBodyWithResponse request with any body + ResetCustomerEntitlementUsageV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ResetCustomerEntitlementUsageV2Response, error) + + ResetCustomerEntitlementUsageV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body ResetCustomerEntitlementUsageV2JSONRequestBody, reqEditors ...RequestEditorFn) (*ResetCustomerEntitlementUsageV2Response, error) + + // GetCustomerEntitlementValueV2WithResponse request + GetCustomerEntitlementValueV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementValueV2Params, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementValueV2Response, error) + + // ListEntitlementsV2WithResponse request + ListEntitlementsV2WithResponse(ctx context.Context, params *ListEntitlementsV2Params, reqEditors ...RequestEditorFn) (*ListEntitlementsV2Response, error) + + // GetEntitlementByIdV2WithResponse request + GetEntitlementByIdV2WithResponse(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*GetEntitlementByIdV2Response, error) + + // ListEventsV2WithResponse request + ListEventsV2WithResponse(ctx context.Context, params *ListEventsV2Params, reqEditors ...RequestEditorFn) (*ListEventsV2Response, error) + + // ListGrantsV2WithResponse request + ListGrantsV2WithResponse(ctx context.Context, params *ListGrantsV2Params, reqEditors ...RequestEditorFn) (*ListGrantsV2Response, error) +} + +type ListAddonsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *AddonPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListAddonsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListAddonsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Addon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteAddonResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Addon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Addon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ArchiveAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Addon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ArchiveAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ArchiveAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PublishAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Addon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r PublishAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PublishAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListAppsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *AppPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListAppsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListAppsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type AppCustomInvoicingDraftSynchronizedResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r AppCustomInvoicingDraftSynchronizedResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AppCustomInvoicingDraftSynchronizedResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type AppCustomInvoicingIssuingSynchronizedResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r AppCustomInvoicingIssuingSynchronizedResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AppCustomInvoicingIssuingSynchronizedResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type AppCustomInvoicingUpdatePaymentStatusResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r AppCustomInvoicingUpdatePaymentStatusResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AppCustomInvoicingUpdatePaymentStatusResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UninstallAppResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UninstallAppResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UninstallAppResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetAppResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *App + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetAppResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetAppResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateAppResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *App + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateAppResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateAppResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateStripeAPIKeyResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateStripeAPIKeyResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateStripeAPIKeyResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type AppStripeWebhookResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *StripeWebhookResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r AppStripeWebhookResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AppStripeWebhookResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListBillingProfileCustomerOverridesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BillingProfileCustomerOverrideWithDetailsPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListBillingProfileCustomerOverridesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListBillingProfileCustomerOverridesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteBillingProfileCustomerOverrideResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteBillingProfileCustomerOverrideResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteBillingProfileCustomerOverrideResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetBillingProfileCustomerOverrideResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BillingProfileCustomerOverrideWithDetails + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetBillingProfileCustomerOverrideResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetBillingProfileCustomerOverrideResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpsertBillingProfileCustomerOverrideResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BillingProfileCustomerOverrideWithDetails + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpsertBillingProfileCustomerOverrideResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpsertBillingProfileCustomerOverrideResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreatePendingInvoiceLineResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *InvoicePendingLineCreateResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreatePendingInvoiceLineResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreatePendingInvoiceLineResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type SimulateInvoiceResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r SimulateInvoiceResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SimulateInvoiceResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListInvoicesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *InvoicePaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListInvoicesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListInvoicesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type InvoicePendingLinesActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *[]Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r InvoicePendingLinesActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InvoicePendingLinesActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteInvoiceResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteInvoiceResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteInvoiceResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetInvoiceResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetInvoiceResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetInvoiceResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateInvoiceResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateInvoiceResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateInvoiceResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type AdvanceInvoiceActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r AdvanceInvoiceActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r AdvanceInvoiceActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ApproveInvoiceActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ApproveInvoiceActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ApproveInvoiceActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type RetryInvoiceActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r RetryInvoiceActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RetryInvoiceActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type SnapshotQuantitiesInvoiceActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r SnapshotQuantitiesInvoiceActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SnapshotQuantitiesInvoiceActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type RecalculateInvoiceTaxActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r RecalculateInvoiceTaxActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RecalculateInvoiceTaxActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type VoidInvoiceActionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Invoice + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r VoidInvoiceActionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r VoidInvoiceActionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListBillingProfilesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BillingProfilePaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListBillingProfilesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListBillingProfilesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateBillingProfileResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *BillingProfile + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateBillingProfileResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateBillingProfileResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteBillingProfileResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteBillingProfileResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteBillingProfileResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetBillingProfileResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BillingProfile + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetBillingProfileResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetBillingProfileResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateBillingProfileResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *BillingProfile + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateBillingProfileResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateBillingProfileResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListCustomersResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CustomerPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListCustomersResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListCustomersResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateCustomerResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Customer + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateCustomerResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateCustomerResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteCustomerResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteCustomerResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteCustomerResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Customer + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateCustomerResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Customer + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateCustomerResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateCustomerResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerAccessResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CustomerAccess + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerAccessResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerAccessResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListCustomerAppDataResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *CustomerAppDataPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListCustomerAppDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListCustomerAppDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpsertCustomerAppDataResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]CustomerAppData + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpsertCustomerAppDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpsertCustomerAppDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteCustomerAppDataResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteCustomerAppDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteCustomerAppDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerEntitlementValueResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementValue + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerEntitlementValueResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerEntitlementValueResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerStripeAppDataResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *StripeCustomerAppData + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerStripeAppDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerStripeAppDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpsertCustomerStripeAppDataResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *StripeCustomerAppData + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpsertCustomerStripeAppDataResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpsertCustomerStripeAppDataResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateCustomerStripePortalSessionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *StripeCustomerPortalSession + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateCustomerStripePortalSessionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateCustomerStripePortalSessionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListCustomerSubscriptionsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *SubscriptionPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListCustomerSubscriptionsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListCustomerSubscriptionsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetDebugMetricsResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetDebugMetricsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetDebugMetricsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListEntitlementsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *ListEntitlementsResult + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListEntitlementsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListEntitlementsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEntitlementByIdResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Entitlement + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetEntitlementByIdResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEntitlementByIdResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListEventsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]IngestedEvent + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListEventsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListEventsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type IngestEventsResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r IngestEventsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r IngestEventsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListFeaturesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *ListFeaturesResult + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListFeaturesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListFeaturesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateFeatureResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Feature + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateFeatureResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateFeatureResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteFeatureResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteFeatureResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteFeatureResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetFeatureResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Feature + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetFeatureResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetFeatureResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListGrantsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *struct { + union json.RawMessage + } + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} +type ListGrants2000 = []EntitlementGrant + +// Status returns HTTPResponse.Status +func (r ListGrantsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListGrantsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type VoidGrantResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r VoidGrantResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r VoidGrantResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListCurrenciesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]Currency + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListCurrenciesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListCurrenciesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetProgressResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Progress + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetProgressResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetProgressResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListMarketplaceListingsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MarketplaceListingPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListMarketplaceListingsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMarketplaceListingsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetMarketplaceListingResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MarketplaceListing + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetMarketplaceListingResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMarketplaceListingResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type MarketplaceAppInstallResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MarketplaceInstallResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r MarketplaceAppInstallResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r MarketplaceAppInstallResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type MarketplaceAppAPIKeyInstallResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MarketplaceInstallResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r MarketplaceAppAPIKeyInstallResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r MarketplaceAppAPIKeyInstallResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type MarketplaceOAuth2InstallGetURLResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *ClientAppStartResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r MarketplaceOAuth2InstallGetURLResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r MarketplaceOAuth2InstallGetURLResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type MarketplaceOAuth2InstallAuthorizeResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r MarketplaceOAuth2InstallAuthorizeResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r MarketplaceOAuth2InstallAuthorizeResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListMetersResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]Meter + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListMetersResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMetersResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateMeterResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Meter + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateMeterResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateMeterResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteMeterResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteMeterResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteMeterResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetMeterResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Meter + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetMeterResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetMeterResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateMeterResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Meter + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateMeterResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateMeterResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListMeterGroupByValuesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]string + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListMeterGroupByValuesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMeterGroupByValuesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type QueryMeterResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MeterQueryResult + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r QueryMeterResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r QueryMeterResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type QueryMeterPostResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MeterQueryResult + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r QueryMeterPostResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r QueryMeterPostResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListMeterSubjectsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]string + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListMeterSubjectsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListMeterSubjectsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListNotificationChannelsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationChannelPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListNotificationChannelsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListNotificationChannelsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateNotificationChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *NotificationChannel + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateNotificationChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateNotificationChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteNotificationChannelResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteNotificationChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteNotificationChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNotificationChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationChannel + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetNotificationChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNotificationChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateNotificationChannelResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationChannel + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateNotificationChannelResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateNotificationChannelResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListNotificationEventsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationEventPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListNotificationEventsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListNotificationEventsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNotificationEventResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationEvent + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetNotificationEventResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNotificationEventResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ResendNotificationEventResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ResendNotificationEventResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ResendNotificationEventResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListNotificationRulesResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationRulePaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListNotificationRulesResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListNotificationRulesResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateNotificationRuleResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *NotificationRule + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateNotificationRuleResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateNotificationRuleResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteNotificationRuleResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteNotificationRuleResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteNotificationRuleResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetNotificationRuleResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationRule + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetNotificationRuleResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetNotificationRuleResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateNotificationRuleResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *NotificationRule + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateNotificationRuleResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateNotificationRuleResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type TestNotificationRuleResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *NotificationEvent + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r TestNotificationRuleResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r TestNotificationRuleResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListPlansResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PlanPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListPlansResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListPlansResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreatePlanResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Plan + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreatePlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreatePlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type NextPlanResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Plan + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r NextPlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r NextPlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeletePlanResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeletePlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeletePlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetPlanResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Plan + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetPlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetPlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdatePlanResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Plan + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdatePlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdatePlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListPlanAddonsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PlanAddonPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListPlanAddonsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListPlanAddonsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreatePlanAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *PlanAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreatePlanAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreatePlanAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeletePlanAddonResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeletePlanAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeletePlanAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetPlanAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PlanAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetPlanAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetPlanAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdatePlanAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PlanAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdatePlanAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdatePlanAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ArchivePlanResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Plan + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ArchivePlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ArchivePlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type PublishPlanResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Plan + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r PublishPlanResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r PublishPlanResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type QueryPortalMeterResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *MeterQueryResult + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r QueryPortalMeterResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r QueryPortalMeterResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListPortalTokensResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]PortalToken + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListPortalTokensResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListPortalTokensResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreatePortalTokenResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *PortalToken + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreatePortalTokenResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreatePortalTokenResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type InvalidatePortalTokensResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r InvalidatePortalTokensResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r InvalidatePortalTokensResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateStripeCheckoutSessionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *CreateStripeCheckoutSessionResult + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateStripeCheckoutSessionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateStripeCheckoutSessionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListSubjectsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]Subject + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListSubjectsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListSubjectsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpsertSubjectResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]Subject + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpsertSubjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpsertSubjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteSubjectResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteSubjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteSubjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetSubjectResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Subject + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetSubjectResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetSubjectResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListSubjectEntitlementsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]Entitlement + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListSubjectEntitlementsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListSubjectEntitlementsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateEntitlementResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Entitlement + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateEntitlementResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateEntitlementResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListEntitlementGrantsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]EntitlementGrant + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListEntitlementGrantsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListEntitlementGrantsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateGrantResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *EntitlementGrant + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateGrantResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateGrantResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type OverrideEntitlementResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Entitlement + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r OverrideEntitlementResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r OverrideEntitlementResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEntitlementValueResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementValue + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetEntitlementValueResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEntitlementValueResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteEntitlementResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteEntitlementResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteEntitlementResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEntitlementResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Entitlement + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetEntitlementResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEntitlementResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEntitlementHistoryResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *WindowedBalanceHistory + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetEntitlementHistoryResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEntitlementHistoryResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ResetEntitlementUsageResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ResetEntitlementUsageResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ResetEntitlementUsageResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *Subscription + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *SubscriptionExpanded + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type EditSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Subscription + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r EditSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r EditSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListSubscriptionAddonsResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *[]SubscriptionAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListSubscriptionAddonsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListSubscriptionAddonsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateSubscriptionAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON201 *SubscriptionAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateSubscriptionAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateSubscriptionAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetSubscriptionAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *SubscriptionAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetSubscriptionAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetSubscriptionAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UpdateSubscriptionAddonResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *SubscriptionAddon + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UpdateSubscriptionAddonResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UpdateSubscriptionAddonResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CancelSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Subscription + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CancelSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CancelSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ChangeSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *SubscriptionChangeResponseBody + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ChangeSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ChangeSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type MigrateSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *SubscriptionChangeResponseBody + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r MigrateSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r MigrateSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type RestoreSubscriptionResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Subscription + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r RestoreSubscriptionResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r RestoreSubscriptionResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type UnscheduleCancelationResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *Subscription + ApplicationproblemJSON400 *SubscriptionBadRequestErrorResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *SubscriptionConflictErrorResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r UnscheduleCancelationResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r UnscheduleCancelationResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListCustomerEntitlementsV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementV2PaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListCustomerEntitlementsV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListCustomerEntitlementsV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateCustomerEntitlementV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON201 *EntitlementV2 + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateCustomerEntitlementV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateCustomerEntitlementV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type DeleteCustomerEntitlementV2Response struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r DeleteCustomerEntitlementV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r DeleteCustomerEntitlementV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerEntitlementV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementV2 + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerEntitlementV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerEntitlementV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListCustomerEntitlementGrantsV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *GrantV2PaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListCustomerEntitlementGrantsV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListCustomerEntitlementGrantsV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type CreateCustomerEntitlementGrantV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON201 *EntitlementGrantV2 + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r CreateCustomerEntitlementGrantV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateCustomerEntitlementGrantV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerEntitlementHistoryV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *WindowedBalanceHistory + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerEntitlementHistoryV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerEntitlementHistoryV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type OverrideCustomerEntitlementV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON201 *EntitlementV2 + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON409 *ConflictProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r OverrideCustomerEntitlementV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r OverrideCustomerEntitlementV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ResetCustomerEntitlementUsageV2Response struct { + Body []byte + HTTPResponse *http.Response + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ResetCustomerEntitlementUsageV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ResetCustomerEntitlementUsageV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetCustomerEntitlementValueV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementValueV2 + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetCustomerEntitlementValueV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetCustomerEntitlementValueV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListEntitlementsV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementV2PaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListEntitlementsV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListEntitlementsV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type GetEntitlementByIdV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *EntitlementV2 + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON404 *NotFoundProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r GetEntitlementByIdV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetEntitlementByIdV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListEventsV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *IngestedEventCursorPaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListEventsV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListEventsV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +type ListGrantsV2Response struct { + Body []byte + HTTPResponse *http.Response + JSON200 *GrantV2PaginatedResponse + ApplicationproblemJSON400 *BadRequestProblemResponse + ApplicationproblemJSON401 *UnauthorizedProblemResponse + ApplicationproblemJSON403 *ForbiddenProblemResponse + ApplicationproblemJSON412 *PreconditionFailedProblemResponse + ApplicationproblemJSON500 *InternalServerErrorProblemResponse + ApplicationproblemJSON503 *ServiceUnavailableProblemResponse + ApplicationproblemJSONDefault *UnexpectedProblemResponse +} + +// Status returns HTTPResponse.Status +func (r ListGrantsV2Response) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListGrantsV2Response) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ListAddonsWithResponse request returning *ListAddonsResponse +func (c *ClientWithResponses) ListAddonsWithResponse(ctx context.Context, params *ListAddonsParams, reqEditors ...RequestEditorFn) (*ListAddonsResponse, error) { + rsp, err := c.ListAddons(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListAddonsResponse(rsp) +} + +// CreateAddonWithBodyWithResponse request with arbitrary body returning *CreateAddonResponse +func (c *ClientWithResponses) CreateAddonWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateAddonResponse, error) { + rsp, err := c.CreateAddonWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateAddonResponse(rsp) +} + +func (c *ClientWithResponses) CreateAddonWithResponse(ctx context.Context, body CreateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateAddonResponse, error) { + rsp, err := c.CreateAddon(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateAddonResponse(rsp) +} + +// DeleteAddonWithResponse request returning *DeleteAddonResponse +func (c *ClientWithResponses) DeleteAddonWithResponse(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*DeleteAddonResponse, error) { + rsp, err := c.DeleteAddon(ctx, addonId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteAddonResponse(rsp) +} + +// GetAddonWithResponse request returning *GetAddonResponse +func (c *ClientWithResponses) GetAddonWithResponse(ctx context.Context, addonId string, params *GetAddonParams, reqEditors ...RequestEditorFn) (*GetAddonResponse, error) { + rsp, err := c.GetAddon(ctx, addonId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetAddonResponse(rsp) +} + +// UpdateAddonWithBodyWithResponse request with arbitrary body returning *UpdateAddonResponse +func (c *ClientWithResponses) UpdateAddonWithBodyWithResponse(ctx context.Context, addonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateAddonResponse, error) { + rsp, err := c.UpdateAddonWithBody(ctx, addonId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateAddonResponse(rsp) +} + +func (c *ClientWithResponses) UpdateAddonWithResponse(ctx context.Context, addonId string, body UpdateAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateAddonResponse, error) { + rsp, err := c.UpdateAddon(ctx, addonId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateAddonResponse(rsp) +} + +// ArchiveAddonWithResponse request returning *ArchiveAddonResponse +func (c *ClientWithResponses) ArchiveAddonWithResponse(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*ArchiveAddonResponse, error) { + rsp, err := c.ArchiveAddon(ctx, addonId, reqEditors...) + if err != nil { + return nil, err + } + return ParseArchiveAddonResponse(rsp) +} + +// PublishAddonWithResponse request returning *PublishAddonResponse +func (c *ClientWithResponses) PublishAddonWithResponse(ctx context.Context, addonId string, reqEditors ...RequestEditorFn) (*PublishAddonResponse, error) { + rsp, err := c.PublishAddon(ctx, addonId, reqEditors...) + if err != nil { + return nil, err + } + return ParsePublishAddonResponse(rsp) +} + +// ListAppsWithResponse request returning *ListAppsResponse +func (c *ClientWithResponses) ListAppsWithResponse(ctx context.Context, params *ListAppsParams, reqEditors ...RequestEditorFn) (*ListAppsResponse, error) { + rsp, err := c.ListApps(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListAppsResponse(rsp) +} + +// AppCustomInvoicingDraftSynchronizedWithBodyWithResponse request with arbitrary body returning *AppCustomInvoicingDraftSynchronizedResponse +func (c *ClientWithResponses) AppCustomInvoicingDraftSynchronizedWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppCustomInvoicingDraftSynchronizedResponse, error) { + rsp, err := c.AppCustomInvoicingDraftSynchronizedWithBody(ctx, invoiceId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppCustomInvoicingDraftSynchronizedResponse(rsp) +} + +func (c *ClientWithResponses) AppCustomInvoicingDraftSynchronizedWithResponse(ctx context.Context, invoiceId string, body AppCustomInvoicingDraftSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*AppCustomInvoicingDraftSynchronizedResponse, error) { + rsp, err := c.AppCustomInvoicingDraftSynchronized(ctx, invoiceId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppCustomInvoicingDraftSynchronizedResponse(rsp) +} + +// AppCustomInvoicingIssuingSynchronizedWithBodyWithResponse request with arbitrary body returning *AppCustomInvoicingIssuingSynchronizedResponse +func (c *ClientWithResponses) AppCustomInvoicingIssuingSynchronizedWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppCustomInvoicingIssuingSynchronizedResponse, error) { + rsp, err := c.AppCustomInvoicingIssuingSynchronizedWithBody(ctx, invoiceId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppCustomInvoicingIssuingSynchronizedResponse(rsp) +} + +func (c *ClientWithResponses) AppCustomInvoicingIssuingSynchronizedWithResponse(ctx context.Context, invoiceId string, body AppCustomInvoicingIssuingSynchronizedJSONRequestBody, reqEditors ...RequestEditorFn) (*AppCustomInvoicingIssuingSynchronizedResponse, error) { + rsp, err := c.AppCustomInvoicingIssuingSynchronized(ctx, invoiceId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppCustomInvoicingIssuingSynchronizedResponse(rsp) +} + +// AppCustomInvoicingUpdatePaymentStatusWithBodyWithResponse request with arbitrary body returning *AppCustomInvoicingUpdatePaymentStatusResponse +func (c *ClientWithResponses) AppCustomInvoicingUpdatePaymentStatusWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppCustomInvoicingUpdatePaymentStatusResponse, error) { + rsp, err := c.AppCustomInvoicingUpdatePaymentStatusWithBody(ctx, invoiceId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppCustomInvoicingUpdatePaymentStatusResponse(rsp) +} + +func (c *ClientWithResponses) AppCustomInvoicingUpdatePaymentStatusWithResponse(ctx context.Context, invoiceId string, body AppCustomInvoicingUpdatePaymentStatusJSONRequestBody, reqEditors ...RequestEditorFn) (*AppCustomInvoicingUpdatePaymentStatusResponse, error) { + rsp, err := c.AppCustomInvoicingUpdatePaymentStatus(ctx, invoiceId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppCustomInvoicingUpdatePaymentStatusResponse(rsp) +} + +// UninstallAppWithResponse request returning *UninstallAppResponse +func (c *ClientWithResponses) UninstallAppWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*UninstallAppResponse, error) { + rsp, err := c.UninstallApp(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseUninstallAppResponse(rsp) +} + +// GetAppWithResponse request returning *GetAppResponse +func (c *ClientWithResponses) GetAppWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetAppResponse, error) { + rsp, err := c.GetApp(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetAppResponse(rsp) +} + +// UpdateAppWithBodyWithResponse request with arbitrary body returning *UpdateAppResponse +func (c *ClientWithResponses) UpdateAppWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateAppResponse, error) { + rsp, err := c.UpdateAppWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateAppResponse(rsp) +} + +func (c *ClientWithResponses) UpdateAppWithResponse(ctx context.Context, id string, body UpdateAppJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateAppResponse, error) { + rsp, err := c.UpdateApp(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateAppResponse(rsp) +} + +// UpdateStripeAPIKeyWithBodyWithResponse request with arbitrary body returning *UpdateStripeAPIKeyResponse +func (c *ClientWithResponses) UpdateStripeAPIKeyWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateStripeAPIKeyResponse, error) { + rsp, err := c.UpdateStripeAPIKeyWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateStripeAPIKeyResponse(rsp) +} + +func (c *ClientWithResponses) UpdateStripeAPIKeyWithResponse(ctx context.Context, id string, body UpdateStripeAPIKeyJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateStripeAPIKeyResponse, error) { + rsp, err := c.UpdateStripeAPIKey(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateStripeAPIKeyResponse(rsp) +} + +// AppStripeWebhookWithBodyWithResponse request with arbitrary body returning *AppStripeWebhookResponse +func (c *ClientWithResponses) AppStripeWebhookWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*AppStripeWebhookResponse, error) { + rsp, err := c.AppStripeWebhookWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppStripeWebhookResponse(rsp) +} + +func (c *ClientWithResponses) AppStripeWebhookWithResponse(ctx context.Context, id string, body AppStripeWebhookJSONRequestBody, reqEditors ...RequestEditorFn) (*AppStripeWebhookResponse, error) { + rsp, err := c.AppStripeWebhook(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseAppStripeWebhookResponse(rsp) +} + +// ListBillingProfileCustomerOverridesWithResponse request returning *ListBillingProfileCustomerOverridesResponse +func (c *ClientWithResponses) ListBillingProfileCustomerOverridesWithResponse(ctx context.Context, params *ListBillingProfileCustomerOverridesParams, reqEditors ...RequestEditorFn) (*ListBillingProfileCustomerOverridesResponse, error) { + rsp, err := c.ListBillingProfileCustomerOverrides(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListBillingProfileCustomerOverridesResponse(rsp) +} + +// DeleteBillingProfileCustomerOverrideWithResponse request returning *DeleteBillingProfileCustomerOverrideResponse +func (c *ClientWithResponses) DeleteBillingProfileCustomerOverrideWithResponse(ctx context.Context, customerId string, reqEditors ...RequestEditorFn) (*DeleteBillingProfileCustomerOverrideResponse, error) { + rsp, err := c.DeleteBillingProfileCustomerOverride(ctx, customerId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteBillingProfileCustomerOverrideResponse(rsp) +} + +// GetBillingProfileCustomerOverrideWithResponse request returning *GetBillingProfileCustomerOverrideResponse +func (c *ClientWithResponses) GetBillingProfileCustomerOverrideWithResponse(ctx context.Context, customerId string, params *GetBillingProfileCustomerOverrideParams, reqEditors ...RequestEditorFn) (*GetBillingProfileCustomerOverrideResponse, error) { + rsp, err := c.GetBillingProfileCustomerOverride(ctx, customerId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetBillingProfileCustomerOverrideResponse(rsp) +} + +// UpsertBillingProfileCustomerOverrideWithBodyWithResponse request with arbitrary body returning *UpsertBillingProfileCustomerOverrideResponse +func (c *ClientWithResponses) UpsertBillingProfileCustomerOverrideWithBodyWithResponse(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertBillingProfileCustomerOverrideResponse, error) { + rsp, err := c.UpsertBillingProfileCustomerOverrideWithBody(ctx, customerId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertBillingProfileCustomerOverrideResponse(rsp) +} + +func (c *ClientWithResponses) UpsertBillingProfileCustomerOverrideWithResponse(ctx context.Context, customerId string, body UpsertBillingProfileCustomerOverrideJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertBillingProfileCustomerOverrideResponse, error) { + rsp, err := c.UpsertBillingProfileCustomerOverride(ctx, customerId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertBillingProfileCustomerOverrideResponse(rsp) +} + +// CreatePendingInvoiceLineWithBodyWithResponse request with arbitrary body returning *CreatePendingInvoiceLineResponse +func (c *ClientWithResponses) CreatePendingInvoiceLineWithBodyWithResponse(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePendingInvoiceLineResponse, error) { + rsp, err := c.CreatePendingInvoiceLineWithBody(ctx, customerId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePendingInvoiceLineResponse(rsp) +} + +func (c *ClientWithResponses) CreatePendingInvoiceLineWithResponse(ctx context.Context, customerId string, body CreatePendingInvoiceLineJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePendingInvoiceLineResponse, error) { + rsp, err := c.CreatePendingInvoiceLine(ctx, customerId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePendingInvoiceLineResponse(rsp) +} + +// SimulateInvoiceWithBodyWithResponse request with arbitrary body returning *SimulateInvoiceResponse +func (c *ClientWithResponses) SimulateInvoiceWithBodyWithResponse(ctx context.Context, customerId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*SimulateInvoiceResponse, error) { + rsp, err := c.SimulateInvoiceWithBody(ctx, customerId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSimulateInvoiceResponse(rsp) +} + +func (c *ClientWithResponses) SimulateInvoiceWithResponse(ctx context.Context, customerId string, body SimulateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*SimulateInvoiceResponse, error) { + rsp, err := c.SimulateInvoice(ctx, customerId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseSimulateInvoiceResponse(rsp) +} + +// ListInvoicesWithResponse request returning *ListInvoicesResponse +func (c *ClientWithResponses) ListInvoicesWithResponse(ctx context.Context, params *ListInvoicesParams, reqEditors ...RequestEditorFn) (*ListInvoicesResponse, error) { + rsp, err := c.ListInvoices(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListInvoicesResponse(rsp) +} + +// InvoicePendingLinesActionWithBodyWithResponse request with arbitrary body returning *InvoicePendingLinesActionResponse +func (c *ClientWithResponses) InvoicePendingLinesActionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*InvoicePendingLinesActionResponse, error) { + rsp, err := c.InvoicePendingLinesActionWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseInvoicePendingLinesActionResponse(rsp) +} + +func (c *ClientWithResponses) InvoicePendingLinesActionWithResponse(ctx context.Context, body InvoicePendingLinesActionJSONRequestBody, reqEditors ...RequestEditorFn) (*InvoicePendingLinesActionResponse, error) { + rsp, err := c.InvoicePendingLinesAction(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseInvoicePendingLinesActionResponse(rsp) +} + +// DeleteInvoiceWithResponse request returning *DeleteInvoiceResponse +func (c *ClientWithResponses) DeleteInvoiceWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*DeleteInvoiceResponse, error) { + rsp, err := c.DeleteInvoice(ctx, invoiceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteInvoiceResponse(rsp) +} + +// GetInvoiceWithResponse request returning *GetInvoiceResponse +func (c *ClientWithResponses) GetInvoiceWithResponse(ctx context.Context, invoiceId string, params *GetInvoiceParams, reqEditors ...RequestEditorFn) (*GetInvoiceResponse, error) { + rsp, err := c.GetInvoice(ctx, invoiceId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetInvoiceResponse(rsp) +} + +// UpdateInvoiceWithBodyWithResponse request with arbitrary body returning *UpdateInvoiceResponse +func (c *ClientWithResponses) UpdateInvoiceWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateInvoiceResponse, error) { + rsp, err := c.UpdateInvoiceWithBody(ctx, invoiceId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateInvoiceResponse(rsp) +} + +func (c *ClientWithResponses) UpdateInvoiceWithResponse(ctx context.Context, invoiceId string, body UpdateInvoiceJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateInvoiceResponse, error) { + rsp, err := c.UpdateInvoice(ctx, invoiceId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateInvoiceResponse(rsp) +} + +// AdvanceInvoiceActionWithResponse request returning *AdvanceInvoiceActionResponse +func (c *ClientWithResponses) AdvanceInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*AdvanceInvoiceActionResponse, error) { + rsp, err := c.AdvanceInvoiceAction(ctx, invoiceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseAdvanceInvoiceActionResponse(rsp) +} + +// ApproveInvoiceActionWithResponse request returning *ApproveInvoiceActionResponse +func (c *ClientWithResponses) ApproveInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*ApproveInvoiceActionResponse, error) { + rsp, err := c.ApproveInvoiceAction(ctx, invoiceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseApproveInvoiceActionResponse(rsp) +} + +// RetryInvoiceActionWithResponse request returning *RetryInvoiceActionResponse +func (c *ClientWithResponses) RetryInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*RetryInvoiceActionResponse, error) { + rsp, err := c.RetryInvoiceAction(ctx, invoiceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseRetryInvoiceActionResponse(rsp) +} + +// SnapshotQuantitiesInvoiceActionWithResponse request returning *SnapshotQuantitiesInvoiceActionResponse +func (c *ClientWithResponses) SnapshotQuantitiesInvoiceActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*SnapshotQuantitiesInvoiceActionResponse, error) { + rsp, err := c.SnapshotQuantitiesInvoiceAction(ctx, invoiceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseSnapshotQuantitiesInvoiceActionResponse(rsp) +} + +// RecalculateInvoiceTaxActionWithResponse request returning *RecalculateInvoiceTaxActionResponse +func (c *ClientWithResponses) RecalculateInvoiceTaxActionWithResponse(ctx context.Context, invoiceId string, reqEditors ...RequestEditorFn) (*RecalculateInvoiceTaxActionResponse, error) { + rsp, err := c.RecalculateInvoiceTaxAction(ctx, invoiceId, reqEditors...) + if err != nil { + return nil, err + } + return ParseRecalculateInvoiceTaxActionResponse(rsp) +} + +// VoidInvoiceActionWithBodyWithResponse request with arbitrary body returning *VoidInvoiceActionResponse +func (c *ClientWithResponses) VoidInvoiceActionWithBodyWithResponse(ctx context.Context, invoiceId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*VoidInvoiceActionResponse, error) { + rsp, err := c.VoidInvoiceActionWithBody(ctx, invoiceId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseVoidInvoiceActionResponse(rsp) +} + +func (c *ClientWithResponses) VoidInvoiceActionWithResponse(ctx context.Context, invoiceId string, body VoidInvoiceActionJSONRequestBody, reqEditors ...RequestEditorFn) (*VoidInvoiceActionResponse, error) { + rsp, err := c.VoidInvoiceAction(ctx, invoiceId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseVoidInvoiceActionResponse(rsp) +} + +// ListBillingProfilesWithResponse request returning *ListBillingProfilesResponse +func (c *ClientWithResponses) ListBillingProfilesWithResponse(ctx context.Context, params *ListBillingProfilesParams, reqEditors ...RequestEditorFn) (*ListBillingProfilesResponse, error) { + rsp, err := c.ListBillingProfiles(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListBillingProfilesResponse(rsp) +} + +// CreateBillingProfileWithBodyWithResponse request with arbitrary body returning *CreateBillingProfileResponse +func (c *ClientWithResponses) CreateBillingProfileWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateBillingProfileResponse, error) { + rsp, err := c.CreateBillingProfileWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateBillingProfileResponse(rsp) +} + +func (c *ClientWithResponses) CreateBillingProfileWithResponse(ctx context.Context, body CreateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateBillingProfileResponse, error) { + rsp, err := c.CreateBillingProfile(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateBillingProfileResponse(rsp) +} + +// DeleteBillingProfileWithResponse request returning *DeleteBillingProfileResponse +func (c *ClientWithResponses) DeleteBillingProfileWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*DeleteBillingProfileResponse, error) { + rsp, err := c.DeleteBillingProfile(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteBillingProfileResponse(rsp) +} + +// GetBillingProfileWithResponse request returning *GetBillingProfileResponse +func (c *ClientWithResponses) GetBillingProfileWithResponse(ctx context.Context, id string, params *GetBillingProfileParams, reqEditors ...RequestEditorFn) (*GetBillingProfileResponse, error) { + rsp, err := c.GetBillingProfile(ctx, id, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetBillingProfileResponse(rsp) +} + +// UpdateBillingProfileWithBodyWithResponse request with arbitrary body returning *UpdateBillingProfileResponse +func (c *ClientWithResponses) UpdateBillingProfileWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateBillingProfileResponse, error) { + rsp, err := c.UpdateBillingProfileWithBody(ctx, id, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateBillingProfileResponse(rsp) +} + +func (c *ClientWithResponses) UpdateBillingProfileWithResponse(ctx context.Context, id string, body UpdateBillingProfileJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateBillingProfileResponse, error) { + rsp, err := c.UpdateBillingProfile(ctx, id, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateBillingProfileResponse(rsp) +} + +// ListCustomersWithResponse request returning *ListCustomersResponse +func (c *ClientWithResponses) ListCustomersWithResponse(ctx context.Context, params *ListCustomersParams, reqEditors ...RequestEditorFn) (*ListCustomersResponse, error) { + rsp, err := c.ListCustomers(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListCustomersResponse(rsp) +} + +// CreateCustomerWithBodyWithResponse request with arbitrary body returning *CreateCustomerResponse +func (c *ClientWithResponses) CreateCustomerWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerResponse, error) { + rsp, err := c.CreateCustomerWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerResponse(rsp) +} + +func (c *ClientWithResponses) CreateCustomerWithResponse(ctx context.Context, body CreateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerResponse, error) { + rsp, err := c.CreateCustomer(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerResponse(rsp) +} + +// DeleteCustomerWithResponse request returning *DeleteCustomerResponse +func (c *ClientWithResponses) DeleteCustomerWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*DeleteCustomerResponse, error) { + rsp, err := c.DeleteCustomer(ctx, customerIdOrKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteCustomerResponse(rsp) +} + +// GetCustomerWithResponse request returning *GetCustomerResponse +func (c *ClientWithResponses) GetCustomerWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *GetCustomerParams, reqEditors ...RequestEditorFn) (*GetCustomerResponse, error) { + rsp, err := c.GetCustomer(ctx, customerIdOrKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerResponse(rsp) +} + +// UpdateCustomerWithBodyWithResponse request with arbitrary body returning *UpdateCustomerResponse +func (c *ClientWithResponses) UpdateCustomerWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateCustomerResponse, error) { + rsp, err := c.UpdateCustomerWithBody(ctx, customerIdOrKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateCustomerResponse(rsp) +} + +func (c *ClientWithResponses) UpdateCustomerWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpdateCustomerJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateCustomerResponse, error) { + rsp, err := c.UpdateCustomer(ctx, customerIdOrKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateCustomerResponse(rsp) +} + +// GetCustomerAccessWithResponse request returning *GetCustomerAccessResponse +func (c *ClientWithResponses) GetCustomerAccessWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*GetCustomerAccessResponse, error) { + rsp, err := c.GetCustomerAccess(ctx, customerIdOrKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerAccessResponse(rsp) +} + +// ListCustomerAppDataWithResponse request returning *ListCustomerAppDataResponse +func (c *ClientWithResponses) ListCustomerAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerAppDataParams, reqEditors ...RequestEditorFn) (*ListCustomerAppDataResponse, error) { + rsp, err := c.ListCustomerAppData(ctx, customerIdOrKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListCustomerAppDataResponse(rsp) +} + +// UpsertCustomerAppDataWithBodyWithResponse request with arbitrary body returning *UpsertCustomerAppDataResponse +func (c *ClientWithResponses) UpsertCustomerAppDataWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertCustomerAppDataResponse, error) { + rsp, err := c.UpsertCustomerAppDataWithBody(ctx, customerIdOrKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertCustomerAppDataResponse(rsp) +} + +func (c *ClientWithResponses) UpsertCustomerAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertCustomerAppDataResponse, error) { + rsp, err := c.UpsertCustomerAppData(ctx, customerIdOrKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertCustomerAppDataResponse(rsp) +} + +// DeleteCustomerAppDataWithResponse request returning *DeleteCustomerAppDataResponse +func (c *ClientWithResponses) DeleteCustomerAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, appId string, reqEditors ...RequestEditorFn) (*DeleteCustomerAppDataResponse, error) { + rsp, err := c.DeleteCustomerAppData(ctx, customerIdOrKey, appId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteCustomerAppDataResponse(rsp) +} + +// GetCustomerEntitlementValueWithResponse request returning *GetCustomerEntitlementValueResponse +func (c *ClientWithResponses) GetCustomerEntitlementValueWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, featureKey string, params *GetCustomerEntitlementValueParams, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementValueResponse, error) { + rsp, err := c.GetCustomerEntitlementValue(ctx, customerIdOrKey, featureKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerEntitlementValueResponse(rsp) +} + +// GetCustomerStripeAppDataWithResponse request returning *GetCustomerStripeAppDataResponse +func (c *ClientWithResponses) GetCustomerStripeAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, reqEditors ...RequestEditorFn) (*GetCustomerStripeAppDataResponse, error) { + rsp, err := c.GetCustomerStripeAppData(ctx, customerIdOrKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerStripeAppDataResponse(rsp) +} + +// UpsertCustomerStripeAppDataWithBodyWithResponse request with arbitrary body returning *UpsertCustomerStripeAppDataResponse +func (c *ClientWithResponses) UpsertCustomerStripeAppDataWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertCustomerStripeAppDataResponse, error) { + rsp, err := c.UpsertCustomerStripeAppDataWithBody(ctx, customerIdOrKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertCustomerStripeAppDataResponse(rsp) +} + +func (c *ClientWithResponses) UpsertCustomerStripeAppDataWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body UpsertCustomerStripeAppDataJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertCustomerStripeAppDataResponse, error) { + rsp, err := c.UpsertCustomerStripeAppData(ctx, customerIdOrKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertCustomerStripeAppDataResponse(rsp) +} + +// CreateCustomerStripePortalSessionWithBodyWithResponse request with arbitrary body returning *CreateCustomerStripePortalSessionResponse +func (c *ClientWithResponses) CreateCustomerStripePortalSessionWithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerStripePortalSessionResponse, error) { + rsp, err := c.CreateCustomerStripePortalSessionWithBody(ctx, customerIdOrKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerStripePortalSessionResponse(rsp) +} + +func (c *ClientWithResponses) CreateCustomerStripePortalSessionWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerStripePortalSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerStripePortalSessionResponse, error) { + rsp, err := c.CreateCustomerStripePortalSession(ctx, customerIdOrKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerStripePortalSessionResponse(rsp) +} + +// ListCustomerSubscriptionsWithResponse request returning *ListCustomerSubscriptionsResponse +func (c *ClientWithResponses) ListCustomerSubscriptionsWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerSubscriptionsParams, reqEditors ...RequestEditorFn) (*ListCustomerSubscriptionsResponse, error) { + rsp, err := c.ListCustomerSubscriptions(ctx, customerIdOrKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListCustomerSubscriptionsResponse(rsp) +} + +// GetDebugMetricsWithResponse request returning *GetDebugMetricsResponse +func (c *ClientWithResponses) GetDebugMetricsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetDebugMetricsResponse, error) { + rsp, err := c.GetDebugMetrics(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetDebugMetricsResponse(rsp) +} + +// ListEntitlementsWithResponse request returning *ListEntitlementsResponse +func (c *ClientWithResponses) ListEntitlementsWithResponse(ctx context.Context, params *ListEntitlementsParams, reqEditors ...RequestEditorFn) (*ListEntitlementsResponse, error) { + rsp, err := c.ListEntitlements(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListEntitlementsResponse(rsp) +} + +// GetEntitlementByIdWithResponse request returning *GetEntitlementByIdResponse +func (c *ClientWithResponses) GetEntitlementByIdWithResponse(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*GetEntitlementByIdResponse, error) { + rsp, err := c.GetEntitlementById(ctx, entitlementId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEntitlementByIdResponse(rsp) +} + +// ListEventsWithResponse request returning *ListEventsResponse +func (c *ClientWithResponses) ListEventsWithResponse(ctx context.Context, params *ListEventsParams, reqEditors ...RequestEditorFn) (*ListEventsResponse, error) { + rsp, err := c.ListEvents(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListEventsResponse(rsp) +} + +// IngestEventsWithBodyWithResponse request with arbitrary body returning *IngestEventsResponse +func (c *ClientWithResponses) IngestEventsWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) { + rsp, err := c.IngestEventsWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseIngestEventsResponse(rsp) +} + +func (c *ClientWithResponses) IngestEventsWithApplicationCloudeventsPlusJSONBodyWithResponse(ctx context.Context, body IngestEventsApplicationCloudeventsPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) { + rsp, err := c.IngestEventsWithApplicationCloudeventsPlusJSONBody(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseIngestEventsResponse(rsp) +} + +func (c *ClientWithResponses) IngestEventsWithApplicationCloudeventsBatchPlusJSONBodyWithResponse(ctx context.Context, body IngestEventsApplicationCloudeventsBatchPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) { + rsp, err := c.IngestEventsWithApplicationCloudeventsBatchPlusJSONBody(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseIngestEventsResponse(rsp) +} + +func (c *ClientWithResponses) IngestEventsWithResponse(ctx context.Context, body IngestEventsJSONRequestBody, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) { + rsp, err := c.IngestEvents(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseIngestEventsResponse(rsp) +} + +// ListFeaturesWithResponse request returning *ListFeaturesResponse +func (c *ClientWithResponses) ListFeaturesWithResponse(ctx context.Context, params *ListFeaturesParams, reqEditors ...RequestEditorFn) (*ListFeaturesResponse, error) { + rsp, err := c.ListFeatures(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListFeaturesResponse(rsp) +} + +// CreateFeatureWithBodyWithResponse request with arbitrary body returning *CreateFeatureResponse +func (c *ClientWithResponses) CreateFeatureWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateFeatureResponse, error) { + rsp, err := c.CreateFeatureWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateFeatureResponse(rsp) +} + +func (c *ClientWithResponses) CreateFeatureWithResponse(ctx context.Context, body CreateFeatureJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateFeatureResponse, error) { + rsp, err := c.CreateFeature(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateFeatureResponse(rsp) +} + +// DeleteFeatureWithResponse request returning *DeleteFeatureResponse +func (c *ClientWithResponses) DeleteFeatureWithResponse(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*DeleteFeatureResponse, error) { + rsp, err := c.DeleteFeature(ctx, featureId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteFeatureResponse(rsp) +} + +// GetFeatureWithResponse request returning *GetFeatureResponse +func (c *ClientWithResponses) GetFeatureWithResponse(ctx context.Context, featureId string, reqEditors ...RequestEditorFn) (*GetFeatureResponse, error) { + rsp, err := c.GetFeature(ctx, featureId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetFeatureResponse(rsp) +} + +// ListGrantsWithResponse request returning *ListGrantsResponse +func (c *ClientWithResponses) ListGrantsWithResponse(ctx context.Context, params *ListGrantsParams, reqEditors ...RequestEditorFn) (*ListGrantsResponse, error) { + rsp, err := c.ListGrants(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListGrantsResponse(rsp) +} + +// VoidGrantWithResponse request returning *VoidGrantResponse +func (c *ClientWithResponses) VoidGrantWithResponse(ctx context.Context, grantId string, params *VoidGrantParams, reqEditors ...RequestEditorFn) (*VoidGrantResponse, error) { + rsp, err := c.VoidGrant(ctx, grantId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseVoidGrantResponse(rsp) +} + +// ListCurrenciesWithResponse request returning *ListCurrenciesResponse +func (c *ClientWithResponses) ListCurrenciesWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListCurrenciesResponse, error) { + rsp, err := c.ListCurrencies(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseListCurrenciesResponse(rsp) +} + +// GetProgressWithResponse request returning *GetProgressResponse +func (c *ClientWithResponses) GetProgressWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetProgressResponse, error) { + rsp, err := c.GetProgress(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetProgressResponse(rsp) +} + +// ListMarketplaceListingsWithResponse request returning *ListMarketplaceListingsResponse +func (c *ClientWithResponses) ListMarketplaceListingsWithResponse(ctx context.Context, params *ListMarketplaceListingsParams, reqEditors ...RequestEditorFn) (*ListMarketplaceListingsResponse, error) { + rsp, err := c.ListMarketplaceListings(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMarketplaceListingsResponse(rsp) +} + +// GetMarketplaceListingWithResponse request returning *GetMarketplaceListingResponse +func (c *ClientWithResponses) GetMarketplaceListingWithResponse(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*GetMarketplaceListingResponse, error) { + rsp, err := c.GetMarketplaceListing(ctx, pType, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMarketplaceListingResponse(rsp) +} + +// MarketplaceAppInstallWithBodyWithResponse request with arbitrary body returning *MarketplaceAppInstallResponse +func (c *ClientWithResponses) MarketplaceAppInstallWithBodyWithResponse(ctx context.Context, pType MarketplaceInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MarketplaceAppInstallResponse, error) { + rsp, err := c.MarketplaceAppInstallWithBody(ctx, pType, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarketplaceAppInstallResponse(rsp) +} + +func (c *ClientWithResponses) MarketplaceAppInstallWithResponse(ctx context.Context, pType MarketplaceInstallRequestType, body MarketplaceAppInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*MarketplaceAppInstallResponse, error) { + rsp, err := c.MarketplaceAppInstall(ctx, pType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarketplaceAppInstallResponse(rsp) +} + +// MarketplaceAppAPIKeyInstallWithBodyWithResponse request with arbitrary body returning *MarketplaceAppAPIKeyInstallResponse +func (c *ClientWithResponses) MarketplaceAppAPIKeyInstallWithBodyWithResponse(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MarketplaceAppAPIKeyInstallResponse, error) { + rsp, err := c.MarketplaceAppAPIKeyInstallWithBody(ctx, pType, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarketplaceAppAPIKeyInstallResponse(rsp) +} + +func (c *ClientWithResponses) MarketplaceAppAPIKeyInstallWithResponse(ctx context.Context, pType MarketplaceApiKeyInstallRequestType, body MarketplaceAppAPIKeyInstallJSONRequestBody, reqEditors ...RequestEditorFn) (*MarketplaceAppAPIKeyInstallResponse, error) { + rsp, err := c.MarketplaceAppAPIKeyInstall(ctx, pType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarketplaceAppAPIKeyInstallResponse(rsp) +} + +// MarketplaceOAuth2InstallGetURLWithResponse request returning *MarketplaceOAuth2InstallGetURLResponse +func (c *ClientWithResponses) MarketplaceOAuth2InstallGetURLWithResponse(ctx context.Context, pType AppType, reqEditors ...RequestEditorFn) (*MarketplaceOAuth2InstallGetURLResponse, error) { + rsp, err := c.MarketplaceOAuth2InstallGetURL(ctx, pType, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarketplaceOAuth2InstallGetURLResponse(rsp) +} + +// MarketplaceOAuth2InstallAuthorizeWithResponse request returning *MarketplaceOAuth2InstallAuthorizeResponse +func (c *ClientWithResponses) MarketplaceOAuth2InstallAuthorizeWithResponse(ctx context.Context, pType MarketplaceOAuth2InstallAuthorizeRequestType, params *MarketplaceOAuth2InstallAuthorizeParams, reqEditors ...RequestEditorFn) (*MarketplaceOAuth2InstallAuthorizeResponse, error) { + rsp, err := c.MarketplaceOAuth2InstallAuthorize(ctx, pType, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarketplaceOAuth2InstallAuthorizeResponse(rsp) +} + +// ListMetersWithResponse request returning *ListMetersResponse +func (c *ClientWithResponses) ListMetersWithResponse(ctx context.Context, params *ListMetersParams, reqEditors ...RequestEditorFn) (*ListMetersResponse, error) { + rsp, err := c.ListMeters(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMetersResponse(rsp) +} + +// CreateMeterWithBodyWithResponse request with arbitrary body returning *CreateMeterResponse +func (c *ClientWithResponses) CreateMeterWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateMeterResponse, error) { + rsp, err := c.CreateMeterWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateMeterResponse(rsp) +} + +func (c *ClientWithResponses) CreateMeterWithResponse(ctx context.Context, body CreateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateMeterResponse, error) { + rsp, err := c.CreateMeter(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateMeterResponse(rsp) +} + +// DeleteMeterWithResponse request returning *DeleteMeterResponse +func (c *ClientWithResponses) DeleteMeterWithResponse(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*DeleteMeterResponse, error) { + rsp, err := c.DeleteMeter(ctx, meterIdOrSlug, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteMeterResponse(rsp) +} + +// GetMeterWithResponse request returning *GetMeterResponse +func (c *ClientWithResponses) GetMeterWithResponse(ctx context.Context, meterIdOrSlug string, reqEditors ...RequestEditorFn) (*GetMeterResponse, error) { + rsp, err := c.GetMeter(ctx, meterIdOrSlug, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetMeterResponse(rsp) +} + +// UpdateMeterWithBodyWithResponse request with arbitrary body returning *UpdateMeterResponse +func (c *ClientWithResponses) UpdateMeterWithBodyWithResponse(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateMeterResponse, error) { + rsp, err := c.UpdateMeterWithBody(ctx, meterIdOrSlug, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateMeterResponse(rsp) +} + +func (c *ClientWithResponses) UpdateMeterWithResponse(ctx context.Context, meterIdOrSlug string, body UpdateMeterJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateMeterResponse, error) { + rsp, err := c.UpdateMeter(ctx, meterIdOrSlug, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateMeterResponse(rsp) +} + +// ListMeterGroupByValuesWithResponse request returning *ListMeterGroupByValuesResponse +func (c *ClientWithResponses) ListMeterGroupByValuesWithResponse(ctx context.Context, meterIdOrSlug string, groupByKey string, params *ListMeterGroupByValuesParams, reqEditors ...RequestEditorFn) (*ListMeterGroupByValuesResponse, error) { + rsp, err := c.ListMeterGroupByValues(ctx, meterIdOrSlug, groupByKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMeterGroupByValuesResponse(rsp) +} + +// QueryMeterWithResponse request returning *QueryMeterResponse +func (c *ClientWithResponses) QueryMeterWithResponse(ctx context.Context, meterIdOrSlug string, params *QueryMeterParams, reqEditors ...RequestEditorFn) (*QueryMeterResponse, error) { + rsp, err := c.QueryMeter(ctx, meterIdOrSlug, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseQueryMeterResponse(rsp) +} + +// QueryMeterPostWithBodyWithResponse request with arbitrary body returning *QueryMeterPostResponse +func (c *ClientWithResponses) QueryMeterPostWithBodyWithResponse(ctx context.Context, meterIdOrSlug string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*QueryMeterPostResponse, error) { + rsp, err := c.QueryMeterPostWithBody(ctx, meterIdOrSlug, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseQueryMeterPostResponse(rsp) +} + +func (c *ClientWithResponses) QueryMeterPostWithResponse(ctx context.Context, meterIdOrSlug string, body QueryMeterPostJSONRequestBody, reqEditors ...RequestEditorFn) (*QueryMeterPostResponse, error) { + rsp, err := c.QueryMeterPost(ctx, meterIdOrSlug, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseQueryMeterPostResponse(rsp) +} + +// ListMeterSubjectsWithResponse request returning *ListMeterSubjectsResponse +func (c *ClientWithResponses) ListMeterSubjectsWithResponse(ctx context.Context, meterIdOrSlug string, params *ListMeterSubjectsParams, reqEditors ...RequestEditorFn) (*ListMeterSubjectsResponse, error) { + rsp, err := c.ListMeterSubjects(ctx, meterIdOrSlug, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListMeterSubjectsResponse(rsp) +} + +// ListNotificationChannelsWithResponse request returning *ListNotificationChannelsResponse +func (c *ClientWithResponses) ListNotificationChannelsWithResponse(ctx context.Context, params *ListNotificationChannelsParams, reqEditors ...RequestEditorFn) (*ListNotificationChannelsResponse, error) { + rsp, err := c.ListNotificationChannels(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListNotificationChannelsResponse(rsp) +} + +// CreateNotificationChannelWithBodyWithResponse request with arbitrary body returning *CreateNotificationChannelResponse +func (c *ClientWithResponses) CreateNotificationChannelWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateNotificationChannelResponse, error) { + rsp, err := c.CreateNotificationChannelWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateNotificationChannelResponse(rsp) +} + +func (c *ClientWithResponses) CreateNotificationChannelWithResponse(ctx context.Context, body CreateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateNotificationChannelResponse, error) { + rsp, err := c.CreateNotificationChannel(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateNotificationChannelResponse(rsp) +} + +// DeleteNotificationChannelWithResponse request returning *DeleteNotificationChannelResponse +func (c *ClientWithResponses) DeleteNotificationChannelWithResponse(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*DeleteNotificationChannelResponse, error) { + rsp, err := c.DeleteNotificationChannel(ctx, channelId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteNotificationChannelResponse(rsp) +} + +// GetNotificationChannelWithResponse request returning *GetNotificationChannelResponse +func (c *ClientWithResponses) GetNotificationChannelWithResponse(ctx context.Context, channelId string, reqEditors ...RequestEditorFn) (*GetNotificationChannelResponse, error) { + rsp, err := c.GetNotificationChannel(ctx, channelId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNotificationChannelResponse(rsp) +} + +// UpdateNotificationChannelWithBodyWithResponse request with arbitrary body returning *UpdateNotificationChannelResponse +func (c *ClientWithResponses) UpdateNotificationChannelWithBodyWithResponse(ctx context.Context, channelId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateNotificationChannelResponse, error) { + rsp, err := c.UpdateNotificationChannelWithBody(ctx, channelId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateNotificationChannelResponse(rsp) +} + +func (c *ClientWithResponses) UpdateNotificationChannelWithResponse(ctx context.Context, channelId string, body UpdateNotificationChannelJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateNotificationChannelResponse, error) { + rsp, err := c.UpdateNotificationChannel(ctx, channelId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateNotificationChannelResponse(rsp) +} + +// ListNotificationEventsWithResponse request returning *ListNotificationEventsResponse +func (c *ClientWithResponses) ListNotificationEventsWithResponse(ctx context.Context, params *ListNotificationEventsParams, reqEditors ...RequestEditorFn) (*ListNotificationEventsResponse, error) { + rsp, err := c.ListNotificationEvents(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListNotificationEventsResponse(rsp) +} + +// GetNotificationEventWithResponse request returning *GetNotificationEventResponse +func (c *ClientWithResponses) GetNotificationEventWithResponse(ctx context.Context, eventId string, reqEditors ...RequestEditorFn) (*GetNotificationEventResponse, error) { + rsp, err := c.GetNotificationEvent(ctx, eventId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNotificationEventResponse(rsp) +} + +// ResendNotificationEventWithBodyWithResponse request with arbitrary body returning *ResendNotificationEventResponse +func (c *ClientWithResponses) ResendNotificationEventWithBodyWithResponse(ctx context.Context, eventId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ResendNotificationEventResponse, error) { + rsp, err := c.ResendNotificationEventWithBody(ctx, eventId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseResendNotificationEventResponse(rsp) +} + +func (c *ClientWithResponses) ResendNotificationEventWithResponse(ctx context.Context, eventId string, body ResendNotificationEventJSONRequestBody, reqEditors ...RequestEditorFn) (*ResendNotificationEventResponse, error) { + rsp, err := c.ResendNotificationEvent(ctx, eventId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseResendNotificationEventResponse(rsp) +} + +// ListNotificationRulesWithResponse request returning *ListNotificationRulesResponse +func (c *ClientWithResponses) ListNotificationRulesWithResponse(ctx context.Context, params *ListNotificationRulesParams, reqEditors ...RequestEditorFn) (*ListNotificationRulesResponse, error) { + rsp, err := c.ListNotificationRules(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListNotificationRulesResponse(rsp) +} + +// CreateNotificationRuleWithBodyWithResponse request with arbitrary body returning *CreateNotificationRuleResponse +func (c *ClientWithResponses) CreateNotificationRuleWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateNotificationRuleResponse, error) { + rsp, err := c.CreateNotificationRuleWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateNotificationRuleResponse(rsp) +} + +func (c *ClientWithResponses) CreateNotificationRuleWithResponse(ctx context.Context, body CreateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateNotificationRuleResponse, error) { + rsp, err := c.CreateNotificationRule(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateNotificationRuleResponse(rsp) +} + +// DeleteNotificationRuleWithResponse request returning *DeleteNotificationRuleResponse +func (c *ClientWithResponses) DeleteNotificationRuleWithResponse(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*DeleteNotificationRuleResponse, error) { + rsp, err := c.DeleteNotificationRule(ctx, ruleId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteNotificationRuleResponse(rsp) +} + +// GetNotificationRuleWithResponse request returning *GetNotificationRuleResponse +func (c *ClientWithResponses) GetNotificationRuleWithResponse(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*GetNotificationRuleResponse, error) { + rsp, err := c.GetNotificationRule(ctx, ruleId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetNotificationRuleResponse(rsp) +} + +// UpdateNotificationRuleWithBodyWithResponse request with arbitrary body returning *UpdateNotificationRuleResponse +func (c *ClientWithResponses) UpdateNotificationRuleWithBodyWithResponse(ctx context.Context, ruleId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateNotificationRuleResponse, error) { + rsp, err := c.UpdateNotificationRuleWithBody(ctx, ruleId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateNotificationRuleResponse(rsp) +} + +func (c *ClientWithResponses) UpdateNotificationRuleWithResponse(ctx context.Context, ruleId string, body UpdateNotificationRuleJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateNotificationRuleResponse, error) { + rsp, err := c.UpdateNotificationRule(ctx, ruleId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateNotificationRuleResponse(rsp) +} + +// TestNotificationRuleWithResponse request returning *TestNotificationRuleResponse +func (c *ClientWithResponses) TestNotificationRuleWithResponse(ctx context.Context, ruleId string, reqEditors ...RequestEditorFn) (*TestNotificationRuleResponse, error) { + rsp, err := c.TestNotificationRule(ctx, ruleId, reqEditors...) + if err != nil { + return nil, err + } + return ParseTestNotificationRuleResponse(rsp) +} + +// ListPlansWithResponse request returning *ListPlansResponse +func (c *ClientWithResponses) ListPlansWithResponse(ctx context.Context, params *ListPlansParams, reqEditors ...RequestEditorFn) (*ListPlansResponse, error) { + rsp, err := c.ListPlans(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListPlansResponse(rsp) +} + +// CreatePlanWithBodyWithResponse request with arbitrary body returning *CreatePlanResponse +func (c *ClientWithResponses) CreatePlanWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePlanResponse, error) { + rsp, err := c.CreatePlanWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePlanResponse(rsp) +} + +func (c *ClientWithResponses) CreatePlanWithResponse(ctx context.Context, body CreatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePlanResponse, error) { + rsp, err := c.CreatePlan(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePlanResponse(rsp) +} + +// NextPlanWithResponse request returning *NextPlanResponse +func (c *ClientWithResponses) NextPlanWithResponse(ctx context.Context, planIdOrKey string, reqEditors ...RequestEditorFn) (*NextPlanResponse, error) { + rsp, err := c.NextPlan(ctx, planIdOrKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseNextPlanResponse(rsp) +} + +// DeletePlanWithResponse request returning *DeletePlanResponse +func (c *ClientWithResponses) DeletePlanWithResponse(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*DeletePlanResponse, error) { + rsp, err := c.DeletePlan(ctx, planId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeletePlanResponse(rsp) +} + +// GetPlanWithResponse request returning *GetPlanResponse +func (c *ClientWithResponses) GetPlanWithResponse(ctx context.Context, planId string, params *GetPlanParams, reqEditors ...RequestEditorFn) (*GetPlanResponse, error) { + rsp, err := c.GetPlan(ctx, planId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetPlanResponse(rsp) +} + +// UpdatePlanWithBodyWithResponse request with arbitrary body returning *UpdatePlanResponse +func (c *ClientWithResponses) UpdatePlanWithBodyWithResponse(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdatePlanResponse, error) { + rsp, err := c.UpdatePlanWithBody(ctx, planId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdatePlanResponse(rsp) +} + +func (c *ClientWithResponses) UpdatePlanWithResponse(ctx context.Context, planId string, body UpdatePlanJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdatePlanResponse, error) { + rsp, err := c.UpdatePlan(ctx, planId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdatePlanResponse(rsp) +} + +// ListPlanAddonsWithResponse request returning *ListPlanAddonsResponse +func (c *ClientWithResponses) ListPlanAddonsWithResponse(ctx context.Context, planId string, params *ListPlanAddonsParams, reqEditors ...RequestEditorFn) (*ListPlanAddonsResponse, error) { + rsp, err := c.ListPlanAddons(ctx, planId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListPlanAddonsResponse(rsp) +} + +// CreatePlanAddonWithBodyWithResponse request with arbitrary body returning *CreatePlanAddonResponse +func (c *ClientWithResponses) CreatePlanAddonWithBodyWithResponse(ctx context.Context, planId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePlanAddonResponse, error) { + rsp, err := c.CreatePlanAddonWithBody(ctx, planId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePlanAddonResponse(rsp) +} + +func (c *ClientWithResponses) CreatePlanAddonWithResponse(ctx context.Context, planId string, body CreatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePlanAddonResponse, error) { + rsp, err := c.CreatePlanAddon(ctx, planId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePlanAddonResponse(rsp) +} + +// DeletePlanAddonWithResponse request returning *DeletePlanAddonResponse +func (c *ClientWithResponses) DeletePlanAddonWithResponse(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*DeletePlanAddonResponse, error) { + rsp, err := c.DeletePlanAddon(ctx, planId, planAddonId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeletePlanAddonResponse(rsp) +} + +// GetPlanAddonWithResponse request returning *GetPlanAddonResponse +func (c *ClientWithResponses) GetPlanAddonWithResponse(ctx context.Context, planId string, planAddonId string, reqEditors ...RequestEditorFn) (*GetPlanAddonResponse, error) { + rsp, err := c.GetPlanAddon(ctx, planId, planAddonId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetPlanAddonResponse(rsp) +} + +// UpdatePlanAddonWithBodyWithResponse request with arbitrary body returning *UpdatePlanAddonResponse +func (c *ClientWithResponses) UpdatePlanAddonWithBodyWithResponse(ctx context.Context, planId string, planAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdatePlanAddonResponse, error) { + rsp, err := c.UpdatePlanAddonWithBody(ctx, planId, planAddonId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdatePlanAddonResponse(rsp) +} + +func (c *ClientWithResponses) UpdatePlanAddonWithResponse(ctx context.Context, planId string, planAddonId string, body UpdatePlanAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdatePlanAddonResponse, error) { + rsp, err := c.UpdatePlanAddon(ctx, planId, planAddonId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdatePlanAddonResponse(rsp) +} + +// ArchivePlanWithResponse request returning *ArchivePlanResponse +func (c *ClientWithResponses) ArchivePlanWithResponse(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*ArchivePlanResponse, error) { + rsp, err := c.ArchivePlan(ctx, planId, reqEditors...) + if err != nil { + return nil, err + } + return ParseArchivePlanResponse(rsp) +} + +// PublishPlanWithResponse request returning *PublishPlanResponse +func (c *ClientWithResponses) PublishPlanWithResponse(ctx context.Context, planId string, reqEditors ...RequestEditorFn) (*PublishPlanResponse, error) { + rsp, err := c.PublishPlan(ctx, planId, reqEditors...) + if err != nil { + return nil, err + } + return ParsePublishPlanResponse(rsp) +} + +// QueryPortalMeterWithResponse request returning *QueryPortalMeterResponse +func (c *ClientWithResponses) QueryPortalMeterWithResponse(ctx context.Context, meterSlug string, params *QueryPortalMeterParams, reqEditors ...RequestEditorFn) (*QueryPortalMeterResponse, error) { + rsp, err := c.QueryPortalMeter(ctx, meterSlug, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseQueryPortalMeterResponse(rsp) +} + +// ListPortalTokensWithResponse request returning *ListPortalTokensResponse +func (c *ClientWithResponses) ListPortalTokensWithResponse(ctx context.Context, params *ListPortalTokensParams, reqEditors ...RequestEditorFn) (*ListPortalTokensResponse, error) { + rsp, err := c.ListPortalTokens(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListPortalTokensResponse(rsp) +} + +// CreatePortalTokenWithBodyWithResponse request with arbitrary body returning *CreatePortalTokenResponse +func (c *ClientWithResponses) CreatePortalTokenWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreatePortalTokenResponse, error) { + rsp, err := c.CreatePortalTokenWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePortalTokenResponse(rsp) +} + +func (c *ClientWithResponses) CreatePortalTokenWithResponse(ctx context.Context, body CreatePortalTokenJSONRequestBody, reqEditors ...RequestEditorFn) (*CreatePortalTokenResponse, error) { + rsp, err := c.CreatePortalToken(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreatePortalTokenResponse(rsp) +} + +// InvalidatePortalTokensWithBodyWithResponse request with arbitrary body returning *InvalidatePortalTokensResponse +func (c *ClientWithResponses) InvalidatePortalTokensWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*InvalidatePortalTokensResponse, error) { + rsp, err := c.InvalidatePortalTokensWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseInvalidatePortalTokensResponse(rsp) +} + +func (c *ClientWithResponses) InvalidatePortalTokensWithResponse(ctx context.Context, body InvalidatePortalTokensJSONRequestBody, reqEditors ...RequestEditorFn) (*InvalidatePortalTokensResponse, error) { + rsp, err := c.InvalidatePortalTokens(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseInvalidatePortalTokensResponse(rsp) +} + +// CreateStripeCheckoutSessionWithBodyWithResponse request with arbitrary body returning *CreateStripeCheckoutSessionResponse +func (c *ClientWithResponses) CreateStripeCheckoutSessionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateStripeCheckoutSessionResponse, error) { + rsp, err := c.CreateStripeCheckoutSessionWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateStripeCheckoutSessionResponse(rsp) +} + +func (c *ClientWithResponses) CreateStripeCheckoutSessionWithResponse(ctx context.Context, body CreateStripeCheckoutSessionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateStripeCheckoutSessionResponse, error) { + rsp, err := c.CreateStripeCheckoutSession(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateStripeCheckoutSessionResponse(rsp) +} + +// ListSubjectsWithResponse request returning *ListSubjectsResponse +func (c *ClientWithResponses) ListSubjectsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListSubjectsResponse, error) { + rsp, err := c.ListSubjects(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseListSubjectsResponse(rsp) +} + +// UpsertSubjectWithBodyWithResponse request with arbitrary body returning *UpsertSubjectResponse +func (c *ClientWithResponses) UpsertSubjectWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpsertSubjectResponse, error) { + rsp, err := c.UpsertSubjectWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertSubjectResponse(rsp) +} + +func (c *ClientWithResponses) UpsertSubjectWithResponse(ctx context.Context, body UpsertSubjectJSONRequestBody, reqEditors ...RequestEditorFn) (*UpsertSubjectResponse, error) { + rsp, err := c.UpsertSubject(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpsertSubjectResponse(rsp) +} + +// DeleteSubjectWithResponse request returning *DeleteSubjectResponse +func (c *ClientWithResponses) DeleteSubjectWithResponse(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*DeleteSubjectResponse, error) { + rsp, err := c.DeleteSubject(ctx, subjectIdOrKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteSubjectResponse(rsp) +} + +// GetSubjectWithResponse request returning *GetSubjectResponse +func (c *ClientWithResponses) GetSubjectWithResponse(ctx context.Context, subjectIdOrKey string, reqEditors ...RequestEditorFn) (*GetSubjectResponse, error) { + rsp, err := c.GetSubject(ctx, subjectIdOrKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetSubjectResponse(rsp) +} + +// ListSubjectEntitlementsWithResponse request returning *ListSubjectEntitlementsResponse +func (c *ClientWithResponses) ListSubjectEntitlementsWithResponse(ctx context.Context, subjectIdOrKey string, params *ListSubjectEntitlementsParams, reqEditors ...RequestEditorFn) (*ListSubjectEntitlementsResponse, error) { + rsp, err := c.ListSubjectEntitlements(ctx, subjectIdOrKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListSubjectEntitlementsResponse(rsp) +} + +// CreateEntitlementWithBodyWithResponse request with arbitrary body returning *CreateEntitlementResponse +func (c *ClientWithResponses) CreateEntitlementWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateEntitlementResponse, error) { + rsp, err := c.CreateEntitlementWithBody(ctx, subjectIdOrKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateEntitlementResponse(rsp) +} + +func (c *ClientWithResponses) CreateEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, body CreateEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateEntitlementResponse, error) { + rsp, err := c.CreateEntitlement(ctx, subjectIdOrKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateEntitlementResponse(rsp) +} + +// ListEntitlementGrantsWithResponse request returning *ListEntitlementGrantsResponse +func (c *ClientWithResponses) ListEntitlementGrantsWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *ListEntitlementGrantsParams, reqEditors ...RequestEditorFn) (*ListEntitlementGrantsResponse, error) { + rsp, err := c.ListEntitlementGrants(ctx, subjectIdOrKey, entitlementIdOrFeatureKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListEntitlementGrantsResponse(rsp) +} + +// CreateGrantWithBodyWithResponse request with arbitrary body returning *CreateGrantResponse +func (c *ClientWithResponses) CreateGrantWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateGrantResponse, error) { + rsp, err := c.CreateGrantWithBody(ctx, subjectIdOrKey, entitlementIdOrFeatureKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateGrantResponse(rsp) +} + +func (c *ClientWithResponses) CreateGrantWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body CreateGrantJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateGrantResponse, error) { + rsp, err := c.CreateGrant(ctx, subjectIdOrKey, entitlementIdOrFeatureKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateGrantResponse(rsp) +} + +// OverrideEntitlementWithBodyWithResponse request with arbitrary body returning *OverrideEntitlementResponse +func (c *ClientWithResponses) OverrideEntitlementWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*OverrideEntitlementResponse, error) { + rsp, err := c.OverrideEntitlementWithBody(ctx, subjectIdOrKey, entitlementIdOrFeatureKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseOverrideEntitlementResponse(rsp) +} + +func (c *ClientWithResponses) OverrideEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, body OverrideEntitlementJSONRequestBody, reqEditors ...RequestEditorFn) (*OverrideEntitlementResponse, error) { + rsp, err := c.OverrideEntitlement(ctx, subjectIdOrKey, entitlementIdOrFeatureKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseOverrideEntitlementResponse(rsp) +} + +// GetEntitlementValueWithResponse request returning *GetEntitlementValueResponse +func (c *ClientWithResponses) GetEntitlementValueWithResponse(ctx context.Context, subjectIdOrKey string, entitlementIdOrFeatureKey string, params *GetEntitlementValueParams, reqEditors ...RequestEditorFn) (*GetEntitlementValueResponse, error) { + rsp, err := c.GetEntitlementValue(ctx, subjectIdOrKey, entitlementIdOrFeatureKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEntitlementValueResponse(rsp) +} + +// DeleteEntitlementWithResponse request returning *DeleteEntitlementResponse +func (c *ClientWithResponses) DeleteEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*DeleteEntitlementResponse, error) { + rsp, err := c.DeleteEntitlement(ctx, subjectIdOrKey, entitlementId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteEntitlementResponse(rsp) +} + +// GetEntitlementWithResponse request returning *GetEntitlementResponse +func (c *ClientWithResponses) GetEntitlementWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, reqEditors ...RequestEditorFn) (*GetEntitlementResponse, error) { + rsp, err := c.GetEntitlement(ctx, subjectIdOrKey, entitlementId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEntitlementResponse(rsp) +} + +// GetEntitlementHistoryWithResponse request returning *GetEntitlementHistoryResponse +func (c *ClientWithResponses) GetEntitlementHistoryWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, params *GetEntitlementHistoryParams, reqEditors ...RequestEditorFn) (*GetEntitlementHistoryResponse, error) { + rsp, err := c.GetEntitlementHistory(ctx, subjectIdOrKey, entitlementId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEntitlementHistoryResponse(rsp) +} + +// ResetEntitlementUsageWithBodyWithResponse request with arbitrary body returning *ResetEntitlementUsageResponse +func (c *ClientWithResponses) ResetEntitlementUsageWithBodyWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ResetEntitlementUsageResponse, error) { + rsp, err := c.ResetEntitlementUsageWithBody(ctx, subjectIdOrKey, entitlementId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseResetEntitlementUsageResponse(rsp) +} + +func (c *ClientWithResponses) ResetEntitlementUsageWithResponse(ctx context.Context, subjectIdOrKey string, entitlementId string, body ResetEntitlementUsageJSONRequestBody, reqEditors ...RequestEditorFn) (*ResetEntitlementUsageResponse, error) { + rsp, err := c.ResetEntitlementUsage(ctx, subjectIdOrKey, entitlementId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseResetEntitlementUsageResponse(rsp) +} + +// CreateSubscriptionWithBodyWithResponse request with arbitrary body returning *CreateSubscriptionResponse +func (c *ClientWithResponses) CreateSubscriptionWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateSubscriptionResponse, error) { + rsp, err := c.CreateSubscriptionWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateSubscriptionResponse(rsp) +} + +func (c *ClientWithResponses) CreateSubscriptionWithResponse(ctx context.Context, body CreateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateSubscriptionResponse, error) { + rsp, err := c.CreateSubscription(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateSubscriptionResponse(rsp) +} + +// DeleteSubscriptionWithResponse request returning *DeleteSubscriptionResponse +func (c *ClientWithResponses) DeleteSubscriptionWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*DeleteSubscriptionResponse, error) { + rsp, err := c.DeleteSubscription(ctx, subscriptionId, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteSubscriptionResponse(rsp) +} + +// GetSubscriptionWithResponse request returning *GetSubscriptionResponse +func (c *ClientWithResponses) GetSubscriptionWithResponse(ctx context.Context, subscriptionId string, params *GetSubscriptionParams, reqEditors ...RequestEditorFn) (*GetSubscriptionResponse, error) { + rsp, err := c.GetSubscription(ctx, subscriptionId, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetSubscriptionResponse(rsp) +} + +// EditSubscriptionWithBodyWithResponse request with arbitrary body returning *EditSubscriptionResponse +func (c *ClientWithResponses) EditSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*EditSubscriptionResponse, error) { + rsp, err := c.EditSubscriptionWithBody(ctx, subscriptionId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseEditSubscriptionResponse(rsp) +} + +func (c *ClientWithResponses) EditSubscriptionWithResponse(ctx context.Context, subscriptionId string, body EditSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*EditSubscriptionResponse, error) { + rsp, err := c.EditSubscription(ctx, subscriptionId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseEditSubscriptionResponse(rsp) +} + +// ListSubscriptionAddonsWithResponse request returning *ListSubscriptionAddonsResponse +func (c *ClientWithResponses) ListSubscriptionAddonsWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*ListSubscriptionAddonsResponse, error) { + rsp, err := c.ListSubscriptionAddons(ctx, subscriptionId, reqEditors...) + if err != nil { + return nil, err + } + return ParseListSubscriptionAddonsResponse(rsp) +} + +// CreateSubscriptionAddonWithBodyWithResponse request with arbitrary body returning *CreateSubscriptionAddonResponse +func (c *ClientWithResponses) CreateSubscriptionAddonWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateSubscriptionAddonResponse, error) { + rsp, err := c.CreateSubscriptionAddonWithBody(ctx, subscriptionId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateSubscriptionAddonResponse(rsp) +} + +func (c *ClientWithResponses) CreateSubscriptionAddonWithResponse(ctx context.Context, subscriptionId string, body CreateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateSubscriptionAddonResponse, error) { + rsp, err := c.CreateSubscriptionAddon(ctx, subscriptionId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateSubscriptionAddonResponse(rsp) +} + +// GetSubscriptionAddonWithResponse request returning *GetSubscriptionAddonResponse +func (c *ClientWithResponses) GetSubscriptionAddonWithResponse(ctx context.Context, subscriptionId string, subscriptionAddonId string, reqEditors ...RequestEditorFn) (*GetSubscriptionAddonResponse, error) { + rsp, err := c.GetSubscriptionAddon(ctx, subscriptionId, subscriptionAddonId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetSubscriptionAddonResponse(rsp) +} + +// UpdateSubscriptionAddonWithBodyWithResponse request with arbitrary body returning *UpdateSubscriptionAddonResponse +func (c *ClientWithResponses) UpdateSubscriptionAddonWithBodyWithResponse(ctx context.Context, subscriptionId string, subscriptionAddonId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*UpdateSubscriptionAddonResponse, error) { + rsp, err := c.UpdateSubscriptionAddonWithBody(ctx, subscriptionId, subscriptionAddonId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateSubscriptionAddonResponse(rsp) +} + +func (c *ClientWithResponses) UpdateSubscriptionAddonWithResponse(ctx context.Context, subscriptionId string, subscriptionAddonId string, body UpdateSubscriptionAddonJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateSubscriptionAddonResponse, error) { + rsp, err := c.UpdateSubscriptionAddon(ctx, subscriptionId, subscriptionAddonId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseUpdateSubscriptionAddonResponse(rsp) +} + +// CancelSubscriptionWithBodyWithResponse request with arbitrary body returning *CancelSubscriptionResponse +func (c *ClientWithResponses) CancelSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CancelSubscriptionResponse, error) { + rsp, err := c.CancelSubscriptionWithBody(ctx, subscriptionId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCancelSubscriptionResponse(rsp) +} + +func (c *ClientWithResponses) CancelSubscriptionWithResponse(ctx context.Context, subscriptionId string, body CancelSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*CancelSubscriptionResponse, error) { + rsp, err := c.CancelSubscription(ctx, subscriptionId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCancelSubscriptionResponse(rsp) +} + +// ChangeSubscriptionWithBodyWithResponse request with arbitrary body returning *ChangeSubscriptionResponse +func (c *ClientWithResponses) ChangeSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ChangeSubscriptionResponse, error) { + rsp, err := c.ChangeSubscriptionWithBody(ctx, subscriptionId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseChangeSubscriptionResponse(rsp) +} + +func (c *ClientWithResponses) ChangeSubscriptionWithResponse(ctx context.Context, subscriptionId string, body ChangeSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*ChangeSubscriptionResponse, error) { + rsp, err := c.ChangeSubscription(ctx, subscriptionId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseChangeSubscriptionResponse(rsp) +} + +// MigrateSubscriptionWithBodyWithResponse request with arbitrary body returning *MigrateSubscriptionResponse +func (c *ClientWithResponses) MigrateSubscriptionWithBodyWithResponse(ctx context.Context, subscriptionId string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MigrateSubscriptionResponse, error) { + rsp, err := c.MigrateSubscriptionWithBody(ctx, subscriptionId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMigrateSubscriptionResponse(rsp) +} + +func (c *ClientWithResponses) MigrateSubscriptionWithResponse(ctx context.Context, subscriptionId string, body MigrateSubscriptionJSONRequestBody, reqEditors ...RequestEditorFn) (*MigrateSubscriptionResponse, error) { + rsp, err := c.MigrateSubscription(ctx, subscriptionId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMigrateSubscriptionResponse(rsp) +} + +// RestoreSubscriptionWithResponse request returning *RestoreSubscriptionResponse +func (c *ClientWithResponses) RestoreSubscriptionWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*RestoreSubscriptionResponse, error) { + rsp, err := c.RestoreSubscription(ctx, subscriptionId, reqEditors...) + if err != nil { + return nil, err + } + return ParseRestoreSubscriptionResponse(rsp) +} + +// UnscheduleCancelationWithResponse request returning *UnscheduleCancelationResponse +func (c *ClientWithResponses) UnscheduleCancelationWithResponse(ctx context.Context, subscriptionId string, reqEditors ...RequestEditorFn) (*UnscheduleCancelationResponse, error) { + rsp, err := c.UnscheduleCancelation(ctx, subscriptionId, reqEditors...) + if err != nil { + return nil, err + } + return ParseUnscheduleCancelationResponse(rsp) +} + +// ListCustomerEntitlementsV2WithResponse request returning *ListCustomerEntitlementsV2Response +func (c *ClientWithResponses) ListCustomerEntitlementsV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, params *ListCustomerEntitlementsV2Params, reqEditors ...RequestEditorFn) (*ListCustomerEntitlementsV2Response, error) { + rsp, err := c.ListCustomerEntitlementsV2(ctx, customerIdOrKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListCustomerEntitlementsV2Response(rsp) +} + +// CreateCustomerEntitlementV2WithBodyWithResponse request with arbitrary body returning *CreateCustomerEntitlementV2Response +func (c *ClientWithResponses) CreateCustomerEntitlementV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementV2Response, error) { + rsp, err := c.CreateCustomerEntitlementV2WithBody(ctx, customerIdOrKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerEntitlementV2Response(rsp) +} + +func (c *ClientWithResponses) CreateCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, body CreateCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementV2Response, error) { + rsp, err := c.CreateCustomerEntitlementV2(ctx, customerIdOrKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerEntitlementV2Response(rsp) +} + +// DeleteCustomerEntitlementV2WithResponse request returning *DeleteCustomerEntitlementV2Response +func (c *ClientWithResponses) DeleteCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*DeleteCustomerEntitlementV2Response, error) { + rsp, err := c.DeleteCustomerEntitlementV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseDeleteCustomerEntitlementV2Response(rsp) +} + +// GetCustomerEntitlementV2WithResponse request returning *GetCustomerEntitlementV2Response +func (c *ClientWithResponses) GetCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementV2Response, error) { + rsp, err := c.GetCustomerEntitlementV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerEntitlementV2Response(rsp) +} + +// ListCustomerEntitlementGrantsV2WithResponse request returning *ListCustomerEntitlementGrantsV2Response +func (c *ClientWithResponses) ListCustomerEntitlementGrantsV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *ListCustomerEntitlementGrantsV2Params, reqEditors ...RequestEditorFn) (*ListCustomerEntitlementGrantsV2Response, error) { + rsp, err := c.ListCustomerEntitlementGrantsV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListCustomerEntitlementGrantsV2Response(rsp) +} + +// CreateCustomerEntitlementGrantV2WithBodyWithResponse request with arbitrary body returning *CreateCustomerEntitlementGrantV2Response +func (c *ClientWithResponses) CreateCustomerEntitlementGrantV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementGrantV2Response, error) { + rsp, err := c.CreateCustomerEntitlementGrantV2WithBody(ctx, customerIdOrKey, entitlementIdOrFeatureKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerEntitlementGrantV2Response(rsp) +} + +func (c *ClientWithResponses) CreateCustomerEntitlementGrantV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body CreateCustomerEntitlementGrantV2JSONRequestBody, reqEditors ...RequestEditorFn) (*CreateCustomerEntitlementGrantV2Response, error) { + rsp, err := c.CreateCustomerEntitlementGrantV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateCustomerEntitlementGrantV2Response(rsp) +} + +// GetCustomerEntitlementHistoryV2WithResponse request returning *GetCustomerEntitlementHistoryV2Response +func (c *ClientWithResponses) GetCustomerEntitlementHistoryV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementHistoryV2Params, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementHistoryV2Response, error) { + rsp, err := c.GetCustomerEntitlementHistoryV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerEntitlementHistoryV2Response(rsp) +} + +// OverrideCustomerEntitlementV2WithBodyWithResponse request with arbitrary body returning *OverrideCustomerEntitlementV2Response +func (c *ClientWithResponses) OverrideCustomerEntitlementV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*OverrideCustomerEntitlementV2Response, error) { + rsp, err := c.OverrideCustomerEntitlementV2WithBody(ctx, customerIdOrKey, entitlementIdOrFeatureKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseOverrideCustomerEntitlementV2Response(rsp) +} + +func (c *ClientWithResponses) OverrideCustomerEntitlementV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey ULIDOrExternalKey, body OverrideCustomerEntitlementV2JSONRequestBody, reqEditors ...RequestEditorFn) (*OverrideCustomerEntitlementV2Response, error) { + rsp, err := c.OverrideCustomerEntitlementV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseOverrideCustomerEntitlementV2Response(rsp) +} + +// ResetCustomerEntitlementUsageV2WithBodyWithResponse request with arbitrary body returning *ResetCustomerEntitlementUsageV2Response +func (c *ClientWithResponses) ResetCustomerEntitlementUsageV2WithBodyWithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ResetCustomerEntitlementUsageV2Response, error) { + rsp, err := c.ResetCustomerEntitlementUsageV2WithBody(ctx, customerIdOrKey, entitlementIdOrFeatureKey, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseResetCustomerEntitlementUsageV2Response(rsp) +} + +func (c *ClientWithResponses) ResetCustomerEntitlementUsageV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, body ResetCustomerEntitlementUsageV2JSONRequestBody, reqEditors ...RequestEditorFn) (*ResetCustomerEntitlementUsageV2Response, error) { + rsp, err := c.ResetCustomerEntitlementUsageV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseResetCustomerEntitlementUsageV2Response(rsp) +} + +// GetCustomerEntitlementValueV2WithResponse request returning *GetCustomerEntitlementValueV2Response +func (c *ClientWithResponses) GetCustomerEntitlementValueV2WithResponse(ctx context.Context, customerIdOrKey ULIDOrExternalKey, entitlementIdOrFeatureKey string, params *GetCustomerEntitlementValueV2Params, reqEditors ...RequestEditorFn) (*GetCustomerEntitlementValueV2Response, error) { + rsp, err := c.GetCustomerEntitlementValueV2(ctx, customerIdOrKey, entitlementIdOrFeatureKey, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetCustomerEntitlementValueV2Response(rsp) +} + +// ListEntitlementsV2WithResponse request returning *ListEntitlementsV2Response +func (c *ClientWithResponses) ListEntitlementsV2WithResponse(ctx context.Context, params *ListEntitlementsV2Params, reqEditors ...RequestEditorFn) (*ListEntitlementsV2Response, error) { + rsp, err := c.ListEntitlementsV2(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListEntitlementsV2Response(rsp) +} + +// GetEntitlementByIdV2WithResponse request returning *GetEntitlementByIdV2Response +func (c *ClientWithResponses) GetEntitlementByIdV2WithResponse(ctx context.Context, entitlementId string, reqEditors ...RequestEditorFn) (*GetEntitlementByIdV2Response, error) { + rsp, err := c.GetEntitlementByIdV2(ctx, entitlementId, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetEntitlementByIdV2Response(rsp) +} + +// ListEventsV2WithResponse request returning *ListEventsV2Response +func (c *ClientWithResponses) ListEventsV2WithResponse(ctx context.Context, params *ListEventsV2Params, reqEditors ...RequestEditorFn) (*ListEventsV2Response, error) { + rsp, err := c.ListEventsV2(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListEventsV2Response(rsp) +} + +// ListGrantsV2WithResponse request returning *ListGrantsV2Response +func (c *ClientWithResponses) ListGrantsV2WithResponse(ctx context.Context, params *ListGrantsV2Params, reqEditors ...RequestEditorFn) (*ListGrantsV2Response, error) { + rsp, err := c.ListGrantsV2(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListGrantsV2Response(rsp) +} + +// ParseListAddonsResponse parses an HTTP response from a ListAddonsWithResponse call +func ParseListAddonsResponse(rsp *http.Response) (*ListAddonsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListAddonsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest AddonPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateAddonResponse parses an HTTP response from a CreateAddonWithResponse call +func ParseCreateAddonResponse(rsp *http.Response) (*CreateAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Addon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteAddonResponse parses an HTTP response from a DeleteAddonWithResponse call +func ParseDeleteAddonResponse(rsp *http.Response) (*DeleteAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetAddonResponse parses an HTTP response from a GetAddonWithResponse call +func ParseGetAddonResponse(rsp *http.Response) (*GetAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Addon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateAddonResponse parses an HTTP response from a UpdateAddonWithResponse call +func ParseUpdateAddonResponse(rsp *http.Response) (*UpdateAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Addon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseArchiveAddonResponse parses an HTTP response from a ArchiveAddonWithResponse call +func ParseArchiveAddonResponse(rsp *http.Response) (*ArchiveAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ArchiveAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Addon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParsePublishAddonResponse parses an HTTP response from a PublishAddonWithResponse call +func ParsePublishAddonResponse(rsp *http.Response) (*PublishAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PublishAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Addon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListAppsResponse parses an HTTP response from a ListAppsWithResponse call +func ParseListAppsResponse(rsp *http.Response) (*ListAppsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListAppsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest AppPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseAppCustomInvoicingDraftSynchronizedResponse parses an HTTP response from a AppCustomInvoicingDraftSynchronizedWithResponse call +func ParseAppCustomInvoicingDraftSynchronizedResponse(rsp *http.Response) (*AppCustomInvoicingDraftSynchronizedResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AppCustomInvoicingDraftSynchronizedResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseAppCustomInvoicingIssuingSynchronizedResponse parses an HTTP response from a AppCustomInvoicingIssuingSynchronizedWithResponse call +func ParseAppCustomInvoicingIssuingSynchronizedResponse(rsp *http.Response) (*AppCustomInvoicingIssuingSynchronizedResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AppCustomInvoicingIssuingSynchronizedResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseAppCustomInvoicingUpdatePaymentStatusResponse parses an HTTP response from a AppCustomInvoicingUpdatePaymentStatusWithResponse call +func ParseAppCustomInvoicingUpdatePaymentStatusResponse(rsp *http.Response) (*AppCustomInvoicingUpdatePaymentStatusResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AppCustomInvoicingUpdatePaymentStatusResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUninstallAppResponse parses an HTTP response from a UninstallAppWithResponse call +func ParseUninstallAppResponse(rsp *http.Response) (*UninstallAppResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UninstallAppResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetAppResponse parses an HTTP response from a GetAppWithResponse call +func ParseGetAppResponse(rsp *http.Response) (*GetAppResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetAppResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest App + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateAppResponse parses an HTTP response from a UpdateAppWithResponse call +func ParseUpdateAppResponse(rsp *http.Response) (*UpdateAppResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateAppResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest App + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateStripeAPIKeyResponse parses an HTTP response from a UpdateStripeAPIKeyWithResponse call +func ParseUpdateStripeAPIKeyResponse(rsp *http.Response) (*UpdateStripeAPIKeyResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateStripeAPIKeyResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseAppStripeWebhookResponse parses an HTTP response from a AppStripeWebhookWithResponse call +func ParseAppStripeWebhookResponse(rsp *http.Response) (*AppStripeWebhookResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AppStripeWebhookResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest StripeWebhookResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListBillingProfileCustomerOverridesResponse parses an HTTP response from a ListBillingProfileCustomerOverridesWithResponse call +func ParseListBillingProfileCustomerOverridesResponse(rsp *http.Response) (*ListBillingProfileCustomerOverridesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListBillingProfileCustomerOverridesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BillingProfileCustomerOverrideWithDetailsPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteBillingProfileCustomerOverrideResponse parses an HTTP response from a DeleteBillingProfileCustomerOverrideWithResponse call +func ParseDeleteBillingProfileCustomerOverrideResponse(rsp *http.Response) (*DeleteBillingProfileCustomerOverrideResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteBillingProfileCustomerOverrideResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetBillingProfileCustomerOverrideResponse parses an HTTP response from a GetBillingProfileCustomerOverrideWithResponse call +func ParseGetBillingProfileCustomerOverrideResponse(rsp *http.Response) (*GetBillingProfileCustomerOverrideResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetBillingProfileCustomerOverrideResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BillingProfileCustomerOverrideWithDetails + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpsertBillingProfileCustomerOverrideResponse parses an HTTP response from a UpsertBillingProfileCustomerOverrideWithResponse call +func ParseUpsertBillingProfileCustomerOverrideResponse(rsp *http.Response) (*UpsertBillingProfileCustomerOverrideResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpsertBillingProfileCustomerOverrideResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BillingProfileCustomerOverrideWithDetails + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreatePendingInvoiceLineResponse parses an HTTP response from a CreatePendingInvoiceLineWithResponse call +func ParseCreatePendingInvoiceLineResponse(rsp *http.Response) (*CreatePendingInvoiceLineResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreatePendingInvoiceLineResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest InvoicePendingLineCreateResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseSimulateInvoiceResponse parses an HTTP response from a SimulateInvoiceWithResponse call +func ParseSimulateInvoiceResponse(rsp *http.Response) (*SimulateInvoiceResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SimulateInvoiceResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListInvoicesResponse parses an HTTP response from a ListInvoicesWithResponse call +func ParseListInvoicesResponse(rsp *http.Response) (*ListInvoicesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListInvoicesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest InvoicePaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseInvoicePendingLinesActionResponse parses an HTTP response from a InvoicePendingLinesActionWithResponse call +func ParseInvoicePendingLinesActionResponse(rsp *http.Response) (*InvoicePendingLinesActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &InvoicePendingLinesActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest []Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteInvoiceResponse parses an HTTP response from a DeleteInvoiceWithResponse call +func ParseDeleteInvoiceResponse(rsp *http.Response) (*DeleteInvoiceResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteInvoiceResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetInvoiceResponse parses an HTTP response from a GetInvoiceWithResponse call +func ParseGetInvoiceResponse(rsp *http.Response) (*GetInvoiceResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetInvoiceResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateInvoiceResponse parses an HTTP response from a UpdateInvoiceWithResponse call +func ParseUpdateInvoiceResponse(rsp *http.Response) (*UpdateInvoiceResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateInvoiceResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseAdvanceInvoiceActionResponse parses an HTTP response from a AdvanceInvoiceActionWithResponse call +func ParseAdvanceInvoiceActionResponse(rsp *http.Response) (*AdvanceInvoiceActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &AdvanceInvoiceActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseApproveInvoiceActionResponse parses an HTTP response from a ApproveInvoiceActionWithResponse call +func ParseApproveInvoiceActionResponse(rsp *http.Response) (*ApproveInvoiceActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ApproveInvoiceActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseRetryInvoiceActionResponse parses an HTTP response from a RetryInvoiceActionWithResponse call +func ParseRetryInvoiceActionResponse(rsp *http.Response) (*RetryInvoiceActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RetryInvoiceActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseSnapshotQuantitiesInvoiceActionResponse parses an HTTP response from a SnapshotQuantitiesInvoiceActionWithResponse call +func ParseSnapshotQuantitiesInvoiceActionResponse(rsp *http.Response) (*SnapshotQuantitiesInvoiceActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SnapshotQuantitiesInvoiceActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseRecalculateInvoiceTaxActionResponse parses an HTTP response from a RecalculateInvoiceTaxActionWithResponse call +func ParseRecalculateInvoiceTaxActionResponse(rsp *http.Response) (*RecalculateInvoiceTaxActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RecalculateInvoiceTaxActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseVoidInvoiceActionResponse parses an HTTP response from a VoidInvoiceActionWithResponse call +func ParseVoidInvoiceActionResponse(rsp *http.Response) (*VoidInvoiceActionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &VoidInvoiceActionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Invoice + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListBillingProfilesResponse parses an HTTP response from a ListBillingProfilesWithResponse call +func ParseListBillingProfilesResponse(rsp *http.Response) (*ListBillingProfilesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListBillingProfilesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BillingProfilePaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateBillingProfileResponse parses an HTTP response from a CreateBillingProfileWithResponse call +func ParseCreateBillingProfileResponse(rsp *http.Response) (*CreateBillingProfileResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateBillingProfileResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest BillingProfile + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteBillingProfileResponse parses an HTTP response from a DeleteBillingProfileWithResponse call +func ParseDeleteBillingProfileResponse(rsp *http.Response) (*DeleteBillingProfileResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteBillingProfileResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetBillingProfileResponse parses an HTTP response from a GetBillingProfileWithResponse call +func ParseGetBillingProfileResponse(rsp *http.Response) (*GetBillingProfileResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetBillingProfileResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BillingProfile + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateBillingProfileResponse parses an HTTP response from a UpdateBillingProfileWithResponse call +func ParseUpdateBillingProfileResponse(rsp *http.Response) (*UpdateBillingProfileResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateBillingProfileResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest BillingProfile + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListCustomersResponse parses an HTTP response from a ListCustomersWithResponse call +func ParseListCustomersResponse(rsp *http.Response) (*ListCustomersResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListCustomersResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CustomerPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateCustomerResponse parses an HTTP response from a CreateCustomerWithResponse call +func ParseCreateCustomerResponse(rsp *http.Response) (*CreateCustomerResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateCustomerResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Customer + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteCustomerResponse parses an HTTP response from a DeleteCustomerWithResponse call +func ParseDeleteCustomerResponse(rsp *http.Response) (*DeleteCustomerResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteCustomerResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerResponse parses an HTTP response from a GetCustomerWithResponse call +func ParseGetCustomerResponse(rsp *http.Response) (*GetCustomerResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Customer + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateCustomerResponse parses an HTTP response from a UpdateCustomerWithResponse call +func ParseUpdateCustomerResponse(rsp *http.Response) (*UpdateCustomerResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateCustomerResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Customer + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerAccessResponse parses an HTTP response from a GetCustomerAccessWithResponse call +func ParseGetCustomerAccessResponse(rsp *http.Response) (*GetCustomerAccessResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerAccessResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CustomerAccess + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListCustomerAppDataResponse parses an HTTP response from a ListCustomerAppDataWithResponse call +func ParseListCustomerAppDataResponse(rsp *http.Response) (*ListCustomerAppDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListCustomerAppDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest CustomerAppDataPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpsertCustomerAppDataResponse parses an HTTP response from a UpsertCustomerAppDataWithResponse call +func ParseUpsertCustomerAppDataResponse(rsp *http.Response) (*UpsertCustomerAppDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpsertCustomerAppDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []CustomerAppData + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteCustomerAppDataResponse parses an HTTP response from a DeleteCustomerAppDataWithResponse call +func ParseDeleteCustomerAppDataResponse(rsp *http.Response) (*DeleteCustomerAppDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteCustomerAppDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerEntitlementValueResponse parses an HTTP response from a GetCustomerEntitlementValueWithResponse call +func ParseGetCustomerEntitlementValueResponse(rsp *http.Response) (*GetCustomerEntitlementValueResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerEntitlementValueResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementValue + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerStripeAppDataResponse parses an HTTP response from a GetCustomerStripeAppDataWithResponse call +func ParseGetCustomerStripeAppDataResponse(rsp *http.Response) (*GetCustomerStripeAppDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerStripeAppDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest StripeCustomerAppData + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpsertCustomerStripeAppDataResponse parses an HTTP response from a UpsertCustomerStripeAppDataWithResponse call +func ParseUpsertCustomerStripeAppDataResponse(rsp *http.Response) (*UpsertCustomerStripeAppDataResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpsertCustomerStripeAppDataResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest StripeCustomerAppData + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateCustomerStripePortalSessionResponse parses an HTTP response from a CreateCustomerStripePortalSessionWithResponse call +func ParseCreateCustomerStripePortalSessionResponse(rsp *http.Response) (*CreateCustomerStripePortalSessionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateCustomerStripePortalSessionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest StripeCustomerPortalSession + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListCustomerSubscriptionsResponse parses an HTTP response from a ListCustomerSubscriptionsWithResponse call +func ParseListCustomerSubscriptionsResponse(rsp *http.Response) (*ListCustomerSubscriptionsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListCustomerSubscriptionsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SubscriptionPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetDebugMetricsResponse parses an HTTP response from a GetDebugMetricsWithResponse call +func ParseGetDebugMetricsResponse(rsp *http.Response) (*GetDebugMetricsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetDebugMetricsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListEntitlementsResponse parses an HTTP response from a ListEntitlementsWithResponse call +func ParseListEntitlementsResponse(rsp *http.Response) (*ListEntitlementsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListEntitlementsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ListEntitlementsResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetEntitlementByIdResponse parses an HTTP response from a GetEntitlementByIdWithResponse call +func ParseGetEntitlementByIdResponse(rsp *http.Response) (*GetEntitlementByIdResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEntitlementByIdResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Entitlement + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListEventsResponse parses an HTTP response from a ListEventsWithResponse call +func ParseListEventsResponse(rsp *http.Response) (*ListEventsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListEventsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []IngestedEvent + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseIngestEventsResponse parses an HTTP response from a IngestEventsWithResponse call +func ParseIngestEventsResponse(rsp *http.Response) (*IngestEventsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &IngestEventsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListFeaturesResponse parses an HTTP response from a ListFeaturesWithResponse call +func ParseListFeaturesResponse(rsp *http.Response) (*ListFeaturesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListFeaturesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ListFeaturesResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateFeatureResponse parses an HTTP response from a CreateFeatureWithResponse call +func ParseCreateFeatureResponse(rsp *http.Response) (*CreateFeatureResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateFeatureResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Feature + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteFeatureResponse parses an HTTP response from a DeleteFeatureWithResponse call +func ParseDeleteFeatureResponse(rsp *http.Response) (*DeleteFeatureResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteFeatureResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetFeatureResponse parses an HTTP response from a GetFeatureWithResponse call +func ParseGetFeatureResponse(rsp *http.Response) (*GetFeatureResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetFeatureResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Feature + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListGrantsResponse parses an HTTP response from a ListGrantsWithResponse call +func ParseListGrantsResponse(rsp *http.Response) (*ListGrantsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListGrantsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest struct { + union json.RawMessage + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseVoidGrantResponse parses an HTTP response from a VoidGrantWithResponse call +func ParseVoidGrantResponse(rsp *http.Response) (*VoidGrantResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &VoidGrantResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListCurrenciesResponse parses an HTTP response from a ListCurrenciesWithResponse call +func ParseListCurrenciesResponse(rsp *http.Response) (*ListCurrenciesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListCurrenciesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []Currency + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetProgressResponse parses an HTTP response from a GetProgressWithResponse call +func ParseGetProgressResponse(rsp *http.Response) (*GetProgressResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetProgressResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Progress + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListMarketplaceListingsResponse parses an HTTP response from a ListMarketplaceListingsWithResponse call +func ParseListMarketplaceListingsResponse(rsp *http.Response) (*ListMarketplaceListingsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMarketplaceListingsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MarketplaceListingPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetMarketplaceListingResponse parses an HTTP response from a GetMarketplaceListingWithResponse call +func ParseGetMarketplaceListingResponse(rsp *http.Response) (*GetMarketplaceListingResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMarketplaceListingResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MarketplaceListing + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseMarketplaceAppInstallResponse parses an HTTP response from a MarketplaceAppInstallWithResponse call +func ParseMarketplaceAppInstallResponse(rsp *http.Response) (*MarketplaceAppInstallResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &MarketplaceAppInstallResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MarketplaceInstallResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseMarketplaceAppAPIKeyInstallResponse parses an HTTP response from a MarketplaceAppAPIKeyInstallWithResponse call +func ParseMarketplaceAppAPIKeyInstallResponse(rsp *http.Response) (*MarketplaceAppAPIKeyInstallResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &MarketplaceAppAPIKeyInstallResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MarketplaceInstallResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseMarketplaceOAuth2InstallGetURLResponse parses an HTTP response from a MarketplaceOAuth2InstallGetURLWithResponse call +func ParseMarketplaceOAuth2InstallGetURLResponse(rsp *http.Response) (*MarketplaceOAuth2InstallGetURLResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &MarketplaceOAuth2InstallGetURLResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest ClientAppStartResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseMarketplaceOAuth2InstallAuthorizeResponse parses an HTTP response from a MarketplaceOAuth2InstallAuthorizeWithResponse call +func ParseMarketplaceOAuth2InstallAuthorizeResponse(rsp *http.Response) (*MarketplaceOAuth2InstallAuthorizeResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &MarketplaceOAuth2InstallAuthorizeResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListMetersResponse parses an HTTP response from a ListMetersWithResponse call +func ParseListMetersResponse(rsp *http.Response) (*ListMetersResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMetersResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []Meter + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateMeterResponse parses an HTTP response from a CreateMeterWithResponse call +func ParseCreateMeterResponse(rsp *http.Response) (*CreateMeterResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateMeterResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Meter + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteMeterResponse parses an HTTP response from a DeleteMeterWithResponse call +func ParseDeleteMeterResponse(rsp *http.Response) (*DeleteMeterResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteMeterResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetMeterResponse parses an HTTP response from a GetMeterWithResponse call +func ParseGetMeterResponse(rsp *http.Response) (*GetMeterResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetMeterResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Meter + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateMeterResponse parses an HTTP response from a UpdateMeterWithResponse call +func ParseUpdateMeterResponse(rsp *http.Response) (*UpdateMeterResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateMeterResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Meter + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListMeterGroupByValuesResponse parses an HTTP response from a ListMeterGroupByValuesWithResponse call +func ParseListMeterGroupByValuesResponse(rsp *http.Response) (*ListMeterGroupByValuesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMeterGroupByValuesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []string + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseQueryMeterResponse parses an HTTP response from a QueryMeterWithResponse call +func ParseQueryMeterResponse(rsp *http.Response) (*QueryMeterResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &QueryMeterResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MeterQueryResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + case rsp.StatusCode == 200: + // Content-type (text/csv) unsupported + + } + + return response, nil +} + +// ParseQueryMeterPostResponse parses an HTTP response from a QueryMeterPostWithResponse call +func ParseQueryMeterPostResponse(rsp *http.Response) (*QueryMeterPostResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &QueryMeterPostResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MeterQueryResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + case rsp.StatusCode == 200: + // Content-type (text/csv) unsupported + + } + + return response, nil +} + +// ParseListMeterSubjectsResponse parses an HTTP response from a ListMeterSubjectsWithResponse call +func ParseListMeterSubjectsResponse(rsp *http.Response) (*ListMeterSubjectsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListMeterSubjectsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []string + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListNotificationChannelsResponse parses an HTTP response from a ListNotificationChannelsWithResponse call +func ParseListNotificationChannelsResponse(rsp *http.Response) (*ListNotificationChannelsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListNotificationChannelsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationChannelPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateNotificationChannelResponse parses an HTTP response from a CreateNotificationChannelWithResponse call +func ParseCreateNotificationChannelResponse(rsp *http.Response) (*CreateNotificationChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateNotificationChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest NotificationChannel + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteNotificationChannelResponse parses an HTTP response from a DeleteNotificationChannelWithResponse call +func ParseDeleteNotificationChannelResponse(rsp *http.Response) (*DeleteNotificationChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteNotificationChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetNotificationChannelResponse parses an HTTP response from a GetNotificationChannelWithResponse call +func ParseGetNotificationChannelResponse(rsp *http.Response) (*GetNotificationChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNotificationChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationChannel + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateNotificationChannelResponse parses an HTTP response from a UpdateNotificationChannelWithResponse call +func ParseUpdateNotificationChannelResponse(rsp *http.Response) (*UpdateNotificationChannelResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateNotificationChannelResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationChannel + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListNotificationEventsResponse parses an HTTP response from a ListNotificationEventsWithResponse call +func ParseListNotificationEventsResponse(rsp *http.Response) (*ListNotificationEventsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListNotificationEventsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationEventPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetNotificationEventResponse parses an HTTP response from a GetNotificationEventWithResponse call +func ParseGetNotificationEventResponse(rsp *http.Response) (*GetNotificationEventResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNotificationEventResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationEvent + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseResendNotificationEventResponse parses an HTTP response from a ResendNotificationEventWithResponse call +func ParseResendNotificationEventResponse(rsp *http.Response) (*ResendNotificationEventResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ResendNotificationEventResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListNotificationRulesResponse parses an HTTP response from a ListNotificationRulesWithResponse call +func ParseListNotificationRulesResponse(rsp *http.Response) (*ListNotificationRulesResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListNotificationRulesResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationRulePaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateNotificationRuleResponse parses an HTTP response from a CreateNotificationRuleWithResponse call +func ParseCreateNotificationRuleResponse(rsp *http.Response) (*CreateNotificationRuleResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateNotificationRuleResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest NotificationRule + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteNotificationRuleResponse parses an HTTP response from a DeleteNotificationRuleWithResponse call +func ParseDeleteNotificationRuleResponse(rsp *http.Response) (*DeleteNotificationRuleResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteNotificationRuleResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetNotificationRuleResponse parses an HTTP response from a GetNotificationRuleWithResponse call +func ParseGetNotificationRuleResponse(rsp *http.Response) (*GetNotificationRuleResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetNotificationRuleResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationRule + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateNotificationRuleResponse parses an HTTP response from a UpdateNotificationRuleWithResponse call +func ParseUpdateNotificationRuleResponse(rsp *http.Response) (*UpdateNotificationRuleResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateNotificationRuleResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest NotificationRule + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseTestNotificationRuleResponse parses an HTTP response from a TestNotificationRuleWithResponse call +func ParseTestNotificationRuleResponse(rsp *http.Response) (*TestNotificationRuleResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &TestNotificationRuleResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest NotificationEvent + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListPlansResponse parses an HTTP response from a ListPlansWithResponse call +func ParseListPlansResponse(rsp *http.Response) (*ListPlansResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListPlansResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PlanPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreatePlanResponse parses an HTTP response from a CreatePlanWithResponse call +func ParseCreatePlanResponse(rsp *http.Response) (*CreatePlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreatePlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Plan + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseNextPlanResponse parses an HTTP response from a NextPlanWithResponse call +func ParseNextPlanResponse(rsp *http.Response) (*NextPlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &NextPlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Plan + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeletePlanResponse parses an HTTP response from a DeletePlanWithResponse call +func ParseDeletePlanResponse(rsp *http.Response) (*DeletePlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeletePlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetPlanResponse parses an HTTP response from a GetPlanWithResponse call +func ParseGetPlanResponse(rsp *http.Response) (*GetPlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetPlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Plan + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdatePlanResponse parses an HTTP response from a UpdatePlanWithResponse call +func ParseUpdatePlanResponse(rsp *http.Response) (*UpdatePlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdatePlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Plan + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListPlanAddonsResponse parses an HTTP response from a ListPlanAddonsWithResponse call +func ParseListPlanAddonsResponse(rsp *http.Response) (*ListPlanAddonsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListPlanAddonsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PlanAddonPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreatePlanAddonResponse parses an HTTP response from a CreatePlanAddonWithResponse call +func ParseCreatePlanAddonResponse(rsp *http.Response) (*CreatePlanAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreatePlanAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest PlanAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeletePlanAddonResponse parses an HTTP response from a DeletePlanAddonWithResponse call +func ParseDeletePlanAddonResponse(rsp *http.Response) (*DeletePlanAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeletePlanAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetPlanAddonResponse parses an HTTP response from a GetPlanAddonWithResponse call +func ParseGetPlanAddonResponse(rsp *http.Response) (*GetPlanAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetPlanAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PlanAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdatePlanAddonResponse parses an HTTP response from a UpdatePlanAddonWithResponse call +func ParseUpdatePlanAddonResponse(rsp *http.Response) (*UpdatePlanAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdatePlanAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PlanAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseArchivePlanResponse parses an HTTP response from a ArchivePlanWithResponse call +func ParseArchivePlanResponse(rsp *http.Response) (*ArchivePlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ArchivePlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Plan + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParsePublishPlanResponse parses an HTTP response from a PublishPlanWithResponse call +func ParsePublishPlanResponse(rsp *http.Response) (*PublishPlanResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &PublishPlanResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Plan + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseQueryPortalMeterResponse parses an HTTP response from a QueryPortalMeterWithResponse call +func ParseQueryPortalMeterResponse(rsp *http.Response) (*QueryPortalMeterResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &QueryPortalMeterResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest MeterQueryResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + case rsp.StatusCode == 200: + // Content-type (text/csv) unsupported + + } + + return response, nil +} + +// ParseListPortalTokensResponse parses an HTTP response from a ListPortalTokensWithResponse call +func ParseListPortalTokensResponse(rsp *http.Response) (*ListPortalTokensResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListPortalTokensResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []PortalToken + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreatePortalTokenResponse parses an HTTP response from a CreatePortalTokenWithResponse call +func ParseCreatePortalTokenResponse(rsp *http.Response) (*CreatePortalTokenResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreatePortalTokenResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PortalToken + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseInvalidatePortalTokensResponse parses an HTTP response from a InvalidatePortalTokensWithResponse call +func ParseInvalidatePortalTokensResponse(rsp *http.Response) (*InvalidatePortalTokensResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &InvalidatePortalTokensResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateStripeCheckoutSessionResponse parses an HTTP response from a CreateStripeCheckoutSessionWithResponse call +func ParseCreateStripeCheckoutSessionResponse(rsp *http.Response) (*CreateStripeCheckoutSessionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateStripeCheckoutSessionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest CreateStripeCheckoutSessionResult + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListSubjectsResponse parses an HTTP response from a ListSubjectsWithResponse call +func ParseListSubjectsResponse(rsp *http.Response) (*ListSubjectsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListSubjectsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []Subject + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpsertSubjectResponse parses an HTTP response from a UpsertSubjectWithResponse call +func ParseUpsertSubjectResponse(rsp *http.Response) (*UpsertSubjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpsertSubjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []Subject + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteSubjectResponse parses an HTTP response from a DeleteSubjectWithResponse call +func ParseDeleteSubjectResponse(rsp *http.Response) (*DeleteSubjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteSubjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetSubjectResponse parses an HTTP response from a GetSubjectWithResponse call +func ParseGetSubjectResponse(rsp *http.Response) (*GetSubjectResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetSubjectResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Subject + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListSubjectEntitlementsResponse parses an HTTP response from a ListSubjectEntitlementsWithResponse call +func ParseListSubjectEntitlementsResponse(rsp *http.Response) (*ListSubjectEntitlementsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListSubjectEntitlementsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []Entitlement + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateEntitlementResponse parses an HTTP response from a CreateEntitlementWithResponse call +func ParseCreateEntitlementResponse(rsp *http.Response) (*CreateEntitlementResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateEntitlementResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Entitlement + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListEntitlementGrantsResponse parses an HTTP response from a ListEntitlementGrantsWithResponse call +func ParseListEntitlementGrantsResponse(rsp *http.Response) (*ListEntitlementGrantsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListEntitlementGrantsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []EntitlementGrant + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateGrantResponse parses an HTTP response from a CreateGrantWithResponse call +func ParseCreateGrantResponse(rsp *http.Response) (*CreateGrantResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateGrantResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest EntitlementGrant + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseOverrideEntitlementResponse parses an HTTP response from a OverrideEntitlementWithResponse call +func ParseOverrideEntitlementResponse(rsp *http.Response) (*OverrideEntitlementResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &OverrideEntitlementResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Entitlement + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetEntitlementValueResponse parses an HTTP response from a GetEntitlementValueWithResponse call +func ParseGetEntitlementValueResponse(rsp *http.Response) (*GetEntitlementValueResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEntitlementValueResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementValue + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteEntitlementResponse parses an HTTP response from a DeleteEntitlementWithResponse call +func ParseDeleteEntitlementResponse(rsp *http.Response) (*DeleteEntitlementResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteEntitlementResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetEntitlementResponse parses an HTTP response from a GetEntitlementWithResponse call +func ParseGetEntitlementResponse(rsp *http.Response) (*GetEntitlementResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEntitlementResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Entitlement + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetEntitlementHistoryResponse parses an HTTP response from a GetEntitlementHistoryWithResponse call +func ParseGetEntitlementHistoryResponse(rsp *http.Response) (*GetEntitlementHistoryResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEntitlementHistoryResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest WindowedBalanceHistory + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseResetEntitlementUsageResponse parses an HTTP response from a ResetEntitlementUsageWithResponse call +func ParseResetEntitlementUsageResponse(rsp *http.Response) (*ResetEntitlementUsageResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ResetEntitlementUsageResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateSubscriptionResponse parses an HTTP response from a CreateSubscriptionWithResponse call +func ParseCreateSubscriptionResponse(rsp *http.Response) (*CreateSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest Subscription + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteSubscriptionResponse parses an HTTP response from a DeleteSubscriptionWithResponse call +func ParseDeleteSubscriptionResponse(rsp *http.Response) (*DeleteSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetSubscriptionResponse parses an HTTP response from a GetSubscriptionWithResponse call +func ParseGetSubscriptionResponse(rsp *http.Response) (*GetSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SubscriptionExpanded + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseEditSubscriptionResponse parses an HTTP response from a EditSubscriptionWithResponse call +func ParseEditSubscriptionResponse(rsp *http.Response) (*EditSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &EditSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Subscription + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListSubscriptionAddonsResponse parses an HTTP response from a ListSubscriptionAddonsWithResponse call +func ParseListSubscriptionAddonsResponse(rsp *http.Response) (*ListSubscriptionAddonsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListSubscriptionAddonsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []SubscriptionAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateSubscriptionAddonResponse parses an HTTP response from a CreateSubscriptionAddonWithResponse call +func ParseCreateSubscriptionAddonResponse(rsp *http.Response) (*CreateSubscriptionAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateSubscriptionAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest SubscriptionAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetSubscriptionAddonResponse parses an HTTP response from a GetSubscriptionAddonWithResponse call +func ParseGetSubscriptionAddonResponse(rsp *http.Response) (*GetSubscriptionAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetSubscriptionAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SubscriptionAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUpdateSubscriptionAddonResponse parses an HTTP response from a UpdateSubscriptionAddonWithResponse call +func ParseUpdateSubscriptionAddonResponse(rsp *http.Response) (*UpdateSubscriptionAddonResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UpdateSubscriptionAddonResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SubscriptionAddon + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCancelSubscriptionResponse parses an HTTP response from a CancelSubscriptionWithResponse call +func ParseCancelSubscriptionResponse(rsp *http.Response) (*CancelSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CancelSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Subscription + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseChangeSubscriptionResponse parses an HTTP response from a ChangeSubscriptionWithResponse call +func ParseChangeSubscriptionResponse(rsp *http.Response) (*ChangeSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ChangeSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SubscriptionChangeResponseBody + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseMigrateSubscriptionResponse parses an HTTP response from a MigrateSubscriptionWithResponse call +func ParseMigrateSubscriptionResponse(rsp *http.Response) (*MigrateSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &MigrateSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest SubscriptionChangeResponseBody + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseRestoreSubscriptionResponse parses an HTTP response from a RestoreSubscriptionWithResponse call +func ParseRestoreSubscriptionResponse(rsp *http.Response) (*RestoreSubscriptionResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &RestoreSubscriptionResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Subscription + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseUnscheduleCancelationResponse parses an HTTP response from a UnscheduleCancelationWithResponse call +func ParseUnscheduleCancelationResponse(rsp *http.Response) (*UnscheduleCancelationResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &UnscheduleCancelationResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Subscription + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest SubscriptionBadRequestErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest SubscriptionConflictErrorResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListCustomerEntitlementsV2Response parses an HTTP response from a ListCustomerEntitlementsV2WithResponse call +func ParseListCustomerEntitlementsV2Response(rsp *http.Response) (*ListCustomerEntitlementsV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListCustomerEntitlementsV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementV2PaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateCustomerEntitlementV2Response parses an HTTP response from a CreateCustomerEntitlementV2WithResponse call +func ParseCreateCustomerEntitlementV2Response(rsp *http.Response) (*CreateCustomerEntitlementV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateCustomerEntitlementV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest EntitlementV2 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseDeleteCustomerEntitlementV2Response parses an HTTP response from a DeleteCustomerEntitlementV2WithResponse call +func ParseDeleteCustomerEntitlementV2Response(rsp *http.Response) (*DeleteCustomerEntitlementV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &DeleteCustomerEntitlementV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerEntitlementV2Response parses an HTTP response from a GetCustomerEntitlementV2WithResponse call +func ParseGetCustomerEntitlementV2Response(rsp *http.Response) (*GetCustomerEntitlementV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerEntitlementV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementV2 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListCustomerEntitlementGrantsV2Response parses an HTTP response from a ListCustomerEntitlementGrantsV2WithResponse call +func ParseListCustomerEntitlementGrantsV2Response(rsp *http.Response) (*ListCustomerEntitlementGrantsV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListCustomerEntitlementGrantsV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest GrantV2PaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseCreateCustomerEntitlementGrantV2Response parses an HTTP response from a CreateCustomerEntitlementGrantV2WithResponse call +func ParseCreateCustomerEntitlementGrantV2Response(rsp *http.Response) (*CreateCustomerEntitlementGrantV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateCustomerEntitlementGrantV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest EntitlementGrantV2 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerEntitlementHistoryV2Response parses an HTTP response from a GetCustomerEntitlementHistoryV2WithResponse call +func ParseGetCustomerEntitlementHistoryV2Response(rsp *http.Response) (*GetCustomerEntitlementHistoryV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerEntitlementHistoryV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest WindowedBalanceHistory + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseOverrideCustomerEntitlementV2Response parses an HTTP response from a OverrideCustomerEntitlementV2WithResponse call +func ParseOverrideCustomerEntitlementV2Response(rsp *http.Response) (*OverrideCustomerEntitlementV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &OverrideCustomerEntitlementV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest EntitlementV2 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409: + var dest ConflictProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON409 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseResetCustomerEntitlementUsageV2Response parses an HTTP response from a ResetCustomerEntitlementUsageV2WithResponse call +func ParseResetCustomerEntitlementUsageV2Response(rsp *http.Response) (*ResetCustomerEntitlementUsageV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ResetCustomerEntitlementUsageV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetCustomerEntitlementValueV2Response parses an HTTP response from a GetCustomerEntitlementValueV2WithResponse call +func ParseGetCustomerEntitlementValueV2Response(rsp *http.Response) (*GetCustomerEntitlementValueV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetCustomerEntitlementValueV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementValueV2 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListEntitlementsV2Response parses an HTTP response from a ListEntitlementsV2WithResponse call +func ParseListEntitlementsV2Response(rsp *http.Response) (*ListEntitlementsV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListEntitlementsV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementV2PaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseGetEntitlementByIdV2Response parses an HTTP response from a GetEntitlementByIdV2WithResponse call +func ParseGetEntitlementByIdV2Response(rsp *http.Response) (*GetEntitlementByIdV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetEntitlementByIdV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest EntitlementV2 + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest NotFoundProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListEventsV2Response parses an HTTP response from a ListEventsV2WithResponse call +func ParseListEventsV2Response(rsp *http.Response) (*ListEventsV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListEventsV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest IngestedEventCursorPaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// ParseListGrantsV2Response parses an HTTP response from a ListGrantsV2WithResponse call +func ParseListGrantsV2Response(rsp *http.Response) (*ListGrantsV2Response, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListGrantsV2Response{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest GrantV2PaginatedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest BadRequestProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest UnauthorizedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ForbiddenProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 412: + var dest PreconditionFailedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON412 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest InternalServerErrorProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON500 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503: + var dest ServiceUnavailableProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSON503 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && true: + var dest UnexpectedProblemResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.ApplicationproblemJSONDefault = &dest + + } + + return response, nil +} + +// Base64 encoded, gzipped, json marshaled Swagger object +var swaggerSpec = []string{ + + "H4sIAAAAAAAC/+y963IcN7Ig/CqI3tmwdE6zTUm251hfTJygSHnMHV14SMr+Zqb10WAV2I1RNVADoEi2", + "HYrYN9jfu7/2MfZ5zgvsK3yBTACFqkJ1V/OimztiYix2VQGJRCKR9/xtlMlFKQUTRo+e/jYqqaILZpiC", + "v/byXIrXKmfq2RL+w8VsIu0/7NOc6Uzx0nApRk9Hp3NG4BHJuWKZ/XUyGo/YdVnInI2eXtBCs/GI23f/", + "WTG1HI1Hgi7Y6OkIRxyPdDZnC2qHpkXx+mL09O+/jf6g2MXo6ei/fF3D+TW+p78+kcoAWKP3b8ejnF3Q", + "qjCjp6O9k/3R+/FIm2Vhh7+QamH/7l/Ns+Wq9ZwvyQVnRb7Rcp4tGwtatYwYrhTcz3hRcDE7UvKCF2y/", + "0kYumHp9yZTiOftitucGy/y4+zYI4PUrfcG1aX+sj+w51JPzxpvdxf7AC4MrdW+SEl+1a06tsTVgvFRu", + "2EJ3p3jz4vCAPHgj+CVTmhbFkrwR/J8VIy/YNc/kTNFyzjN4YDecnheMHOZMGH7BmXqIyKeLEjCw++jP", + "3337tz9+++3eDz/v/eXH548ev/rr7v5/fP/Dj6PxqKTGMGXn/P/+vrvzx7d/3935fm/nx//2l5evjnZO", + "f9r5G92Z/+PdQpQ75nLn17e/Pf72/R9G45FZlnZobSxdWPS6H6hS9Jboz9zvh/kq1Pu3CM/70B4NtEX5", + "IJT/hS0H4fwdWw483vHI8SZ0FnN74F/BjAOgt6BNNoQfBr/nBRwpvqBq+XxBeTFoISV+QBh8sdmCGpPd", + "88L0z9zMZWWOuBAs7+Wrr0WxJIqZSomwRk2u8FtSwsdtlqsn5HTONeGLsuAZN8WSaGY04SIrqpztFcV+", + "GMlIYlTF1rGLNLQJFJ1LWTAqbocjdl1SkeB0z+F3YuaMKKZLKTQDVBCa59y+QwuSM0N5ofsW5IZO8r6b", + "X7EI2N3yn8RudTFyiC8lSCMcCOnHnUzFVBxeWFqw2w7ngUhLXxah9Qi6ZBm/cGydai0zTg3LHabbxEau", + "eFGQc+aIlOWtaSx1jQkXJKN2uguYzIlg7bHGhBZFYy2toXs2NYWqeIeDxAfAbEyqX6hg+8kLsisE1/1K", + "aamO6IwLCojO4Ic07PiM0At7V1zNeTa3hKkNVQaosayHGXxhwGwbXREdkAu+4CYNMTzyh2Vz8HDk5Al4", + "tLs7Hi3oNV9UC/8XF+6vcDS4MGxmqSq1DMeuvpRDsXJBH/c4tEBbBf1JdR5g/OK2Zu3iPo1tSoCZWtVz", + "Ybgp2IIJ88Xs1Lo1fdwN6kKXWsMPjJpKfTm3/ar1fNz9aEKWgv3Pin5Bp6N/NR93H2K4UnAfikvJM9BS", + "vPaqmNUF9qwotUod5/glce8TwxdsMhWgrmh+2a9vxuPHy6jNSI93Hz/Z2X20s/vodPfRU/jfZHf30d9G", + "Y4Cb2n3IqWE7ds6UiWjwKp+xC6nYPS7TTfDx1tmvWCYsK4cH64wEv0+TYhevffaLn+fUkJIqo71sX3Bt", + "iKxMWYGyjB9abdk+4GKm79iM4WAdbq9ILc4wkbP8xFBTaaaHnA//jVW68KO+ZbXGTi7wDnbIWQwOWMEM", + "y/vtKjm+4BeiBzLi1vCb2ckS0GpdbcB08fXBzCge/aOxIgRiOMe90Ro/Nr8tmeLSErcyazcT3/VWioHL", + "7EzwKSx1/abedq0fe1/1AFZoub0nXny/b2F6JfMbwN2Re27AGL8YQXvVej6uqN2ELAX7C77g5vXFhWam", + "zzT4qlqcM2VlByAHKzGgaRxs7gfOqM41ebS7ex+2wo2NhfGaJPxn0KL0O162lzR4QW6e5IriBewOWcBL", + "qt4xUxY0Y3sl/wtbHgptaFEcs39WTJsJjpAiK/vES3m0LO2yOH4bzn1JzbyGG4YajxT7Z8WVlUnQWTEw", + "cqcsT+3375swf17Qvt6rzPyxg9n+Wyr+K/ukgWfmC7KE96/m4/LOGK5euP/DzjGh+SUVGcvhpz8rWZXP", + "lngHw+WZSWGYACZEy7LgGbhVvv6Htiv6LcZvcCgfKVkyZThbe/viPCdBbgjSRWeq8QjskXYnHLwEQh3J", + "zEKM+ESY31sqa0UElM7TTVd/O5mKv8qKZFSQSjNi5hx4Kz4lF1KRS1pULKii0SjP3Ib2iiir0NzckKzg", + "TJhU2NI+PCGHB1PxRrOLqkBvMc3ekVLJmWIaQKME5h7smfPzxcS1oNcvmJiZ+ejpk+/gCvB/Phog70Wr", + "QeTtrw3G4mJmd2JRFYaXReRch1vtB6mIk0+fkn9vj/kn//LOo2m1u/v4u/4XHvdsTwfMYWr0gl4f4kO4", + "+dcJjx28OEJApJSKZdTUzLWJphNuVx8ToydfjGCw+MkMWVCTzXtx5ub7+yUTuVRv/yRLJiiPkebfWMic", + "FW//NCvNzjc7plLn0o75n//rf//f//M/yNnZQYD27OwpeaMZ+WUFhf8Ctwuj+Urse2SMB3CVPoOGPP8H", + "y0yM+5yx8nX4Nd4BJRddagTtiATthnBBjn/YJ0+ePPmeIHvCaI2gayVQreTiT493H3/rdajd//pkz/3f", + "ZHd39299WLAAfSCNLMLDLKbBhkXngghpfHALywklmotZwQidzRSbUdMNZQHCZDSbE10B0gmEH1lMXnGR", + "y6vJVPziHv1ihVRKFNNMXbK8ZsfAZROIdZD+yX2PZOt/BILtwewsQVk3t41FuHOQDGVq7vUUT3OP/No8", + "J2v/3Me/PCB3vkIjE0FlIr/dCTHSnY/Hm5wPIz/C6UCqPeG/svUHZFyfkErT2dpzYmUIJgxXzCy9TFGf", + "NmfiSR4oIOgEYmto/3Sw99eBAkC0xKHy5c/1J0PQd8oX7G9S9CgjcNwtL7DrtzB5XAB5/SoFI1STnF1w", + "AXZleHa492qP2HGJHZgcUEPPqWbkwdyY8unXX19dXU04FXQi1exrO9COHUg/nECkXWvb7IBvTvdhQpjP", + "b1elXXReCs1+VX96c7q/EaoDOpIa9wiHW0ukr6SBmEOLyf05FYIVX4xeNXRtH1fL6ody3ZqeX35JoSzD", + "Vvbp7FUM47r1HFdfUDTroIV9OvsUgZhaDRq/vNULT6HMGYRoPFdKKu9+tf9OSDH2Z5LJ3Eoox86whaoU", + "XMzw2AfND10uzjV0sWtXgGazWy79rLHu3/qMI/NqQcWOYjSHCALDrg0plbzkuRVjo3wBLlCq4lKMp8Je", + "kcRIQrXmGqOD0aJAcnbJCqu02Tu7EjlT2lABo9UINnNqiMyySimWb4TlxrI2iiveDHuV4iuwVilOOAZb", + "LAFPbTxesXNSWmHQUtZURMgj9FxWpsbFmHhcItpZhMypqLHZzt9YMeRG+LQLvTM8nlRZxnRI4QEI2khs", + "fAkn0cea10QEklhBDbPyVzanYsZAJKaCUJiBGPmOieQR1gjDxocYoL0nTGhDTQIVAXiOou8UfJpsOiIh", + "q5tcUU1Kqy0L46VghyTaQKRy5v+psGwbzUIoYyuWMW5V7QslF9EAT62Ii0FFY6KoyOWiWJIZE0xRYwVk", + "WVJ4ZnUPIcXOrGJaA3kjTvAYc0000OrVnAn0TcOREACgPSNZA0IY7pIWPMdsGftVqaTFlmcSm24donej", + "vYvyC+w57e7NkT29XOTsuuM0HAoWDJz2GG7qIGyBm9ZM7cY7NyQRLW+hZSH2y1t4QMPE9+QEPSqo+LLq", + "F6xe0ccVudqw9cH/RW3GJ7oPK7agiDIf98rygBrq7pS0n9cF0oRg1JwaatcA/t5lOZilOtfvhq7eLvww", + "rF/An1NxDd1gzzolsxXwecdBnh6s4VGejdW84Np8wiGsd7G6TcM/a//d7QNAw4F2n68PCO3C/25FTYI6", + "ffZ8Sd6x5WQq9qlmO1xoJjQ3/JLBBnJaOP/awDW927RcQRdusaocQQNwqEdwV5CLjQsVdEEvCyr+MhTt", + "kLZZUGHx784JV0RX+tx/OFg4cdPeFvohZRQaS2jUUbiznShvXGGhu6Y17qrmcpwLwxjFzysQ293nd7a0", + "lNNq2KrAw3AjvoQFsj4CU3rvP66rcyU04jzfsVp8Ucgr7XIArCqkozxJ5+63fJ4abnUwS/G6YxawqltG", + "FYaklA3vORVCGtAh9HAhay/6CMWsht+cQfb1O7bcQV2zpFxpsqCCzljuT7heasMWE7IPEJBzRhYyR3cX", + "UBxTE4gyo/lrUSxD9QEf+hNDMA6ZT6mMcL5g2tBFaWECvdIpk7JSGQNN2n3dzI55vPv4m008iX2Q7tvB", + "7ZE57fE4gr1LZMvh6N93X+xbmm2KuW9ODkbjdBY/fIKmFR/uByQ2iSKq/MgjCJwCSr8hTkumFtSCXSz9", + "gbsf/MKBXIXfYSbP6GePHr+eCXnp9OdHu4+/IdmcKpp51hFFR9mnMVyxSbIDFbu4sArRJfshGXti98yu", + "PoqZ8GjGXSPnLJMLpkkYaEJ+tq8k/JnuCwixyBW9MJ2deHIXO/HcQ+JyEXK0v/Qv/VTeZOFcEyFJIcWM", + "qc1WH14GE84FF9ywYnnfyGAuRCKFCp64pvZIhTl9PCTuhRCBQJL3nsjXty7IY+yuQ2hDRcZOnfo58Bqx", + "N99h/Gn3MjmFzI/6lSbv0nB/2MtjOsJwi+mISEWmIx9oMx3F/K052XiUVAX2iGYLvjNsF6Lz/9037ejI", + "GPd059fdne/f/uuDf396Fv54+C9/iKBDUbUbWcgMtRr7cMS+9F908blXSwV+3OS6RFUU9NyC1dz/MHQi", + "zi6toPzYdIJAVEdnRvKMmSvGBHkEB//xt9/189nH33bDUD3T5bosKCpAKVRaQWjfCkJpxmMfExCUulfk", + "IPX62I0PirWD6TgMOkpp25BttNmR8SlKycOCI7bgn4p9uSgrK/WeU81yIpGlshbLtrj3/Eo/nYodvC/I", + "nyzLbVxZ9hnFT//UfEKm1e7uk8x+cuX+TSKWDx+qbA7Oh/jbUxl/uYIF1RlaVZnfQuwrqDbEDXE/sskL", + "O8MbmKFXPHFODy4F+BsTlPkCbEQXpH4TPXp6MFn+1JwDzmrrfPct4af2pAkivmRKB+mqdmY0V/ETvtQi", + "THIoMgW1RbzXp3llR9sT+w16oXWQdD0L7+OMlb/bi3fsLRu18hBT1NiZbC7DkI1LLpLbwymO+UtiY98m", + "WCacZ1ARkp5AR60IIbF6G24FRLh2lblPV5X4FEXwrdCyFVq2QsvGQkuLkzqokVn2s8h6Eb1s8LB1Hjc5", + "U5OpOMFwa/+OP2yQw3UOf2JETWxAwwqe0r5+NedF/RFY0EKwPuRINsZZSAUxOQI+BulB2Lvp7+5E2813", + "X0cLrve04WTtskTvZJTOzAdhLo55RHPBLda+ptx1dkaj+8z+0QuGCyNg+bGLsEjGPeArIQqjc/f0VKyB", + "bYNgAx+nAjRhMO5gKImijTThrUqHaZxi4UcfqhHLdsmgg1tGTzTG302mRhtpaLEvK9FTsxKet2doDPxt", + "auDWWYxmGftAkyhAA1Hde/6OGSQSo7y6QhpBmlovjWxv/bu89bcX6u/rQm1dpQPuz5NgSxhmFQh5NM4j", + "09TiwRQQ6eb12Y5vIDAPjMYjNAXYfzjVvu+6UUzrpLMLHnQUGm4S1+M+N2C17bpSLOtTm6g/+EGk/TTm", + "waeo6HBB/n548po8efTddzuP3kJykfbZRVpCchHXcgeeO0B27Jd6MjeL4iGhRTmnO499YhzG8Qj2KOWC", + "VdoQ+zDaMIuf5KLte48T2asskyIfPEo5l4JhNZHE9W8futsp/bXUcPOkQnuP4BlG16eTmZLXjaVmZhkk", + "REA7Iav1cSrZd6/gM7Fg/qJdnUkdXiaZFBd8VrkbDeQtDEKQqiExdq+5c448Ur+stIEBh8z885yZOVNQ", + "s/2ZG8HJFfbkeRaiyaLShlA77GQqangXjApMkztSPGNfaeLKf+/TnFl5tv4OVnMuzZzkfn12CiqyuWXA", + "fBGjNjitk7htOYvTGdnv79MhHOSh36DenRK0OMzBB/L9o28eZ9kO3X303c4fv/+O7vzbo0dPdh7R7795", + "fMGy/PF3eTI5fK8sE/yoLCdT8RqOzlMIbAYmnHP70sKKwphGsqBlaSkRbC/ayMUZVqmC31ZFYB361+z0", + "45GmIj+X171BjfjYvYvQ9L0KT+2b7wOhLl9F4XvvxyMp2JBIymikNW/W4K17NbH692/Tu7JPS3rOi+QN", + "sFeWJAvPIXw5vM6ZRrWOXXMN4fF4tomWls6WJJfiK+MiKoDygmQbBNmIytpcySKFlHRpT6EmmSwKlhlN", + "ZGVCSotil0xUrruG+8LH03ylQ/8GN4iVwOYSTJxg2XEbfOaGPnOv1ZEo+/iAHDkg6sPrPgkP3m8kkoNx", + "LyA1FsyTfDtphkJr0J3Yl9rzpeXKFtC+E09PnvtgcT8mvxXifjQzxtF2NDKU3lBHd5JdPMxa2k8bQ5r0", + "X8fwOqlMsVIq80ajBoh/QaajpZWMFllVUMNO6TXImVBbLe790SajpChXlp+D3QD54NZqcD9Wg7I8ZhdM", + "WXkjTaPKP0YOLXwiPaGaUKLnUpn6HUgdFBCU7lKfLqqigL9xTgz9MEQwlqNPqEVKeRpNhwdRgbMPXgO5", + "63nqxeVK+4vFZ+MV8tLVObkfsaQJzgYySufDYQJL87M7k17aww4VZTb7bh36+oScPp3dbrYrwxcKPzc5", + "PM3tlVIJn/DXp3K7LIzuwWjW/WuYsL2867d83CWj1FzPaO7qDR4peV6wRXwxDLt43wh2XbLMQJu0xhA9", + "0Q5MXTJFMtQZpMIkUftvlz3oDEyYZJhXwGS0tCJXnKtYMuXSIY0EI79Pp8TM5AdsMpuMyYIWVnmH2wwH", + "1Eth6PWYcAHe3vD7gmkImb5QdMHFbGwhy1nGSgiY8G8pWRkuZg8nKTPaM1pQkbEfuTZSLbHKSpq9neOb", + "ZI6v+upKXUUV39szUNgqPRarm32EcSlmEWOEiG+rBBVpundYHR4hq/MiGRuBC8VLC445DLU2Iwrfej8e", + "QTD6qvsQo9UdoBfYLcNLEXcGd4uru0V46MZtZKeOv1fYQ//Eni6G/oXQW44smLKKs28Say9X6Fnou8px", + "TYKUF2f4trvaEd8QsN2WjkfXsibOTOv0FjddpbEqYi4Z3spzemkHXJJ3XOQW/SHYBsshjqN2eTVwWEYx", + "EZdelhuERTVbn+2VpX6tatEkzTqiwpIahRIwRHDdacJrF+y6J2pmIC2LzCwOBQoqPHSHRHZzNZcFi+UW", + "qcg/KlcR4fAgQm03xP39eKQrCxna4TZbPlVm2bNaMLjbFWRSGGplqahUgDfE+5mTaCCKuZRznYL6Sqp3", + "FwXyqI2g/tl/mAbcQ+HHr7cAoa7JvgtV65AGxEbQjpHSVpzPA67BnHtk7whhksxnD28QeEpy90EiPkcq", + "xQrAebKoZ/3YkonflTBeOOdch/oQBRfvwhua0ExJrUnOL4DETOi9QB74uqD2BvJIrTSD1pIPfd9Jd3Ne", + "8tyHT4crnzAx474gFq2M3PFVAYgUPv6a5dwn+vt67QUXbDwVZcGotmrRO0tnCi7id4yVSHiWOrPm8n23", + "S7c2e4i4IIlVTIVmpip183W6QIws+GwO1kQuYILMfIQuKGWDdoYdj4je0icjIrkWrpyrLNWmcLd2ScUT", + "dK8z/2jAyThmVPcZlBQ869LyGrXFQX+mSybyPgw153e+4hP4Ah1mGVX5WYz7IeMcuw8j9ESjOeljk4HQ", + "DnNbhWbFYtcpJ2vXd7MB3LoGEMgb3cM1UVTbMswtw2wxzH9W1GoiG7hyX1ULpnjWwyv9eB5JLcKzm/nS", + "SmjnjJQSE1njYAxH6i0uGYAccARSOn6N+/Pahts8ADe5OPrllrX3SH0SY0XrRtPW3KE7Y/vYJ52NbrzD", + "pn36uWtydYCdyrtYHfQZ5sI5O7eLPEItBU0CVLHAMCJHUZCIraDtm6UD2/Fcw7Ecpr3Wg/K20z5fl0xA", + "vnKtysWDxDrauAYEctqM4pmBbvauOpT/IPR0MpoVFwlFCp3+qf46x2xWFVRZijckvAcjX80ZKM21jqDn", + "sipye0Cw6tRFZIYdGsMHMR7NWuld43zKivumN6wZt+IBvyD0knJwoz/s197XeK/2hIu4pIVPwqtrEPRN", + "NSwmqSdMOu3UesFmtHD1b1Wtd9E4SE6qGRWuzlfa40Wv8c7cXIc8tZ8y5G3pE4wPv9KkAFAPDzBIBs4M", + "bA29JmWlSqmZnpDTOVuSBV2CjWAqJEQ+oCVFj8l5ZcgV+0q5fvpcGKaYNr7Ar9QMU1+6AwcutVeXJtgk", + "9wGP2pv2CN0lv0TJFDwU7kXX84HljpsZ2Ti/7cuDNCZoXSSdNay4UFDJT3jaLHHWKjqhlq9b0Vsqcl5p", + "LpjWbtu2TGLLJH5PTOL9mtN014HPn91p2tL574LO45V0q+O4J0QbqZwh2wunQeg0MlS4tRqr+6INigWV", + "1iKuC4ZNaff55vpFWEQot54O3n1lj1HBf7VQ02vcET2XV8LnPkvFZxyK5vqV5zKrFmydQtLrp2k+b97F", + "LVv61t1ROw4+59o9IVu2c5qcdyzym3n8/vsoVSFqW23nXpN+vpA6K9skoDtLAvoMvKxfSIWLz8AzPKQc", + "xArvcX0RvF0rN8RBk3qdENF4OZYocKvDkwc8H4MF+aG3Q1i4wjW/Xv6I4gM3iJFeJ3PUrhArHdTysN2a", + "CIcdkcCHvN8lLD7afjNIDL2+UyisKLoJBO1Q3Shk225WjapBhDeE3jpklhQc74uiPgFC+qj082mSTV+B", + "mr432yTERVkZgBuYKzZHaRHQV5o4XrqCjm5MGR/SfTkeXe/M5E43CKQmxhuS16ewCkfRN6DRjw/9HR+L", + "WOmGUrrLG+nua8MvVgkQXX6RBrB9JCvhdK+Y81vJNTXLVGBCbNtS0EXLME5xcy5x54YTB3CvzWSNreSu", + "jQCfovK8VTp/Z0rnrRW2lYdquNo26auNEali/vBtFNLr2ZDz1b524fArQu9DxHxfvPp5Y+TDnky0Nt5h", + "tWFsrgnVWmYce2BxM/dRZmxRmmWKj9hvCinfsZxUJcmXgi54Rot2VeMPErP1eRdhD+3+0ynGnhB4vn7T", + "PjzqP38zUeug9xlhon3a/Hz3CSdHdFlImrdFD8GuiFSIGBeiCSUF7L87qTQfmiN04049Z+jk8miSzaVm", + "4L0JztqPkQa74XY97+milH4vlH3XwT8d6h0F5PoOS3G2o9M6Q+BOMrNxJaCb1fFrtkNyQER0XYPyyhkk", + "3Z/oNc9CulijGYz/eT8cnM3X8TM38964ym4WWrjAPbmmrkWq2bMbHoSa6x7VpNw6Dj45EToFyAsCTVvg", + "jGStxflATCQPdl0WPOOGuJwDK4TUlQbalz5S7IQcXviM0amAK3mMNSAhNjSxUpIW/j/G3eype+PouL7K", + "Fx5JTYZ1zgppRTkjJ/G0sYR1E02tI6mtAaotrnXEKJdBiY8hyjbKSWyUSO/s3fv4DIZQgI1W1U75TAQc", + "InztQxH62Wad0xgdwvZlmjyEm1+fEXv4DEp/DGd12wIh91UgpLkHffd56q0QenQFLRMd+fsQ/aj1Y+MW", + "X3/l9V7VyddaMoV0HUIb17mDTceXeY/wWuuqoMeuh/azO2bbs/SBzlIjZNUys58jm80qym5WkOm1wNZK", + "T/sOcgkuaBuFA+mrb5z7CNnctfstlmPQObCmj+vYzjXJmYZoQlCxpsKf7jrcNbIFtOuXbU2tW1Pr1tR6", + "h7ExNzSyrmBRJ8y4EjIvkwVhsW6PfweC6O3hwnqrk6k4NPb2Z2rBBdNkLq8auXdYJpT4VFpdJ+zCviiW", + "c6OjvYi7ZVYai/7Y1eNcO+6LM6vHufJG7Gk9jC+dUip2yWUVbScUfAHNAQIkWE4uuNIm0ggVW1Au7Mu+", + "kg4P0OYT4hOTY5Zll7CQ2pBMLhZStNEUAyxFsXyKQeIbQesRl2MRWIR9Ql7JCJGN11KonDSlnTYCMYrK", + "Q7lK0ElHc3dJJvUaJnGK28R5N5jNk8cdXtMD9drL1r/QvmAbp5B2TmkqRN6nqN7cGROGOHGz92nPdTps", + "l1uEg/9+fJPQnhZMoVDaGpDq6I7VEG0c59OCx5W6XAONj9FYDctGIT8tOE7p9RoYLI2vmn+FmbVLEK1a", + "2R33d6g2DXZL9xlwUEZK148YCox7PQIrODouAFaXA+Rsut15ZUyu5jybhzrW1JArBpzHSN/vCk3wPsGZ", + "XTK1REOfmbOpoM1OLo7FQZUyTR5gUjah+SVyXgvgQyIVYSKPHivFqNLu8bqiJFgxm+UbH7yA5z0/gr1e", + "z2N833DAk3iU25YY2Xi62w4X0LGqiMiQ79fx4RXftnT8DWl+KtpE32HhilnF2gqWodDdMN5w3Pzwp8c9", + "LCFM4M+Av7HDWiZxBeQET3GlIKP3I8OKx/HbdT47V+u4vd6bbW2D0m6wvfH3977FN0RtgwUMQ+9GyAxX", + "SQe0IJ/Ed35AEojc0j/r4/YgwgSkdAOz4rvlloJLfU81WhT+FjDW4oJ3f5Wh2GOYuqRFwxAxOjp99GOi", + "TyLXZKZo5itO+u5hvqhIzqzuappSV6it2QEntLQmXExFTUytAkcXVTGGgvdUA9WFBmZNNWhOL0GkKvhs", + "DhljofhRU19oWrdGR48OYr//4cnrf/tu99FGnt5WgNAddLzcysdb+fiO5eMu8tfdP50vuoZVlGHX6H9d", + "JloZuYcibIPrrOooYxlXZeSCGowEI1zrijXAoBeGuVJpil4YvKjJnGpSUq3R8JoymcLsp/R6HxpqDN/F", + "+pPupjkFwSnvcRMeu5CyLJY+palRY8lhmtBa63/wCxaunti/fiFfk1+MnTdnh/kvD4kUhEa5BnlnWvDq", + "12170JxEBRGSFFLMmKq7P9orBKzZ+dNO+YHWyGCmmArg+1xow2g+Ic99GJGh19AjyjuiF3RJtOFFYedS", + "bCEvWT4GSH45Z5ZtS/WLsyvpqbio7PbqqiylAnO53aR6Q1v31G66nW9LZvQkgnWw37ESwiKwC7hrImZf", + "XVBR0YIodsnZ1Q3vifEor9ieJcUWpE9Wg4rUi+pjowKWJnlltc6fuZlDke+aI8miwruPm69cexiX13Re", + "sHhFEZOv+7JEa0PYhiwuKrzn2MXaI3yCHpBU4UFLe0Uhr1K5FWkPR3znPxf5kZJ4rl7epOpCl9OtGr3Z", + "SNou4YxmpqLFWaiT3S7kKIySBYqeMeA7ThaCVhFMWHWNqUse5Co0VtoZgP6jhntBxG3z3tEmN8AaHCZv", + "hcjoHishTMDORvJMrAsAkuyBrlGUwNvb9TbJ9lW97u5qvd++uZJ3+oCbqz5HL+EYbdKTr/Vlk5qyOVUz", + "dta44karpBE8xm0G10Ms7eUOIJZYJlmH7OjdNqI7gssAJDNh2Ve+lq88h/dqsQDvJhfwZKkR44LpteWh", + "4T7xjdkoNEP7QSri+OC40dkqHBYcxcE09sPFtd459R+d0uu0kMHEhVRZa00XtNCJRcGbN1nLzw1A66qM", + "oXkEsNrYEllXZ7VLl5VpTzuZCgcQ0A+PS8qWTIG7fAz7GpDoUEGhTw7o+TrEdU2t/okV9WGmQmbR6sDI", + "idJPSXnecc2kevm1KT2mtxSV789Z9k5W5sReRFJgANUpuzZwY59U5wtujqiiqdASt7LWEBPXRMSwa9OV", + "dOtR+2JPif0QTcV1qECObmCWR0KtP8Qg13nv7HllTKp9o2vV4YpOB+fP4yiWY5Viq+cc7MO9rU2HwQ5R", + "kxxcVzieLw4WCSR3D/ut0B1A/tAoN0wt9OuLExQE9rKMlYYmW1ANWggXBEJiQv1kL7/baeyPXuKgM8Xw", + "dNsB73hZ79cfwTeHabGj57RV/MwKGZGMwRbnzOovo/FoLrXp6Ri0D51vsDeRMv2RZ/5J1F8Ee+ZYhvag", + "ZqrnNHvHRA6VKbCHDJTC3avM/DFJez0rVaTNqW+OXySH8U2QkO5Ao5opKkwYf7Vp1c6XsqzuJ4SYtuDa", + "fKNtRY11/zq8CT9iOXlQX8mX2qkgD2PfelrY0Uzkwdf+NkpzaisvKb3EauIFzz5cjybf7iiD9btIMTsu", + "1KnyTZko8A4LWBzljBGJGnsBXzhBSc2YaUQwJTau7uvc2bO7aeOcRc2hJ1PhWc2V3CmYsXQfv4BqCi20", + "jEQStESLSyY4E+1aU29OWpFQjdiEx83MgL2dv7397XE68h9NrS3mAPEU+w3baYuuUe7xzUvd10Tj5yA8", + "QJnD/rupIZsmhNHOECSvwInlJ5uQ2HcMImBaZKxP8mAVYwBOjv2oKZOV/eucaSuNYRdnvxweFUtcuR7B", + "Lpnqxl55rCW50SZQ33pHwzpiLZVfnAX6HY1HsIj0JQKz4WQtiJ1K5ASmVUR4Arx0GbC8H4BGVho7qLzg", + "/J///X/WYU9Rw/PgzqyMHEU43xD4fcvnhFl5dJwRM4Sre80zgH/icS7JjCL9QPt8yw2g0ivcqI08sVZX", + "AJS28Mo5ZpVme1422fQQDFvl0YoJU+cjRO+BbAgNFVzX8UuuuetaGyrJNvR0ZUePZC0XnP7m0Ottmhlv", + "4/Y6FGx67k/XlbOfVprlrsuG+2bO85yJ8ZBpQWbEzh3FFV1qOyB+HkHkzHwLWbdEv3vU1+N3MX140UQH", + "sg+dcCyGhKFAY5i7gGOD4XOxqIQv9DTBIO8OyQJGQnRmOJlGeoHaqsqYHmF/lGA+NjKeaSoaU9Xi44Kp", + "bG6Ftpx5F6gU3cNtVeGCTchrMOL6fFY725uTMAbWhm9qCvezP6fNOVbtkWc6Y+yv11L54VoAvmyvk7by", + "AQ/O5TU5ZxdSMXLOgMG5lZd0iTumXON/6GGJhYI7Q1kh2qU7LmWl/JVwQPX8XFJVV32dTIUXj3L/cBJ8", + "LIuv/Xtfl9V5wbMeJeaO2MymF9rq853gqY5LrUt4uaP1HPnp7hNpR9GaNkKeZxIRD6lZo8dU4lpFDnnr", + "S/WowVNvC3nNoRMQCynYreE97fCZ28LcPrQx5ADyLUQY3/aip9x98MVA6p2TYaQgIQHch7K4XB9nWW1f", + "Fb1l8e+GDTcW8cz5RgfJ6rUUSS/dVdmSF4m0V5bnyxMvRU7FqfTSgBc9KfYobw0whj5h7scz9+NZpC01", + "42K9LlCn1Xxi+MHi+w2k2J96l+GNmJ/YUoJtNc7aaS7Lv4Kb7Xc59SHusX8yfJM3Zffp1W/MYvzhdT0s", + "fDRBiiPeRKk7Zpjy91rso2HnJreOcoMQ4Il+mAaIcPpGY6uIBv53Y5DBLHUDKOG7hrnmt0aBBTRbZUsw", + "4xz4dN+no739l8/H5FBkk1G6b5GugCT+wpbarnax3Klrk4/eWtJxmcdRfZmEHj2KUNOBJeuw/8CXAwUg", + "uPAXuAmyjGn95vjF6OnICoRPv/7ardyKgSPXXaOpEwfzD/ojaxtH04bw/v37REW/VI2QlTVvIleab/UI", + "iafLj11qY1BJyP26+Mu6mPr9qBbM0Hd7q7EdIS4JrdnD4QGRCvq8GAkMLi56VNv0A7+cClQj2+O4ThDt", + "XI7w3ahJy7e+JNxhfl32acruiQtws4A5mgGHaqj6BNpm68TjlYazrigT5vlFjcpJp1JTjEJYjHaIaX8s", + "FcSM6VbbQP88CmBLTLu+ulbdpMxvwtvNrqUWvjfloW7WqThhjAQdU2Y6Vi9pyb/2X37tvtRfI976qm0l", + "rYq3pq5ek2WXzu7MZtmwFltWjJVnqMhYAaz4t6SdYVzP6Cwy0H6GZu+cOxbjGoPNwRvL8ObFkwHBZW+O", + "X2C7F7YkOcvA0SsJzl9XKxZWszaVAmsPWBOu2Lnmhk1cYHpJFYVGeZYxh9AK5M/OQ2mfeNdksnkT+hVD", + "OdrDgxXNPPArtLb40rdJ9QTzb50u0+CAY/snVQb+KRXRfMELqsYhIjSK41cskyLz9ap0sJKZOWIDcgYE", + "LVzask6vL2VUvntLVYJa78FW/T6WOYYXm8Iveno5nc4VY96vdnjymvgZwLkGKQ+WqFRGdVyg6ZRdb2IP", + "Hx7wktA9vPWzrrkAFmSLTyCE+sRhEnpWhyY0SkpFYtndKk7p3b8bTf+9FbJKrpje60klfV7KbI7Jm1wQ", + "bU9Nrgk1URhv2taM42JVAH9YxRJ75QHpPdklCy4qe5UaSR5/Q+ayUtpFA3XGzFwh0Al5tvRX6BgZHoRg", + "W14UxkDS9l/EYb9cmO++GaWqyKB1Os5NShf3CHRylMgk6+unNDphhsgLK5/tILgl5cqlzy5lBRiixlCL", + "UshfcpXrHDOumddFVQBtaiOVu3U83cbKMT2HULe5L4HnOrsZVWWmcl2IF9SOfyhyfsnzihYWunoqoRm0", + "ty6lDkU0oQobwo+h/YvJVOwVG3/pEZoMAWj4yE6XJUt24C64NiGwwL5k/2iajjV5wCazydjeCflDpJUu", + "XVnEQyRSo3JSt3p+qziS6tGb70AgTgyc4qyNOxrLQcBJcpfz0/pqbkokoIlPpuIFo0qQhVQsopagyXs7", + "g0WrH8hfk/b8Rx6GlvTnNkHXIiCyyB2nju6UdMb+3b21U/E/+eF3LE0ibq1gkpSVoliiAGqDTaPEZNfp", + "owqXEGRktfEMglGUl4XMnHEVaMZ5rJokBAIeNMiz0kSPcBTiBtKSkZO1ENgdLFHYJlSqmA9r9YDo2hqb", + "KJFTK/YrMIQs2onyTozVrClFWiUqoEBZQbQCVdyH+dxUHAQNaimr//zv/zMnBX/HvF7aKLzjPYhuQZa5", + "dU6odN4uSzZjohjFlu6zCgp8egsZ/9WyGnjRDQYfPL0lnfa2JL25zLcmomfFbb8+8gZKSvPNEkXSwYrp", + "iLA3h6Hqj92DIJLHDAYjFDc3mB4znawQ1tRIO+Thq+clUkz7Va595ABvjl8M0lvyu9Bbmlf5R1ZcYIEn", + "LFOsR+5zIaEaXvH73TGwdMQT7DQruOFQ2sft2uQfOhKoYeQdiEDmlsksfFPgyY2L0zfk0Y7RYlWV+ieb", + "VElPmAw/DYWJKSwn3Vv8+SvLmikvgqcsGLaCQW1yk/L6XQuXs2N9YNvtKi1mKJVEWsvdUsn96Q+oMnjj", + "T8oCmuDBi42uhySv7rki7M9WIQBP6y8gS/wCB1/Iq8kaye4YrVF9LNktqLfNQ3s3k9ZUO4ypykNhmDCD", + "h3IyEXzUOy5k2PaUzMPs2z4emh5undHaDjzIgrxaWjxxslIf2pMB/T6Y3wfKD1hSjx0bquZ3FhvvdnvL", + "mm0+gZTXWsB90W6pDC0cBa/JgAo4LeGjEAoPYrBOlbOIEuD79uvwACrKxN0o2nnzVkIOacIOC+OpwLHO", + "wZNtNLmoRIZMhJslCAkXjFq9Xteei1B5ZNwQFIJvwrshGiC4DP01pn2HmzPETdvC/1/wP+7pmXu605hn", + "FKc+tH5vk2BtmElg9PnpD6SgYlbRGSOGzvwpw4862wjZfXX+EGLrvKDinRW7MBSzY+AvQbBTLD/DUbV9", + "91zJK90IbPQOTI/Dp/eARIeLqD9L+KGNNsdq1yTkBCW6UZu+qT5DNmNI+5gK1JvdibD6beYjT+9t3biY", + "M8uN6rUfhxUOyj7bh8KWr6Rhr11hSUyAZcf28ht6Hbpv/swEUzw7cAUp7RAJxW3FjMHd3VEc6rKXvqLD", + "nBqrIMBo9mwDqfleB11eBGVDkgLzoX2yZ+yEVoPUdQcO4AhuMSAv4yC3E4Q6TYXaNIo1uTdG/iv8rIvw", + "BydMcVo8JK9Cse9Gv+W8UUG02/M1XQ3MVQJr5KB3qqjabTnzW9dI8Rp0pb7g4p0X4lwlpRjUgN5K8fWI", + "TZd3682Vi3SYtvLgdI88BGjRWiFppGgHPSB1NW5kjVinH7EaAtCPoBxDb2HrxvsQ+paWkM4rwU1KHMAn", + "QXhzQzX3hAvz5HHSqaCXi3NZrAELXxogNGFSqK/yjENHwK/a3J7qvLG2+ffDk9ffPH70x/7UOvt0x4Pd", + "yK1raKlRUl08fuOdm+TVHbSq/jYS654kEuue9CTWAXCh+sFeWfYmIB82mhTHZg6sQ2qYuqCutgChYhnV", + "9ZK1aRktMXXNNzuW0781AV3JSLKggpdQb6FZGNubKcdkLq/YJfPFMAybocw0FZA4oFixJFKQV7IutqzJ", + "3tEheIAZXBxYiQ6t/f52wXpIKZH2M+4KmDOQVW4Ie8nUglq2VFjWByPdzzoOGPp3VqzjU2x2gJ6KA0Uv", + "zMlSZD9K+a43WxQKUE30UmRkLuU739DJwmj/9t6EuvhIlHjtQ1x8WaXaziHYtU8ubqRY95UmsYNb4YeL", + "2VqIOb73kWHmq2zOdXBpsi/E/dre+oj58CCpvaGmu0FfDKreMQOFHV64b9NiwKJ+kRS+LNsc2spBuX5t", + "aFGw3MeWxvJyR/Lbtu+4u/YdwRI2DJFYr8J+kojJa1jO4AqWQtSJ60MlePz4K41VfbkmLRGg29DxrC4F", + "+vb30LaV57Vk2dcFyx/lsMdjr1qkLoQ+tpuWUtsSWaPb0Ypysy4rYm252e1F+nu9SLes/c5Y+4fhrumm", + "RvfDabxrYK8sDxyNrNEDQ4jlXlmSAxfD1smD2bRba0MZ7asY7QUaF4HKG7opCD1Aj3En18QVyfPeLUxm", + "PkDOOxzGSqOdcFbIc2CW6EAITQssFMvyQzTJdfS6ByDfezs2/8iV1gX130XUdrbCYU1N1p6XYI1aeTSi", + "lZ7iCbhhr4EWnYUTNFdS8F9Z3ptUdxjFaxlJLrjAyI5QhDp0/ETfVm+vhRsUV28BbeF1UUJ9BavsQ391", + "67A8F12Sdgs05/jBrS8Pv9wIMzVFbIQdb9q+M4u4r2FRX6xfad8K09+wrshFHUuNeVNMmFMZGKTpy1tp", + "jQ2pBVFiLgRd9E90h3EWm2yuK71wo631Vr2BG8uuMR6rJzWyi0E/vv+QHB6sxuAt8HAL2mZemgukPmnQ", + "sBfuILUJWus1u0K1iLBuW/fg8NVPO+B05dcP74ON9B/xm3GVG3RpGEiXQ+Cpjcw34HYvuGAHXEPFu+eB", + "UF/WnbNaN6HruX/uxE1odJK779FcHVGt3uwwnEJ3/5rmIXi/e8OiMf0rTQ4PHk7SFqd6TX3zNAD/GBFr", + "rWu7BfM4RtTbYdt4w+37lHZt5W59Gpt0g81xZ/pU8dmMqVQjcDzABl/AJuksqwzD1hee9+Yp73NJwXLj", + "mMDZBeUFi3+ohI8WPy9Y9Lu8ZCqv7C8YvREXZbiUvKc2Ta84tu7+qJlT9wrZbwYPayNVRFKoWR4eaJ8X", + "4e8PqZB+7+DGrcn0pnfu+NOT34oka9cDUdJkkDF7WDFtcHB2Qtbj+JYwWOAJ0N2VM9/PfioiQh/Uy36j", + "Wy2RzFU0+OdGOPoMUTMAJQNEh0Y3oaTRpD5Wda+e/vCQTt9gH0uABQ3jFsGuGjO430vFzCB9vFam/djD", + "Ai4GcHi0Uvt+HGAb7xWsnVE+SG3o4fClaRL8sBsXEOkI7vMHWAsDE6EaZiGuXcFBO1xCmjb1rXQjybV1", + "ufW09qpvtnPmL7e8xdC7JXU9bP07cFRQcSjKqiV5JyBgixJQeCEVkQuOLahqVEzuogtiu9lhw3Ac2hg2", + "Q3698Qy6mtuFuWoS+zRnycr4p1Horq88keHLmBe8pm/6AbsI3dnlhWEiSgasO/K4D12TJJJH4GLW8HOU", + "w/RTMh0dPXo5HZEHCynMvFg+HNufnsBP/6yoMkz5Hx/91f5IhahoUSwftptPvWwo+t1I4WfN5d5bPo5v", + "WIMRRysCt7IoFQ43MApR8ZB8slEcW8fInTlGyjnVrCf7wxIGgRcgJEwhb1aQj1QU8kpjBJZrClNQ8ZUm", + "yrKqjKpcEwkRX3zBCNWk3Tnbu8b0ZCr23CT6iptsTmSWVco3TEPJhYkcjFWtZqFjwoTGPFIXaWzPfqv3", + "aNMtJ6QhXGRFlUP8mJoxV3Mhap0DwNjlIncdJKxYfn5kPwT65OIQP4p24ihgM+p9E+S4UsljKAe1aZ/D", + "o9aHrW61rZpomEA1wp5g7AwX2c3Z8g0SSyV3FE3ke6zn1xFDOeoZxWU1GcyjvFGPuJPm5622XRjfbOZM", + "nNUtgxNZTmGQRoqwu3YOTV18uu6w4QkRxd1gA9TNCEiEoC5xs+6K2yEJmJ/Ww/ik81KxSy4r3ToPGJkK", + "9RRycsGV9vZL5CwLygUYUWiBDeoDtHk8tz14T/H4bTRxbQe1S3dgTMgrGeGk8VoKK5O6uXCc6mNHXEho", + "6LFYuGa40ZbF1HbSfNTnlQ33bUdwCUyxK711y9kVYEAvK9fkGYX4BvvxxVzIA9/G6x3DzKdLpjSX4mG6", + "nQgMFTcD3Idw14TOAr+HtOxOZ6500TJosZ7m+6EsGLwTrMfxsATuB5+IC3qB1yCFlYPQ6kOzTKrc5ZjH", + "p8aLfSEsgioGgcBuV5gvOe667vAFm5BkNcZAkA2ct1bQqM5/12nUXprfVBGpNYC+XAHYTbiEYwEL84Bz", + "JwxDLYPGhkPjtcVGXoZ4gFP8NgETPOhRAjAUe1xHjeEPXuU19B0j7OIC6wL94HvZouQQ7xxuKla1Yblv", + "UYvF+UN5kcbpauQAdhUxXE1jn94OO2097cL3fW3J3+Npa6C+fvt3d8DW1RbAdNk4MXFCfOVTxrF9xZzB", + "RSAh+Zn8SCFbUzPcKnlZv/IR68n+hS3TCwTIN1rheo2lE7N1V1zMy4N8sWA5x0qe98XbYiOHFWP8lJOe", + "RPLAkeL8EI/Ufrkg5Y3Za5fCbZeLrrNiVkXr8nwdlUWlpUNl6TqqeNXYgwpQn7lfzt6xJVagbtm3hJBY", + "dWWTWO3oo0S0drpGxYIKOqtNtC4ZiuwDBJbfLWSOiUnnS8v71GRFYHMDgnGreOwGC3EfpHlap6tA64xO", + "xRufAmboNUihPA52bBuswmzjzzqp6s6L3YT80hUIdnsxXo3p2Nrmeg/GjGz9DXPSsHU0wSFzqokUHzG1", + "Zt+1U2xAmY583Ga+3afN9EvJynqXEkn2fHlvWvglpSSUqXiOookTS9rX0SS6i0JPKy8B49G+qIqu8zMc", + "Ny7ajlDdbmMOhcRyaug51WyYYOTwYYWxrTH8Xo3hii+oWvYUJEMlDN5oVSRr01nD9okf4JjpBP7aJNhT", + "halhNewSNXSlCw1sf2m8/gth16XFmQwa6iB7dsyvsSZL+pCeNMDv2rU//3SztNS6iSLK1Jv2CIlQfRfh", + "ZiSh7kVGoGwp+DShSJBs7PztuFlEowAdaYC3cY7d2xWqyh4U6uqv8IfPo1IdWBvc1YXqCjQU38cskXYH", + "YFgUlB1YVbNu1aY9r8f4ySoDXffISwo0G0+2CkrUCu0uOau2W5r9Ce0qoQ44OrvCsO7Bv3Z+x3ujp5hK", + "1N+92ec3ws3K/VqdUhRemIoTI/0O0bL0hbsy0rg3GpyKEXnxlGBlpTHRVOTn8npMOhkk41HO7dQLLqhB", + "09miDg7tvD4s5KO9wPHIAdDLBfFx4jtYwJrCg62vakV2+Qo1aNiB9+ORFGx4OcPOqGu+Si9hWCOfXsy9", + "H0A/aMp47XoBHBq22FLUnVJUAsH3QmPJeT5VqjuiM7vBLD921ZVTYcvulVCBuZuq4WWkRDajfeQbMjuN", + "HQp2bxjY2GAMnXAAOuuJoLJPCBc5u24IRI9SNZzsuyf8156RFk7JFKHiGC6tZCqspx5/dzc1g5GGFvuy", + "Ej21mOF5e4bGwN+mBm57cepZHGqitXmkr6KNPmdOSMZ3HcPWJuN/fla7z8Py9WnaTLa2hq2t4UuyNWwV", + "WdiNVTfFc7CW9Auq+DyUKNYukVGZzs5gNlSJ7A8r+0Ljn8qUlYkToZoWoP7spbS7eU3XQzALtcpst0Sd", + "xKBvXhwekAdvBL9kStOiWJI3yOlesGueyZmi5Rwrl5ATqQycpsNgQ374sdPdeL5yj5Ne7Y3w6LzyTUS6", + "22I1aODTXAHba5Uz9SwBHzwg50vfxzKKN3N8ydNT2liziq4+I5l5Kyzfu7B81wWstjLzVmbeysxbmXkr", + "M3+hMnPsA7yZ/NJ0ccbCDHb+/UFBMBz+cSpXCjNvEht2W2w7Q3MWN6mF3hK/MiUt+qEXpUO5Hk/FeWWI", + "FOEn+AAyKrDEmR1fiiZFNi/NRlRcj1P4H64RAjWY+OHXkifAd6m52M0UnK1C1mPA51rLjIOIF3zJMXw9", + "4t1JAJRwTSj28bcgRV0iXHjJEoO9fWji2vDP4GEOmEgke8eUGiMtRbA+s/6IqYwJkxQb62ehiEB3d8rG", + "AAMTtepv0hJNPahnWDEATgB1wuWCC/xrN2Jl0QQtxETwrsLLMaNaCicUnJRM9ASfKXgvXAOh2AIQgJeU", + "tf0+kbbtKsv5A+5eP4PX19dU7K0S11zDMTUsoypftdNrV6LcINHOpIoAKMWK3uZJ+/VjcnjQmaiurhAd", + "l4KLd3FtokxJraMExZBO9cCnUfLLWiCuNCMZ1eyhr3LVDeOPqoaIGRcufp9WRu747CyIGiQ/W0bBrMiB", + "zZB9KmXBBRtPRVkwKyQt6DvLjxSwzXeMlRgtayWFrLn8Fl0T6ERAEquYCuidpZuv0wViZMFnc4N1FGCC", + "Vqjzh4mR/+R5wLhz1jxBnyX5weoeLBuxEH/84C6+zcmD23h76LaHzh26f1ZUGG42UM1fVQumeNZz3vx4", + "Hkko/TUI5aUXnqXmVvzsCM8rTxoMOPiQheWtOmI9h+pNF/TmT2TBqNC+0QDDBGHyyhmyrAh4oRibECts", + "x/m9umQgd08FpCpHo1CxdBiDcl8hWMPHN0EzbqF5DpL1LqmE4YWr9+uAmgquCbue00q7GL/mSf80N7y1", + "e4O2LSE7+0eQYAK9uiwaISn/TkTOhLy79tqp7xuv/G4+n8NScqoWwtMFmw6Wgi54dmQx8TM38325WHAT", + "ovpaWMSXEW+ou4AwCbni7qsuYbm7dG/h7bF3QV21oUmTgi+408UQHGowhR1imxb+Tg+WGSc24xNXReJ+", + "IUT8tGG010svkAhSDGRVGF4WfJNCTE0IfXbeo2Rthnp8UNfLsliG9NZQpsP3iYJ7K6YGOM+h4M9U7JDd", + "ye5TlzjOsQSCVeHxybetJ9/u/lfPJuq57KuPOoOEu5fq5PvtoR8lx44rfd167avLeJuoNSCiKjK6uHFu", + "oY09z3kjjWkvz9MBgHt57qvrGraAdWKRlO6JlWV8w9I8P7OfJG1BMMJfkv64MdzN+1Tl61xOx/699qpl", + "OYqmiAYciAmsE7MCFTD2gPXje70I2CTGH2ByYVL96x20wmO2kJc98Z74DKRau91QV6R3w+0rfZvYRIaC", + "YW9ED2v21sMwfOE9u+tXPmhz3XrW7G8fbvScX5i11F0De2LfH4IMHHgIKk6MYiab9+DCPe1FBrs2TORo", + "RU6WVVtNDRqHvxn61qAggDYEC2+ExXZeFcw+SYjs4bkGWbpVbCc4yofwwyqMdWaHWc+7ZZleQ50lgACX", + "imXU1CWk2g1z6qQEX6oQlQmvWGMhhXYGAxaf93WPfvC5HvZD6YSSgAeWmGPsbtolfIJzhECbUIRssibq", + "2zfbWZ8J8sy9Cf48Bihc+81L9yZ2neLZgE9O8MXbhnEngFgXep0CYvAXHjvv11CUf++GhOVqwOEgMVkk", + "imDWfqN0C1tXEwWLmLQd43dbwiS4rVZC4mrc3Sccd184ATrC1G/4BbS2JipC0ahrA6UmdHV+9ujxk26S", + "4RdRcwB14SOokraRndi+v6qJtHGaNBZgm3xJCfTOfNRX+sBbl0ztBbUqlaM5uHMq3clb3zv+25NXB8//", + "cnry0zfHxz/88B/fff/nb3/Y++kOjZMOsN6iOTcB3P1rx3278w6kkCic4rtv2p7UeDl059fdne/f/uuD", + "f396Fv54+C9/GFoh4JjRHPzWLmoHAkPragH3j+S1jfg/WHiN24GJS9p2juaeeMe6nsI7FpDnm+Q7F/hU", + "vHp9+vwpOYm98Fjyur4cx8TZ+30LM6sfBiPO3tFhM0AwVG7aeXRfZNI2dXsZ6stsNupsoJsy8GOorcbF", + "bCUn92JrzMkTV2ift6Cv22kjZgaigSN6bbCpmNcOE93QRABl1fQQMc6FVUOJTIz5SYhvHentbm6AECNV", + "r5jI8Ndhbr/xaP18r4ubr/ID3i0fhUtvxKnu4JRHZ2Ol88PXzE0EXDUE5+HW1s4x/elxqrftVqPaalRb", + "jWoDjWpdnc9IzmvKeP7DD3+rrC3duVI2TcLdkCm/2LJtW61zq3V+2lrnVvP6/DSvHmWrcbWsEem6Ktdq", + "BaupWN2p+6MByg1cIa3vN3SLNL6+exdJa/gN3SU3/TqF2XVulD8rOsw7Z0l9Zl9OiPOL/kRUfAaRJfAx", + "OQmd62gIi3OJqt3E15oPyApbdzYilXFdwrWNvBcZGvATS9FNiZlrXbG9C8PUMdPMONn4MxeOvxQxDCup", + "80uWWslz/xCbIFhuBxSK3XZcBwX7q/K3gHseitO7nhKhY0HGuBOCgJnZL664yOXVCf+VkQcLLirDHt6x", + "2hhx6D5x00k+sesbpKAQvQvrgmj5phlhA+ForZTDrkvugi4Gn8zn4ZuVFzCCX0+ANzL35UbhAdN7fZny", + "fMEiLLi3b7dLa7HxmUqq9PpYFoW8ZGovYvku6nI3yTrRFaEk9FOEVhTUWH7BzJhQyzddjwyIvwi5kDTK", + "lvAtpiyBUIUH7MqR7pLMae5bjjhOxMxkKp65j3CK8ARCVWmRQSfRnFD9lLg3z4CJnwEXJ38iLw9fPXjZ", + "Xu6YvNz7fx/4D57BrPjFmLzkovnyw4cDbrPODXanykB9OPywbXsPVChx3Ust+xiV/Oyb12rv3fzF5ZLP", + "ufy+/PbR/HvOfxDPQIBdtJe5JYG7JgHBrs1x6KeTZlr2nTbngmsIL6s7vmNKxaVyiRPJPHl46nUeJ+e5", + "rQdz9JzP5kzVb3Z6y02m4sg/hKytIBnmLOOLUMpET8jPdsBCXjHlfyNc5DzDpoBuJr4opTJ2j9o1GWgD", + "3kd2Nki4rtQMjNlzKlrvPJ5Mxc9O0rFwK0Y0u2SKFkFguKQcSiTUbejoIlhIxlHDD6JZ4TKt621z9noA", + "XZsw92QqDgVkgmkraSnmp9Nz6m0wdpoAa8EuWTGOhs4Kqe2IRhJudHxDxk2Wwg4cupo60KTzgpgr6WeE", + "A4lXUUYLPyN3nQnjm5caphsLhpm8wxnBArkjknIdAK2qOoE0Ky7Mv8UZi4+//TbSA5IFeFTj/Nylth91", + "umqq+k43+kLsJZfSCrgDZSYLNn5wp4yn3eSoz1CycAWKYnG/IXA6+0lTVB6iF8deuE1U5LpRI9hSPmGN", + "+XehIn001WMrMG8F5q3AfN8ksBVPt+Lp7048XR8g5B20Lfm0JVWtl542FJRS4UKfoWD0EVwJAqsJnoWC", + "g45oWj++34pt9yi2uW7F8UOuW+VXHCljGTT000JlWBiDFcvJCtnv07jsSdxbFvea/bOihXZrc+n6W7Fw", + "KxZuxcKtWLgVC7diYU9jvrYkuFL828p7N5T3ttEk22iSbTTJF6MbbENS7jkkZatlbbWsrZa1jVbZ6n1b", + "vW8brbKNVvnko1U2D1DxxbgGxKW4V5s101xdtYuqAD6woGIZ3WG+CLkeY+00zQxwrKp0eU7n1B7G0Jje", + "8jAc2b5l6bVg1/bI5NxE7ZFce36uSW5hWkDiFA4lRUgvxBkqDUXL6+vUXYP25D6w2znFrC5Ci0Je2Vem", + "oyCMQxnkOSOQn5F7zsA1mY7OKyUMyeWVmI78azDQw22i+jZR/XeeqJ7A3jYpe5uU/btLyub6RF6YF3zB", + "mzrjBS105349vCDav/0nO2BjL6yO6EVKv1fskgnCO1yOxA0MxmROtbswsb9HcUWX2grCdo64lrqFFYvE", + "1zvgE3JhMW+EKyGfXsxq8eEgqiDGZ0Kq+no9p9k7JvIJOaori0WoI1xow2j+/2CjhgvOijxI81iYOBRa", + "vagwOT29gFaWZZug/iorwDNKeE4sqIxcUON6C9NCipnmead6LMr/jtyIzpigikty5V0NGLECkgjc8vaf", + "TiSZQHsWq4ItfL8Z38w5J1YHsgpcpO760azg1AdOrWHVQwU70anVRaIBUdMxX2mwV4Cxwglq0C3jgs8q", + "hRim5Iq6ZmpoYWA0mzsTQ+i6OnZ7ivKW09BNpXCDpOIzLmjhV9tc6mQqXlJRAa4DynQFlZkdxIDRBUOT", + "CTTNAyEOh5uOxmTaNdjYn63WNu1a+qYjJChtBUA4FU7HnIzWen/cuTkU3HCvGZMgmneMHC36O2pYGNxh", + "etQ9NhdcsFh5Drpv6CLkbIPBObaJGunXYGHzK4CtxV0NZpCUxmnVtp6j1NCYQL3D8ea0LJm4rdI0oBoG", + "1ZViIO/0y90AICgmaIzDE48dZeznuTPVx1QqRYg+G3vMg+oSn74Qn2ZnuPelfoTCH6XdTXXJXl8yBc0t", + "IzJYc8fBMpAV4Mfo/cDx8mAmBdTjGFFbHKgcZ+nISLLb7JqKA4RB/TjJm2BbLTNqd+gsANuaLZvZxX5k", + "62q1JPSgD1E2M+bLSc0vwR6baBpmM7pF4U2FdWEWXYvStvDml154c6sTbXWirU601Ym+UJ0opXkMFctb", + "X3aFjnjhH0p52aoYN1IxNhKzP5dSzzcRE1OhvFtX4taVuHUlbl2JN3Mlbmtgb2tgb92tW3frl25a0NUG", + "kXyHLUW+y2NRnYkUmVFb1Ymf9dkGVhs0ttaCrbXgU7AWrDO7bX2qW5/q1qf68QweW7/ip+VXvDdX4iZt", + "JYLBaNP+Els/4u/Qj4gWtL5ETUvYhi3g+cC+F4kSVO9rlhCGdYBQpehyq3RslY6t0rFVOj53pWPrtNzK", + "8FunpR3jtcqZepYQn+ABOV8SWaJLqNXYDOM4Hd7SgncKi9HUR9RyWMPyY6ZLKXQiDT68YvcQ32nLuUHq", + "SfgY7CMfFOS9LSWdAc/cVFqqyaUWhexYPfnyQKQiZ9ftlOcuM7LvnvBfe0ZyHNDlwVvtCJdVMhXW0iw/", + "0J3BSEOL/f6SUfC8PUNj4G9TA7eJr57FoSZam0f4GnI8cf3o1gtBewR7121bJv8O3Mcg3aXx9t9OXr8i", + "JVUaajPgm6n5yemca1dOhlspSksn71nuOmeCZHOWvbOSWnzPuvgKK5VxkHmjiA0vdNpv7JW/M1MU4inc", + "R0E6dW5Nd3GO61ANFFeXslJEXgkXpjEhP1L45twileA5adLAb2SKxxBFWT0dPSV/n45m3Myr8+noLXkf", + "U8M/NHRz6Dppt175DTpRbz3MWw/ztsvyh1AqttlKtUbiGvRunQofvME0yhx3naw0SP69RaaR8xB0ZeOO", + "aLwVqu5FqNr6Xb4wv8tHuQI3uQY+H7uUYzmDeGAqjH6r8291/u31tNX5P5jOv42830beb+0iW7vI5ycU", + "bm0Dn5ZtoDfgcHi44Knb/rX9lJcl65PGWn7ucXCGj3upaTy63pnJnVWe3JSsHj0mhi3KghoWcl6B6+Am", + "tMEEQZKSsqBiMhU/IKbwQ7ngBkpJK7noRBL5OcaEaiwZbz/xG+2cwMrSW0YVUHXOLbwLLqiRyi5gQcvS", + "Lu7pbwEt6/3Cz/DNnx5DbKgrLrz2qzpXOCB+/UdBMXofVJ7lK7qw2wK78348koIN6emRAuT9ePBHESCD", + "v6nx9H4NnW8eD9s0c93pvjZAudEOt0bYcLcbX9/Hvrcm2JAGbvp1Crvr6eLzihhx8bTbmJF7jhn5yer3", + "Ky8gvD5gT6WCu/F1yQQcAa+3L6igs2A1YEt/O9X1FS78VQT2dedVmpDGNK6BkeMSY+LYzZgEk3zXXOUi", + "UBMRWFYCbradSAT+6wnprS5xXvHCEKpkJfKeOg7YdKJZ9wGKQ+RV1rhrG3UcJr6dClEMQvaEa3eh2IJy", + "EUUNJwSRMQbxollGsEumiKmU0ESwGbVy05CudD0Seh3F2mc/SmC1a1TU2IRoqJ2pZad5x5ZPyXQEC5yO", + "wC6zVqEIAe1diH+eMzCSxwrcnOqINGNFgZzMoXsOzTIlNYYLN+SkZdlqioUQ9UAYBUu6iMpbEKqLEm0T", + "DVKd7xgivjIks3NhDREkuDFhk9nE5wXUWLBkjZyoScLygjza3fWc3An455VrJnRlaR4UTBid5eTfdseu", + "9UsIhX+862NIG9i6GTUCjHseRZBb0dd4azA2sS3lYhFi5kFyLkKAN3ZRo4b8s2JqiaHIRy/enDicNz7T", + "3J5VLtxH7pTfxTmE/bjFKo8ZMgcT7pwWs2pd1qGMRnQP3QDw1j1VH88hl9Eafci940zROmV7tiyJgQUa", + "2aSL/QcLtLfG6UyWLCc/PQ6BCtuLZXuxJNPGHFLR9xOsTUfNhMH1XctuwaiyQurW7kFSTsxwmrwKMoAY", + "2Kh5nEVyeADnwv4QPDtJCpn0o6c+utt7d3vvbu/dz/XeVUqq59eGCe172qaZW4d3/ZkJpnhGmiMQqi1X", + "hp358fT06EjJ84ItJuEFPfn7iaGm0vsyZ28TIVV5r0aeza06aVcPiI9eCYzfwtJk+Vxc0oLnZw71Z+iH", + "WcvzQVroMzKYeWBd9rXmhDTPpdBfl0p+rahhGVW5/trId0x83bBgD3CQaN1r6ZhXCyo2xYWQhlyAwOEJ", + "8XxJBiGkRVOInTHuVg1pksAuWYpV7BeyyuGZJieYt5eh1AMX+wnYgqZiKl6Xzq9T0wnIT6Iq8PzRLJMq", + "h/RQ3JN4aB0P/XQqXh+dHr5+tfcC8gW9MZwao/h5ZZgmL/f+itWQHZeHzqeEwmwIGVyYrbAMiMT4Nnu0", + "e0FztvMo+57tfJN/l+382+M/fruTffs4e/LdH588yp9ko/EIfUQWtUxd8oztCAq+GwvpJVN4CkePJrt1", + "NGTsPwZPCHiGVoa0uG0olVyUJjJ6ulMW/G4Dz7qlOHaJlrxlIWk+qTdmbK82hy7CDVlU2mCnfMBXHYfh", + "d6xXkLBQZVIYJowJjpoG0eBDEAQ8mce7DW4/3CACXLqWcKYjaKSKhPD1P7QU0xEGtBTyyvfbtQwr9vG0", + "P7EEHh309tPeJUaefmoo2jm7qzv03lm8MfA1lC1gYTS3t7yVmpp5voqP2p7ktXCkXMat+WG/m/xjIIk3", + "YenM7U/AmvmBEq6NvSUx8ZcKR4Pp4kWt8xTjZ0cxKAmbsQHQxecwysF1R7J7LtzLKXpscJ+6e7NbRqXb", + "rdVxinUAeqbwWydp2v517snHCZr+NoApvcThUNt4ViqZVxlT5EEIEwApFrfrYU8UP/CjNRAjuxrmRJdZ", + "6Bsbtpm8tCwFyd8y+eMf9smTJ0++v12A39oz0s+DKBf2UkDOgo/PfX0Cz5sQqYph+2x3NbmSCFDroF5p", + "C7VyMXF/TbRcMBhoHZJb9zPG0uM5a5L02DvgPRl17uymsxq5wHMHQ3iyg52jLXqsODR66oLoJplcfJ3Z", + "IwAf6q91/m5nJr++fPw1ruO9FwkOWMEvmVruGcMWpel3R2E3YXzapNjcDWEvcDtGwn4j856QHvskChiF", + "0Scroi08fOSZHTLF2SsMKnzZ4xfzz9uT2jO54EXBNcukyPUgIA7cYMnKDDqI111IUPQmVm7rAnJRazWr", + "oHBj7KPs152/UkV34jfHL5w9q96/K6qJdmzJd9MW0tQcM5tTIViBEdJX7Hwu5Ts4YKvAe3P8Ym2P5HPc", + "xGjPkqJraNgd8J3c2rixt99lECFqSeLH12+OR+PRwd5fR+PRz8+f/2U0Hr18/er0x9F49Nfne8fpRP8w", + "bh3C050dVeYYBnbBBXfk0dauep2RtRsStO1KcBPcuNHgCSX10eNW1ZEnj+OyI492rfq9ug95HuF3WJBS", + "Ym96ou4FN2FVPiQssaA2ieT1EUOspSjExdakwu+CmYhG4YPUeP8mE/aY5UQqknON/7bQhbCdN9pev9LM", + "4We8nO3XhhZyhv3kW5UkWiH8+SUVGcvBAP1nJavy2fIHXhimVpowV+EcPz+JwlYbZhGvqPmZ0SpCZnZu", + "K0hc4OyTqfDVlzBlkKNvGJ7CYuFeDdHw0SjPls6K39K/FjJnwHP+wIXdu1lpdr4ZjfG/cvQ2usz/wP4J", + "pAdpGlGtrr3VQI8Sm09VNueXN44Q9J/fcV1Kvx4YnRb9keCfcRT7lxIv/XkG7r5LhUnveS8D9YDjB8j0", + "MAEExGC3lCWhjUSdOwmMdnh3bN8CYYFyfMRx4XvIT4s4EeAGvUtxJcDAG8NM710g3HDOnDgFq4NY40nT", + "fPgNJuXwmNGCS9Ru2LmSNAffDbW6KzX1PaZo9s5+/7y3CB51o8GrUAyvKAgYQYHpg0DXZOnhbgZmPp4K", + "4w+vnzaDwaN7At78EzD5yVRMxX/+r//9f//P/yBnZ3WPtLOzp+SNZmTFbejboiWvlHCVBJkFLo56Z18O", + "vi4AISdFNbv7w1MzBECxPgNvwx2fKlyptgtIHCGwulgqjc4g2Kh3go3avjLgMFqBbV9qM/wwOinsjf+w", + "KwjWRmSmdkAizKQ2IRMNbhs8D1A4UFS0mI6cPHbBr1ne/BCC0aajolhMR3ZbCquXVCU8m4rgln/x4iXO", + "Y0/8uVVwQpeg6EjunC8j23ZciO2Nn+/LSEdoCdh9gf/oj3BWPJ6vkrtXBzlvZfAvXwbfyiJbWWQri2xl", + "ka0s8uFkkdY9Ht3XK67qFy9evomQ2URJAM4CD7A3cfGSlroNZs4XLqDErrq7vPqSat7J4Z7qGsZ5hseY", + "HB44384DNplNxmSKRw9LTmcFrXK282Tn2x0thWBmOnro9gvu0as2r0AWRSjRXMwKx1TsqiqD5a/ZdVZU", + "ml86XvQLvOAY7vKXeBdeAvCpWyP+pKd5ZmeLXX3vubQsL7A7cniQXA7iH6L3ErtQM8G1K+uuKACUWlqp", + "eOZSzzY6ghHFHbkhuofxmGlZXLozhXeCm4/0H53JVEB0QSnLCt17XAQ3SpcAvurQruPMU4EOYosnmhnf", + "91OBZIl7gWLYGp+QW4FfJFA8DNRL5nZJYbYWqcuSCcqR1qkwcyVLnm1K437wVcTg30lS+pFfQpIimh/e", + "mN5jNNyU5jdZaXKFK4kfSPI06Yh2W4lEC15njHzZZJuij93+g+kRJAt8qB+CbFUyiDhHcnyKL4yJrAz8", + "N6PZnJ1ZCh0TxaiWgouZ//lKccPGUISK2esqeFun4hf34y8gbwhCC05R+PoFZvhlTH7xryfewel/WYX5", + "gL8kkZ2G5a/E/a3prEbzTamsMcL61fascjWptUojFMUi4ZVMZfMPu/aPaj5+Fzy469u01HbMaH7EFCx5", + "+I3xqlowxbPE/WABh5xPGB3iLd1ecEHenBzEeN6vX7FfwGvgabG//2xPwT1CBqdsDWj4TgM2OGb3AlbE", + "QxIAgc2mCQqe5nuBBYfuBeY1Pm5AE9jYvQAURu+F6Ti8EYHVjvJpbF4HgyuOJXZe6RfI91Kahm8r0zVz", + "hXSA2yLoh95ZA4pSLSdgNQOZ1diDuwo9zCTiM6EDE2TFO7tiiOepzYu10RWC/bjIiipn2l2rRnudunbo", + "afKA52OrdCdat6cchG/aIzQg+ADVkxyFOlwRB0+I3kyKbO/6Sit5Y4MgfLGoDCjnVWqFsRiDJoi5ktVs", + "LjEzhuwdHY6nAkpZOEsQ3K9cGKZoBhF3cElSHxn5le724giIm5XmmzMUgBJLxgD+ASF4dtkr6GyzziE+", + "ez6OUA6zBIv58D4iDojPoCKED7PZ1oK4r1oQbbNVlwT6jVXeNuUYUKhI681VyJ5DxpZ9kC8FXTg9NDL8", + "rCspZEXSwUo/mBzhYlj9SesuvG2BmL5RN7VZpGu5oJ348OD5Nc167u1gkqbk8IA8ePPi8OAhWsMw2QFi", + "j+11xP5Z0YIbqBcMF5XVNrp3EPhzklXxYEyf7uHzFVGrzUnBNcTd1RaMHhYBAS4P3gh+yZQGtcbdKC/Y", + "Nc/kTNFy7nrynUiFN0R92TxsX3h//u7bv/3x22/3fvh57y8/Pn/0+NVfd/f/4/sffrzDcoE9kePIk8aj", + "6x1pBYVFaaJWqz076Rx56zbSmeBDtllrh6hIyAnOvkBo2ApndnI1UjO5OIfCXu5aLOTMopnsvToYzphb", + "3siNMTNGZ+B68gJi9WH0gchCMtbqYP6emWdmyMwzuFCd7+lOZ2cbT2+lm3tABC/4u/XALKhx+SvNaceE", + "z4QEAs2cZn4zKO6az9z+4I5Hf7gVam6Mi2IQaRaQRH/HdFkMo8t67nsiSrEeDCHvjTeIYWfCQnDf50IM", + "OBgOEx/6cIhbI+nGWJHq7q6818cf7sbrlwVOk2lyLUkA0xg+TTkAFnBDSrqzu/gGuX4f9IK+O/ju5o64", + "S3ju/OK4O+A+Kru48cFIMouCgi8lgWz7CHwn7D6NtNC1IpRfAbtcNG9v4uxplByLu+3g9LYsO8qdGHE9", + "gn7mZn5El1D4manFKnzhFpf4MjFMLT4qBssm1AP7M9jP4/XixD5/nYszF3mWTGOP156AaioOojbaXPgo", + "tk9iw6U653nOhCs2Exsyh6HujWDOxd0eIr150B9bkUrkTGkjZe4irsGbDcWaFLuoNBRrILQyc6n4r4xw", + "cJ504IeaSs8qJQ7klfiRayPV8oTNFsnCKXtE4yOPVsz/PK+UILm8EmSOA0AU4h6Z8UsmwifJ6lXgPnCj", + "MHPFmKuzoF2w9JyKGcsJ46GUV3vK0JVegt3aBU/a0aN80WRlvT3zXPTktcaVv3zJM2pcfbdQaj6Vj3rD", + "ck8BpBNDVQLzKwBq9EG6Q5AalecCru6s/BwkwruVnCtG38Fu9tWVS2L+KQHqPTx46ssONmNXVxjkLFbe", + "D6gv10JC2J2PiIbEfn8oREDrnmSpPZ7NXfUzrBJHMxcmYg+qwZParCpHBVT4gIDq2rk7SLD5c4DlmGVS", + "5aP+BQRfTX8VvkumMA9hRR29OzlQ5V32PGo2vXA8drKiclzt6Amct2anja25g8W2rlG3cg9bvRsdxtdz", + "4sZNnp1kTk0afdt3123m94y2P/Z6Dnd0wpyfV+F7AHnr77w3f2eHfXXdUnBC3dM2GQBJ9nc0axzsD++f", + "WsF9GoUnA0tYx2lWcxaPDD9xL74/t+4TDujtMby3Y3h4cMx6y8GFZ5iNBKFVXlOnghweDIuX2kvEE/n8", + "rnTi0n0c0r7w/cODIZFESdyJGdMGK809c3WuqFgOqZ2DlbjGvw08Ee711iFIikRxWS2nRDqtOI4LcdHn", + "WAUKzNrn4B7wZdP0pF4gy3sqiO5ZaRbf8PWkLGVIn14FZV9dMaZOKdTfsLDZZ1K8069zz6z+0Cr+vW89", + "xrc6tUDXNegMvfwPD3x2pismqDtdjGl4+yOEZYQdHVhBCsk6ScauTl8RyiYi/iftzUgWevNtB8BV06x2", + "Vg90p62J633fFCD88o7BqU8e1IZOQ9U+nk3auqC8QEeAe2mylk36OonR/kSY6eegjsHsV0pLNUBA2asr", + "5mEvCfudvZChsGMqgmqovBLXIRzEmZsc8j3k2B7ih7E8EKQWwa7dOvuOOqzF8W+oGWHh8PAVXJv1+7Di", + "thfa0KJ4ycw8VczOPSYLeO6hiKrsxiqgZTdnklZm/ng0xr9oyV11byHPMsXguqeFPgvQpZTDQ2GZDy1O", + "wKQLBPuhzchMQIU5MHdQQaowCsmkQBsXmkZKBUTOoKk25MZcVMUFLwpffNTftaMk9i9l0mvkHsTGYWrv", + "VvzV7b3rsZ2oKFgULLMj9bEf4Doh18kPe8WLgpyzr+dUk3PGBHED3Xk9tC+ve3e2HE6R++4LKNaZSEhx", + "jzG4oCjC9hRcOOYEfoSXVWE48dP7t1whdmmIrspSKkuYS2Yabb+Hg/oM6dhR4777HvoG5Cw/YIbyItVE", + "/wWbUdcnZEkUyxi/9MdhJmWuoXEcimsoV34p1eMaoP/WV2Ug0RkgaD3kpVMxH+0+/oZkc6poBuU4muUa", + "7NMYrnqeFFSKXpg3wvBiBTuo7PMGP+BwC8LHBAvYAuG99r/59zJ/RjgIoL5dUtwN6UqqdxeFvCKaGcPF", + "DEc6vAiB6GWp5CUt7Pf+aoAWKqSGHcHk2o5xx9JRXrEU6R1UDjfe94qcPfb0eRw8iCv1Prxnfsmu8X48", + "zPXws+wO8V5ZPo8+755d/5QcHuj2KrkgEvXFstREV9mcUE1OjOKp+r891RQ/P+V/PMJuXiuv08ZNavUK", + "+ATo/ICVTOQY5O99VabqYBcykDMqyILZ/7P8vSzgZzHTT6diBw/DmMyo3QQuZk9Jenq8yH0PslBVpO8k", + "7rg3+4arV3O/dG1vOJ1K8sNIoPgi1LVoZPEKXkGPTpDftSxCifdYAR4oxMNML7hIJjh9sDb58XHoBCrV", + "dXdw6IR86azDm/KIV86o3IEVH/geCq6rQavtzTu2DPWIQo8HpG03PJyJ04jAnK3Tkj5GNngJF++Zck41", + "09AB/YqBfEOLQmZYst+wRSkVVUt8eSqag+oxhH5AB70LMB9YDVtiU6SYyGfMuDf4rywnD9zZgY6FDwHi", + "o4JRDbKV84qaukQ31+RB3j7lVamNYnQRjtpDH7DhGKDb5qm4msuCEalmVPBfXQpr+61AxWNMDkIGQR5o", + "4L4PoedOJYydrCp1Zwr3OMmlXZzRxnQSBTalbpJDgWwAlgOtE8WYzOXVGC0fklzNfbNEtwl67guElZTn", + "aVjvwVscgwA+bj0hh03ebHUiISMZ3HVlBEnbydellXTzZO7QX5iV0Gt0KDaj2CDJ6o9cVjoS4EVOSmlQ", + "UwaJFsRsIFiLs2XUdS6TSgUNbRPWdiCzyu7dMbsYEibwz4qCMH8iaKnn0qy5C4OY7r8j2n2o/eFoMnNY", + "jKHvmLjnK8ZeGKfSazIbXejQFsHIHnPq3UMKMsLGZxI7QfQZN1Jyh2PHXLugYEhEzCS0RMG6NIuywNYz", + "+P3YFZZSzNEmVFuqiRvDRvxsTkusA+Q7R7rx3g0X3K+LgrnVweAW7p2Qge2gcpOErSrLgt9AZz6iyvR5", + "ZAy9hqvSKcgwx3K1ggzuvM2Rc4qfdcE4qRYLe2m6Ho8NMRS+GbtCCQAWvWaaPKgVu4dJXPmQ080ghEze", + "LpqiIFXeEht8AKsHOGeGqQXwEXChV6qUuv01sNW5vLJKan3NzKnICyelnwSDCTQ1BYFbGypyqvKnZM/y", + "7KqgimRysWAq47Q2zeSOm4ZgTUo84cC8gWXYMTPFcm7OrBzxlByzi4JlBp2pF5UIMZ0lVZb/W0KwyCuY", + "iYJ23T0T5p2QPTcsiifs4oJBiFyxJP/CwFyj/8V/i9dN+DS1k59/YePY43FoRbmEXvFT7e4AaQ90CqSA", + "82WT/TulafAt+1Nz8iFX7KXk+YYqJn7iTSnpp2MUvZG1e8VQM+N1o1UD3+8F55G6Mcv42X144sTqHi4b", + "NN22R7TNUw7Rb1pc0SXcd05U8cetozH7iFNvGmrbwaCX7lQgyrmu3d9Wj465D7suC55xUyy9l8CDyK5L", + "yzdcyN0kXcmkr1p36Cbmrq7I8htUwshwHS6XIHO0r+Ror972ezFalqU+n0bzNeh7B73bsAfQzW1PLf8e", + "fJWUxU+bEyXmqf+E0sRlub4PV6ceYq1S3WR2n/lxo7kNvb7pvIZe32TO9yuowg+zBx6pSMpLU0fzda+t", + "OPmtlSvREuvCTZ/5EihTIaTYCeayoGN16UUxbdVpMbPiZE/wF9gCuoY2BcYn5yp3c1t+Yi9gYDpU5FOB", + "nhwrqLDc8iKiDSvRW6Mr6AV9URXAjn6I6iVhRg9QIdo3ztyhb4NgoYcUIPca2tXPvF39TDCW119NNu4u", + "3MLP28Eb3tzBD7bv6T0fCPNgMDuQUfdz3NKgZMpekLUJNtqEZG+CzW366TOWsjXCBC1xHw1Z7NqsUoSQ", + "ku4TNpwg9nMDFh0V6rarKAklev/uD0hwADbx9wD0ZctnnMkwGHLc/juPZFpn4nUEwG0gbp2ylC3OnRHS", + "ORkpsBQzanl/aDy2wzciGrSuLEiWKeK2Y7RRWid3Atp/oHHJH557gdQbvLwlizNMgMCgbfSsRI75FLhW", + "mL4/AH+SPMcavHbiJWkSYQKgFXf1gbPmgN+jjwXGLzXiU2o8hL4EKScMNm/Hw1wsCc3tvXTBktVjDZvJ", + "G9BhDOK+1GbfD9TMvnUKfSf11r/eSLl1EHZ297OOXQGTwZ5zpiTvvX20KtD6HYz+8v2TuYZtB8EF30WZ", + "Jmd5lTVCAIA6MLb9nF1IsPdeu3gVN+RN/HP7rTUMUbXvPGbnNBgVM0c1Hi/b4JZ7D27hGjxbm18ClnwO", + "wteJy94/82buFbT/il2RAIm/+ZG3XXIaCwxf6ejFvaPDMXR5ohkvuBWtp6J+CmwUzgfa88SsjgoAv0mS", + "I90mOsSi5ONHiNTqKZ6hDx62flOp7Nj7u3t4RCPSA27Kc1ZIMdPEyEk0sWcVqxs4RXZBR4o4Zm1gcsPd", + "dTD5ggo6Y/mz5Y3o62X4uoukMHIUY8BrUrAyRUty8KeLlpxIRdwA5HxJXpdMQDOAJN19PjEcNFWC6sdE", + "76TOjOSZc0c8Ai/E42+/6+e5j7/9rt0AKjBgrsuCLolLrOmzdd1nZZTVB+EoUScl3L4lU28EN3u3qhSz", + "Zn4oVxOFH5FzBtqMLPLJnaa4HzXS2+sjj/cSNgyUikBMemUpIZMz7DtPSlWVUjOMvHROSm/0NlZS1C4c", + "AiINsJoCLsMVor1krr1i7n4PrS4mcYjA/aD4P3wgwQosK2rYPlX5rfSFYz9ImoPbOUhG/3/23nU5bltd", + "FHwVVM8+lTi71bJsJytR1a6ULNmJVmJby5LjlR2lZIhEd2OLDXQIUFInx88w/+fXPMY8z7zAvMIUvg8A", + "QRJks2XJt3DVOTtyE3d8+O6XPK3WXsOnFzJ9NzTfmyW0mvCPK+Z7z3t4epzQLPOGDBQtMFwHuYWxJc3I", + "ia+WlvkOUCZ4Cp1b2GBiZhrK6RpMqorzCl+4+X6DAbooaNgOVo7IznZQTtC069HLUhMXEEhFcobOyYbk", + "xqzY9HofUmn338uJ79IHlE/otU3WTVytKad6b+bwrgIVSEwRKQIFqZA3rZvzbyJanWDkUh+J6rbdE/BD", + "/QQ6fA7WHnrgT+CZyiDn1dmUgVZ7rXHls6v521mjYIyWxpLhC2yEMQOiT19QMrLj9oJE69Q1fVRQYYfQ", + "E4RXdTcuXh1dOMwPaQG670L5P+mpSORiwbXzi3AAUiqKyu8tgWvt9KTPZlzjulmhpDpfcqGZ0Pdcgn+3", + "PQfTVQ3aDWRjyxl0ycXgURURUqv4p2TA8o1EqdZUgS0unCHv5c9pcipemwdoGO5xpU5J6VhlQGKaM1YL", + "QncpBUc79++PaswtsKV5zmhYwhVS5r1tZ+4xMWQE/N+VY9qEP8IwBOCud8nO6HboXMSvzVG2tgspRMqm", + "XLjonmaP4J7Q1AdrjjRcZlQ4/qtSWs23bOZbgpvowkSBV2x/3SBoIJ9LzV7YEPVSG9BuiQmmCiv4Yluo", + "kBw4z0tCBWHXXOnQ68sgAxjrXpdtM5goXrQw3o7gPdlieZZ6+pkd84sQ5leahlgz8HM7c8H7Z06z0oE9", + "n4DvS+s68XMtBmFJc92Mp5HOjyYIlraFx8KFYthJ6L9dOrxM6HKpulb7AxPmSdYgp6YbXXANunCof7t7", + "Klx6OgOr1gedC1ufyjO1OUvLA59TsPKgY58PkTM8u5ILfEc5mxkGBIQ0ZBmMrAcMidolx4yixdyH2oFm", + "HiUCjDxQNDBeL4zAzxAoz/HowNWMXetdcqohBlT5fGBl3j+SyJQFY5wzv9oIferSKAdKFe8Cf+5KS7W7", + "L0auCku7tShRysiViuZaWE97EBjcQ+SKzBkiJ3M2LimxQ0HrPXNu4iFbf8DdzrIeYqqPsmkEjJaM9KUA", + "W2A7jqpiuAlrpOAjTeB9Yi6jL9Dly5X3asNanSZIyAP2mKp3MEL6mDgw5EZsj3OepTlryfKPQQsIlc5v", + "G+YMuAtUS2wYlREaYPsYsgbj42B8HIyPg/FxMD7eyPhohY2fXCXM9fY2X7XbBYDa7I3KU5QaOH3zqG5W", + "CY2UdOvP+1vf/f6fX36/e+b/ce+ruFFysJS2W0oHu+jfzS4KFdpZepTD4aFh7F+3qFE5cVXgWVqGsYba", + "FeCDufAMhQO2L5whDUI5jMBCxSpAu47fKENPhBRbf7IcajgkFEPXlrmc5UyB2c1aZMaOSBumdi6vFMSz", + "LYoy9QEiI0O4nTug6driRmk3d9tnFj0rLL7v8kq5Y3WgYI/LHmT1tDBtesmiNbbxCdjH/wbW3+VdPsP2", + "59f69t7r64KyHmJlGzReug+6NMg5Ip5w5XcYT3mwmQLdGRFKKRk10Bt7MsB2tpCvidnb/3gf11zTYd/h", + "Md/YfaA86NtwHnBRzmXjhC6hyLjldXWQfgqtH+ZhlscxDWq9hNc3uCUMbgmDW8Kn45YA7/cM3u/gmfBh", + "PBNAIwH2YKeOadVJN5vWkrfa4nJx3SSmRHLh+e7JhKrKu6x995Rfs5KCuJVqCQtZhYk/jNC5ZHkCJRxw", + "c/cmHXeOJ1It/pCsanqbT12T/bdQsZ6wa11Rr1bSUZXAA+xxm7h2y7ksP7ZoBSM8zsA66I7jA+SxbDd+", + "3sgB6CV2j8Vwmg9g7v1Mc8jUyFEnHbKn3FkTsx1qO4nK3yJfxkeVsyJq2uu6o3rjqknaZmayZNVaM6uO", + "cp1Wybsi+3v1BQFLgqtVt0LV34Wi2FNDdYtd4eZ5K/o9x4PQjNd6y6VJrp6PoqGKqAk7eMUrkG67bjR6", + "PyjBt87h5e225k4VEvKcaAqv+E468WNTcazGH0fS5bbUPnsVhNCv311L69jmKoUcw9eF+3XcLPoTvJsD", + "AKyqfe9rcMyz0F7UCnbPIrafq7m0ChIVlR0ryo/xCCtFoLhU0KzLnw3ckNkyowlD4ti5tkrLRilj/HUh", + "U5ahl5ggrx4fVV5FmXwSfAwX9IIpQPXOom+kkCyTV1jYBVhxMSOCXVknHMNBB4Vfcc4NPc0+mPvAJ29/", + "Nkv6WGzQH5cpeAgvHcxnm5jPPk4Tz9/CJvLxqtbjCtGIKnMNf3vsrT71ygrCJ4WuOtSrpk0nYC/AegOB", + "2eivCuUWM67XMRZxk0oXgxHtURWCW00ty7JKV4elpconWCvT0W1mmXeWq1pt8mCRE3JobdON5Rso/ULV", + "x+CKpHwK+9anwnO+Yc9Gp2YmWHuM0HX9IgnXimXTeo7CcWBXh5zJe2QhhZ5nzjxeHYSKZC5zZPAf3H/w", + "NVJZ7NfYuBshpTxbofnXp0aE27wCMj6nlyx0JJHTcugHlYke+rIPUENPVSbAUhFrz/FUOD19uf5wkoc7", + "cdWh4cD7o9GyCm+Lgxy61fQ3IEIVjVtcAIwXBeZbtMauW8SaeWv4syYV4YnYmxnXnv4ajHpCrx+zOb3k", + "sbqN8XY+imUurzz+d3BYE3sNhbIKI/Rk8VzEglGL96C7smnamQ9yqnZ9ct3aEf0EIxOGVf3dvMAdu7/X", + "YHlnoI0ZhPctGdTSEe8mBaSwwgxDO4ygfulC4CqSYxN3BxeysR0hvNBI0J6q3Zi/D0CE/h/T2GE2c8bd", + "ZtwlvSbLXF7ylOXVs2wrn5JsVOrlCDvQGYtz1GAKDGMFl74DpBn3bqn4ADA8G5U1p8KHiF6whpkRfvc2", + "RrJHBM+87RFKUtgwMzMMV5abWpxLA9tffcWu2WKpv/rKqoXo9eR0dC+OmXK029yGSvVYLgxEF0LnnPlS", + "dmD+LWU4P2P3ljdK3dhURnVhpUrLmp06ZJFLk3CLVg6La6SFz3qcykCZbZlxlJVmMud6HiK7SNTVYAUe", + "rMCDFfgOrMB36p9bdcj03rE1pOFLj4CoaGOIsKBotgJawaOOuQZjMEHPM0ylXgl6oMFgXRYrtB54B1PL", + "KhWCl4pjkbIcq/CAe/pdOLjiOTm/mttf72Dqf6+mfg8eHbLCc1+BMUqMn/vygbSjKqpFVGMyY4LlVAde", + "sRWzuyfJOJRgShGsSghl1yjJsKrJlCZa5ljhiC6XrrAJ+dIuYYm4MKhBaH5xsdP3TDcfCgj9EyZozqUi", + "X4a/K7feMA1/WYJF0QUghSm/vle59sPnv2yVV791f2e9KrlFGnmRpyzvMK/Z7zXdlzS/Qh1HLL8C91CK", + "HhDoXkl04ao7Wf2cLxYbuiS2QBSqFI41zTuVZ0d0xoXpFBbArydBtE3M68I2DScPZ92MqxNU1aKvydKG", + "xm9iFY0ZgJdR+y8oEcB4JVJ2XXn55ZVyodkMsZtpe8z/bBlpYa1ztiAn5BowW1pCLa1Z1S61c/9+bAaw", + "iu/HuecTbzWvzVAZ+OvYwPVkC+Us9miCvbnD7kAplaqbETDAXJheRVotH+l0D+0VN6sgo90sPaXF7oqg", + "cIjmG8Tg2JXWsNyk02x+hCVWrdNNl3m60bJunraRCBXzdMVh450SSAwG53c3OA923cGuO9h1B7vuYNft", + "QwkPxbLQt0kOiatn3q12fw8JbVzGJUy35fV8b8c2d1tHkqZal82Y2Sa38Raw3SGOsRPx96uIkWUcEq5z", + "k+ts5/TX9WhkD3W/ezuxvWt3v4AymUiXkqOyKuYbvnmOjzWpPSyH6vJnucJ27blluHJSM7tqnsrrOQMl", + "Xr2WqWBX2SoEgBZd2bmUGaOiH1AZlIYF2G8GWP0SfNXAyeUpLOt2VU6kH3ApLCj1lGeGmvfGGZFuFXdU", + "nszLB2dNktXQgAjmMB2i4Q9Ymz8ATpTlWoceEz6FUvzWEpaiaiPLKr0xB8Wl73VGNTkt7t9/mBCqXkx9", + "+J2zqJoxfospJKXIVr/D8PEyYI2RSLEEtZ96MR0bgDwVIcGKdFQaYp8D1syTQbeIZJVkDHwi7DYPD5Qz", + "HoUJL8dkUSiNGfowOST827PIwAhSTA0J67Nz2mqKsKIp5VkFxGue3D8fHpAvXwl+yXIFxr5XqDb6mV3z", + "RM5yupzzBD4cy1zDjIdezXXvA7iM9nbTbj6BlidjmUdXvq1salgfBFXzj4oXcylwWiN/tY5wUJXYS5tO", + "tx55HQ6B2trVFk6QNJj1P17tW+H1VJhXaGsVP1ksQcNs1XM0Z/CSwOk6Gn+iXkw7BDKEpDKVaVnhz+NK", + "W686fK/jit4JBgpS+96i/Obk98MWZ2Yv3x8ewF3ZjUhHMmv47D2D7RTR78aUeA3+j0UEw+cyBhhU9x5w", + "q+oagBCHJO07eHHJ8pynEe7FfbE8fRO7Om20M6eVtfNPxT7mtvMpSLkyyGQbzUNx41HgWHdeKA5K8UzO", + "eHIqfGlRrhsUpOoUl8spzyC7TMeCHfL2GalrjEWDO/Sg2EG6O9wkX9YSRLfS2fWe++8NpNcaKoU3mGwE", + "4dbOEuc4S41tba/d7mJ8zcX0CZLZOECm9RJ9DfdNzXtHNNer6mrbZC6L+2p4GzgKm3bv41RrrmXY605y", + "wSlvyrbXTrJp7fhkVISqAAXZHUKUm6Eqxbdextsy7/rGCOC17dhnWW4Sh7lV3AZRdR21Z1WyEF6qD1bd", + "gS+O+cJGHXYLXbV2TfZR2QZVBvLu1TLuM2IqKGcfGEvQFmZo9LMi07xU4DQ4S3OUMjec6orpLiXOz4EC", + "pw4zpSX8hk+5PGYni9ff8XukRO+iOKptZD1YNXOmR4XRSg17hD4XXuGH6lAaDfav95Hwl1g5yqliUsJ1", + "mUao0HLLPxR4m1CDpRo+7bva+BCnHShFMyXL3XsnrwQqJ/jCCHqI+xzsg4N98FNPmzquZ5W28VGB2Jut", + "PmrL5vtOSjpYUz8da2o/l822YNnKZ1/9ph4uW2XJnYvgjOo5+BSOxqM0p1Nt3QTxF3QYLIvNnS1zmZjX", + "Bl/lJcvTAr3EwAG1EInMMpZobnD+eHQpDZ3uch/ENWN1mXU7s60aOW7szzXfedw45p85OjRQmSNbwUQi", + "ixysGFqSnGUrIq24t1gUYAPYnkLw8Da9pBk3P6Bq0oaoKqwxZCOGMFZIsGtNlGbLiA+/0ox6JM+uNRMp", + "S+1lwYARVbZLF2Un3vj97tUHiL9emgSFtSxHvWS54ShQq1+XgqvLb17YE/vdwR0XyJ2Ur6NDzRVjizGK", + "uwkYqh4oQQm2hZnZ973Mqf7C107AUg4N+4xbV9b5Sfx2Guc4bt54Bx448cljo0lgKzHoqlgsKIR8GRSQ", + "ZdUkQ5EruaucXqWb6iXNimgWJMgxNg6lAJGSsrBp3PaOQS0K9n5b67QJ0eQ0slZffcbVZg0KzOFS4svE", + "5GUfbJmtydPCWkEfbHV+BW0Zppny8cK3ukiEyHKpmOaurDAEkcgGD0qIE7ENKxly25fsY6Pf55Lr+qju", + "Jb6HlfXISX1ni2hCHp1qlt8E08TT99XwT+Mt1R5+HDDiEF65IXdIXVShq4YqpPOuMU6udmpo6T9p/h7W", + "rgb+vMiN5Fnnc8wJzuUV4TrQZcypSLNq8VWlqUiNPDEO67B28YgRWWR9/cVNC1aLhq7xLotWr9fubVDG", + "uq46bFcUBpY0CF0EhUdqi43fmrbQalGe2mkv2CqqRLlNMf1uam9XtVdDZeoo2nHmrUMX73dsTVf9zND9", + "uq+1T1cT/XrrWUXs9da1CJtbaLmXXlLvzQAnGH+d3p1Tgh7bCDfoQQbCchUnIrExd2JEa6vum0NmSNXi", + "izF2s5/cLrAdNKDCaS28K001NyzKzvY6bOqTRKaMfPlGYQS6+dcbsk3ewLtI2WH65h6Gc5ZuKRFg5OpU", + "lCgQSS8VREiSSTFjeVkjUuaGpxYzlu7a+McZFfxPXHZ15JTBuLb0GYjcE/LEFf/V9HoL2gBDoKD+s9LW", + "GpGzhbw0r8us5I3L1fLG/G7EqFMxLcz1eusguhuUF1qBmNHR/YNRFCXh5dckLmtEvGBLcI2EUZ3sPMXq", + "eAXNSM4uObuqRvSNjnYOQu3/4fGLb7+BkNRm5oSC7RlQrK30YfdSEXqjDnNpYdiF11zPscq3i5hTMitQ", + "soR6ylJkNtgenTmDHTlFkYSia3NZM3fYtfXZXJg76YlIj3KJcP1MpmxjQt1ER12j4ytz53nOs+yMJrqg", + "2ZnX8dUs1VLoXNpMS+HCt6zXpJobEBMs9fTIa/Fz5mvmdfmFxt0N1qHfm3oDlTgVkq9Z9ZiXRZzqg1CS", + "+4dWik8w4oRAlt3Abklqi3MkoYm339kpI06s1jhnVDXcrbbyPr4X9XWsvSjXsH5HTc8RtKesKvodn9MY", + "4vqTTApW994uUXdzSGtqBftlICA4t+BTASH0nseU1qESVFKKpyxaap8ul5sz1Ee4yr3lUr3I15VshYh/", + "jIwIHCEN6pV5MmdK5zUH2mDz8ZxxYG6sLiXmtxttd+AcZ2onjpX9HbL1h39FA4O+E9FcF66IEnSp5lJr", + "fDr1OxlX0Dj3Wl6aYaVLLjAPAyT4ORXeBmPHx8SKH975cvOHXkPo6960syKUr6brabcAwPhGb34Npn5m", + "UWjcN6zmqf8CWFNrpqjq78MX7TyeLHoGwWIFJAf85CmZc6VlXq+cEAxxKqgu4wEMRlhTuuNG6HmNUNEV", + "xlWRAzyy9vfz1tu0bgxSNqWAR90toqhjjTrWUrcY+HMrFxmFJyNwAGP3kikWc9wDiQQRQA5N+lZ4wHPk", + "mtOMzHLqa29V3E1kgVaNBRd8USxGu/dLkfIw3tnuwXqwoRpA5tYq7lmpnRaZHlp6mIxszq+t4EJ/iwoN", + "XNqDr78OFho4e+AZ2WWWg/npRmvTZnRU8viZK/0E1SygV3zJFGyw6VCotNPHQEOzCNNyPJKCWdDs5UQY", + "zBZxHezdt5nW5e3vdj9Wr9O9F6uSuPk+7Cwb78H2a1n/M5pfMA0o5FAoTbPsJfujYEof0VUmaYSEBz1A", + "rqRZBskTmdLmaZtObdkCq+RhrV7hcErgZ0IbnIFjW1wglRMiMbOSeRyYEw5yHnknu0xJSF5GVUUtVB+c", + "TyshTq4ZcIjHVKTnEqoYxXUVcWet53Th+Uor/jlNgz1DH2pFMaCqEuBil+CzZi+CO7BZjr5Q0HUy6lU9", + "KXbtbTHM8QvH1lHmdR0k7y2XgVbnqcz36ZKe84zr1clqGXMvdqoaCMlzjTlG2PZ5O3vLZXWOaGBhBYUt", + "l6OuJf7efag/46VECgXF7m5yKl464QUSkDrTNxbLEg5sKn2rPr9wLaUqPNQLoad30BO4f9BEQKQpxF1Z", + "Zx6JfE8qxRfaembAeC63sxVQQ/b3r1HlRgw+q9cchpcIKlWXQxVzwC5lHroTezXbaDy6YCsLwkt25rud", + "aXo9cm9stO9+NmOXcO9bm18Ndowux/u6O+HMpjtLizAfcGUZLhbZ9yiX4uJB94NPnkjCp/JL65IsZ6Oc", + "KkgRWWiwDhns5HweYZW2h1tJoFZ03FWpQ6oeJQ595uYKThO/kKPyiztQ/OI/xMpK2zPVbGZ1qBCUqshK", + "FmBst4P7LQa7gHAABOBnsGgFugKu52eSFnr+wEgR5l90yc/MZn73a8YBqigPH3eN/FQg9K+4RPyFquCW", + "yY2QSyw6oTtNq588+H0S96GunlFTL4K4GW8eldXAesip+y2gN55c9g/GCKaPBmFEKV+5vxbyVFZg7idz", + "7C2XiMHbNBtfYIGqZjK3FYCK9TlMK9EHdaJSPep+yP4TSPwXoVBDDsC7ygH4jFFV5GiBf5rLSJJ928LG", + "qUxNm1As6A5FqA5+hALfOmGg3g1SrKIgEB9wt0mrbAm3BXYAYmOzbwZODfuvXr588vzk7OjJy8MXB2fH", + "J3svT0bj0fMXr5uODePR9Zbpt3VJc/M6Af9jCJs1KGHSzfHoubwaxRYL22gs9beXT/cfPnz43e9fzrVe", + "qt3tbS1lpiac6elE5rPtuV5k2/k0MY3A62FBQWvow0YIrtC8uVcn+7ccf/IsjD/xPnNH1ZyOnSm/R8cM", + "ruKCrbbQsWdJeW4wvxvbMYhOvQvFHEIPvdAdlZ7LQoNhooxXCdi8MvE36Dy/23n0IEm26P2db7b+8d03", + "dOvbnZ2HWzv0u0cPpixJH3wTEgn7KsxNz+SW/XFBl7/hzn6vnEosCe8epk62avqqtdYwwq6sASTNlGRB", + "dTIH8yWdzXI2M0yi4Z+0qm3Kfbbn+epZJQFsZ17j2gIPyYm8YIIAUJpJzHTogmRQ/GJptj/LZbHELLfA", + "SY92R/8xwb/8Wf3HRFsJhafrtMuWD4KZFXGeUSorZqPdkYZfz7T9NUj93LUtACQLhStcDozT5KoqZ7dB", + "DBXL94KeLXS8bIHuV+iS4wV9gIbqgzSX93Y8okJITTd0Et8LOkXY2+gzs1U9vUkJK3dOyD6swLy6hUwx", + "0u98Be72sQCw1sK9wYoixGUov/CRl1/4YHGzgHfi/Aa40RlUqDikInHvyPknuoxdFlOeileKTQso7Kou", + "+JLILC2/1cNZx+BMj2YSntDMtqy44N4yBQ1QbLQe+SVkw7DYwxOC6iI8al6TpjzA3Dck1s/pgqXkn8cv", + "nh9RPSfseglhehBtIgm71ubyMWLezGWQhnXO8e4BuCND2EG6+4mtyiBgm/4d/XaFAsEPvE2y5ZwK9BCG", + "r1COQCWGEahCXEAWG6SogYBiEc97HYnxo0zF+zGdOrvGwRAFHIsCPhUHNfWy4R9ckiX/vm8vWhjZkzbg", + "GZN5dU8RYELqfyqeGdh/V2iv80l3kiDg06+70eAM6/uIYLY6YkPuyaMzLmZMGYEL8NoXCjAbsUzmyvt2", + "+Ga2u8zJ8atnY7L3yw9j8uzwOfopPtv7d8g1Wo8eJ/3nhDphrhLaR3MrGbmmvmbmq+eH/3r15Gz/xavn", + "J+HA4+rScU0OCbtJJsQM0ehbHoI7RigLOBMyr1+sZ7vXUKZmIqz2Chbw8MYVvj0konElRo1djyv4enPr", + "Vj2Aghacz2g8Co96NB7t/fLDaDx6dvjc/N+9f4/Go5/3Tp4cn/TUHBwXCzO21dhgekv3r71L0+kZNxt/", + "BkaDn6lmSlutgmZ5W6kCJ4CGuZd7yJJ3LyRuIgJ+6rLdwHEPHPffluMeONWBU30PnOrA5X38XN5NGbnW", + "ImvwweC/sI4awK4K2TaMXLSvpTp7nOf8PW73YPm/CpavrKtZO7P1h2nlvMsivkYYoJbCiD8guXga5F1u", + "oRqd3nLQ/biFoHgWw81s1+nJh836PDkVv8oCwK9QNnmTlvYrnK2lM5Y9CUZ5vLLOyjX6YDnBv0b/wQWk", + "qVnqrUeGWTT/lcC/Ojv6f7A/wJ4J+aJjlCTJOBM65p+/D1/I4UHIiZiXfeHzSkEIId5MFZan/3jEvv6W", + "pVvfPUrY1qP7j3a2KLv/zVYyffT1owf3H329Qx9WkdbD9dUB8cj2O1KB442ZJ3++Kmsdeh+dyhqNfLS1", + "A9Uhtx4Y4PRW86ZeCCujq6r12dvIcV0/rGdR2mfodBMZHXOz5BBkHJBZ5xl2bfAtGLrioGJhZEsX+bkM", + "IMXN/JvjxH6Pwcg0ys+i9be0j3JBXj7dJw8fPvzO2k+rNfBvmf0MWMKGq2g1tyI1HPcsY4H978pHN+oi", + "F9ZplNFkTlQB28aStWZbV1ykEMH1xn56g3QmZxARkNb4xRqMVUS1dwEyO3lfmLfN6yBvfwa4d3+/G/Br", + "GclzJNIPBxd4X87bpB9z/Lrs02SPI6KWAyh01lgDViA6CM1zVrrnl8AZRL424A8gq3o8B3u/lps84Qv2", + "31JUvadHr072o4GryLfY8CoROCHDLf0pBUS32Gh651p0uPd8D5SAxExEDqim51QxAm4Uu9vbV1dXE04F", + "BR8KM9CWGUjdi4qoZsBXJ/swIcxXT71f7hM30cd7OeAg4i73JyhUFJlGchWwEzVkiRLVb3/FtC5V/Kkr", + "aprwefo80/DG4MxHuzsP3JU9EWkI5A9O7t/fhf/33yMPuuDgUn0JvpEBT0TH8e/4INdMAG/DgVIti4cV", + "KlurhaP0C3eLzLtBhs5H2fDlhEFlEkAQ5qN7C/0d08obxVCkBr1tVa8o55Cky0DtSvJfc+vcBtm2gmi0", + "NQYlshkXwlW5sGFdt4i7YsgUdCki7bMrLfvvCUsb1cu3fOy4GKISoQFR/M9YemePjNP1Z1G2hWjcAFPb", + "Y27GNsL7+L0bD8mrmBSTyyuHVPtho48YCbUVuehTnkeHpKh2A5PRzXR/Dc1Uty7wJKLl67mssAxDC0OG", + "FRSQineO2gafbR1AxRsydmu3bW++y0zjFBqTaPBiIyIxAKA1iMo+03XnevvYBiF3LXl43+urIRK8muqi", + "w+MtAax8Aa14py062ulOwhwVGAktspWLZbfvqKIls1qbqvkAtWT2QMalzjV0reRSmDGs01vMTP3XOjvY", + "u5u83n4aVQ0Go8Zg1PigRo3YJTyX+qksIJfPecYWYfxKvzt5Jdj1kiWaNYaIs3My5zMuML1CTlKewl6n", + "3CAVz5v6fC7VZMma5jOmS/8Ymbtw2Ssbx2vTp2ZSWWbRiJ1YVDNK1Z9Lzac2Ind/ToVgm+TebHZ+zc7n", + "Ul5E9h42hkReAp0I+izJFQ72KvN3XV91wOZiXwlvoMeaC9BQlaUFBbsy597YEeonE5ZrynGAvns0DzAW", + "JmPfMiAil8rDMNKi5TzX19TzNU2taqRloNBTce/lfz98fvDkp5PjXx69fPn06b+++e6Hr5/u/XL7nor2", + "NFxp1rL+6rtHz0UOvSWaLgar5WXWVnoSC7gDXyTdZpCKrGQz81TszirWqnL+TcxTkXV9ApF9MRw2hPbd", + "VWhf2ytqrtVmDu7EMRZcXz95/OOLFz/19HJzROb3+HLc52YmilaEfYVd/Buv2Vo/7rCaPmE0n3jYDCpU", + "fmQ0XWPfXiNAoDGV/HhyckTmOBrWDYUsrIGwbOEhML/7tQZDuAVFnslnE+iDtYureU2nNFPtqXDnzD8u", + "rlzxY8jfKmS1AFuc9B+4KaNVOj5rhuYTFwlfKZaTac6ZSLNVxeYWvQavtbXPrbeY5870eZvvGp8JyBOX", + "5NE4bvxMFHwvM3jWXj25pBlPEYyke6QJ45dQIE2kzpFqQfUueXNOFfvm0RuoKJQaXoiKVC7I+UozZXk3", + "SAy9zNmUX7MUCc+bq7liydmbCXnJErlY2Ho5/E+2Sx48qpwWtjz+Zvbgx5/FyVX63d78x6tXh8+ezma/", + "HH/3YiqP6PT5t1UA/hI73fv+N7r1597Wf9/f+u4/t//r978ePhjv3L//NszQ7g7FHloHt70Brxyj7zH2", + "+TONGinyrLl6y56QVy9/Nou3ufgrSMtWs64u3AXy218miVxslw/HLSsYfa1Oti1WIhQerCbF7KQnNxgV", + "sSNV4fGNwSvAuq1LmlP0u8NkV/1k7W7W7RNkHD4ygjuQpIEkDSTpU0Dnm2PsJ5csqmVok9zBePK3lo89", + "t9E8l1BMjjkBvpNx9V0STvBLlq/aajRClJZtE9QHbb/6jVVyAGQH1WW87ZRIcTG+GmJdkdc3/L5zG6Ew", + "+M8HPz0/2vn15N//evnvH08O/vnop6OX/zj67/u3LwzCWayRAZdl9tnN9dowgctfGzFA3RIgN5Lg50V2", + "Q038S9MzbioTlbWZKWzmel8tHsML/KU2i8nd2EDwxEeURNa2Fj923/8ai0FVYw8n23jHJZj0wvGPaUZF", + "wk7mOVNzmaWtGY7th6aRwUIGMAhhburJOQ490W7sNy2s+GZMZN8tHMQZTRt8Sr0bYZmdue1u3NZxxM2z", + "fESOK5iZnLNMipkiWn449FNhjPrgIu3wxWdFE/Vm9oqSZljWsRv+zYvc4ALizGYHcijvZNzunrnR82nm", + "nG6+nLvACE7Y6o8VXDAUvPjW+/eNxuFV9Z8lSH0P7mYs7ZyvlmXfZrvvP53Pbt8xR5ABP3DE7Df+se3Q", + "Nb5vMx6VgHxjel4Htl/A+a9rft+04sa58XWtnyhoTGzr2lsLQaa8zdA/0fkyVp78+ifoONs9rdliqdfw", + "4hRbbSKH5Rs7L8XW1eG/5D6VAT9WEIsghpwlfMnX8EM3GhAegbYOoDfkJqryyLGOF5CB3+EG2LxxM/Us", + "Hfv7T46PO/baOVhvYmvBoXsxt0VJ1067lnDhPY1HgWdIuc2NXs2tCbCfo+7CXodqKcAip42bU+8uy++V", + "oLtWmN9zC2yK88ktuB2C81xfP64IwFClZMKBSzUMzaQvDx24Gwl2rdsxe/0hmdbNR0wOp1CPmHBNFowK", + "sGfnZdygkGQhcxa/zPfw/KOrjnHYOaOqLWEWfvN12KnyQ9r7cH701U09pdwW+Ui5WkKOY+vLXUDGHVsw", + "Jicsz2Xn20FE/BKXGFPVvxfachCCYIfg4cPWYuaKNqpzE/upfQp16+l7E9vWG1RbaYu9ydCG6bBKgBtv", + "QG6OdTTOpEFzNrw/nwnO3d7TvcOfnxyMxqPjJ88PDp//MBqPjvxfL5+4X39vUZM2z6olO1ySMGVwMD4m", + "Mx+WmjXz+b9eMmX//j12QnV220qSj2nMN9T8SryZj4qVlycxkUPAjYd/+xCtQWD8+AXGT0Nc6/X6bS0j", + "9F14Ry2pq8Rp1V+3oxa1Cxw0noPG831qPGuw/HGqOO3bQBbilh6vZSmGxzs83k/+8VpY/jgf713EP5Vm", + "1HXBTtZs/kmFOqHzzhDo9D4CnSpuFe+ugky56b4woCRBmFnQ5dLWTF1jXHxHc/loXJ3AVjrrOShUFi9H", + "qnMFfYeJc9njBqLacLwa4S+zIqyeY9IEF4nfr8xc9+7XVZvrfSEbDxQ/vZsOUz+0Xi8BNQQdKUyjzAXV", + "QcK4LRVVxztc3s+pE9IGoEtQmdvBphevztKClV/9fHhAvnwlzNNV4Atrw3R+Ztc8kbOcLuc8gQ/HMteQ", + "6KBkQe7dfUGXCItT8VVtKtTf9r1AfYtOQIBG7sjxp0vfNHDSAyf9oRx/kHR+lMz0yd06OEV5iCY7MI5J", + "Hp1s+MsiW+fOb5rcPQsVc2K5MetkBguQ2MuW4+o5UpX834xrCsax9P9WuaXo6W3CoERPbNMBagd1w+7+", + "fNY9vOimu2EZPZprdpAIxH7eaQlaOT7nuiDinN+c4QHS5TKD0G/5LhlD0IOgyV8RqhSfCbQ8vyzCLIGl", + "B8NQkPQTzVMAALRRzKQBge6ASWuCUh2Z9yCPE0mk0JRDhFtmQd31fSfotqY/B9ELLlxC84Z5sG94TVeG", + "hdxS5A+TXgHu4++QWwFzUrcFs665EUuYSElSckaTOUBwv/hWOOe24FY/bAcWL9uUwK2K5RIy1UlDRHTO", + "ZzOWb5A6u6ffcTWpf8uLCC3N7rhOyn1FKgGsjz2FTdYDT9dHD1TO/PPNj3DzbARJoPwor+gmHNodZil4", + "R+7unfkirizxSOvE41PXgUXfb6tC7JPkDQxoQWkKrOfFiEokSu+VWz9fOZZhQg41WdCV4ypKVuJ8RTgs", + "/oKt7hAMTsWemQGLxVhlWViPjCvMaqCl06GtsKoM0koohfbi4MUuhnTCKJotljKn+YoomRXallsDopFr", + "ci71nMCqqUjJT2Zq68ho6KJasgQfqEzZjInJbdSM+993ALcdnNjAsQwcy2fDsXQmq9Dhsj3luwlB/6Wt", + "BIADI9RrAF0OqkcBSmFIi1WTGN88jrx1jT1iy/2pVJ8G1PM4u3SQ0lL0ACbpHgns8pEiCPWYPOt52SiP", + "0JLiv1fa2+5z6dRdI2FGXH/eQBM2azjOsnsqviJvbCM8sje7QWNX/ckqtnK2sAK5Gxeh5ZwayiWFK4Al", + "sCANOijIKZnlVOiGZwc2xsoqsA68uCXLEyY0nXUuxXe2bYmBM5ojAb355GuPAPvZChFrhnz+6tnjJy/f", + "kC+/+iply5wlhmf/6qt7u0QxVp0R2h89ebn/5PnJmg7B+QQ4yPYdjUc462g8qlyrERpq3f1PpQNwzDLT", + "BCEdQ2BRj/ojnMysCt/E2BEu92SgysNRuCb4BT//HnkUaySSzTOTl3JIPS35+7ehVDd3mwaV+si3Yl1p", + "G/SdTC213PN3bHepz/ZuRph3G63rcN/NPNPM57+W+DTsSzey1QDMDvaZwT4z2GcG+8xgnxnsMx+ntuM2", + "BH/v7zSYJ/qaJ27Ch7x/i0QXDzNYIQYrxGCFGKwQA13+LOhypxJ+I7JV867sKzzX1DKD5DxIzoPk/KlI", + "zoPkOVC490ThIgknBrHzNsXOLl38HQmd/Wj/IHF+hhLngGE/Ewx76wKEi6/aVIBw2QkHAWIQIAYBYhAg", + "BgFiIG9rkl4NAsQdCBBRB5w7FiAc7R8kiEGCGFDsJ4Zib0+CuIuUgZECbCXS7JO+5BNLIojV94YcgneV", + "Q7BYsJwnkdeFH0jOljlT5noIFYTm51yDqXmZs4QrA6q49kmVCJyebn3/GxqHT08n+Ne976Mo/8VeoecP", + "zP+ROf8T5TqZsh9yKvSTPJd5POACuxEa9gMrNsYbYJWFMlwmwAk04+lZ7n2mC+HGYOlZknF0l6eQif4s", + "ZYIDGiuEj8E5c6/izD5GNyY4H4zGI8XyS5afwQrMjq19nmers0LQS8oRZ8de6xFNLuiMHeU8Ya+5nu/L", + "xYJrsKPG3ik0JkvTGjkQtWQiJUnZK6J6WDho7BksZEEknsoM55ZTIoV5erCgsKj4Hs6GAWPmNe3d6vQu", + "4b6h5hlfcI3CPh4D1WQhFSY7w12HK3tmXzctV8jF3a4Q76W+xozR9kXikoJF/lFQobleHbHc3v9trdSN", + "bPFb4yr/FfnekbRsjgTZ57kzgBK+RDfC7z0psD2C6AnEUNsRXZkXcFCwg2iNjOp35xCEaA6mQoecMlvj", + "knKvRpvxSyaIKwJzVw/sR3lFFkUyJ4KxVNmYznAZbgGN4ipId5PVJoUosIfBvZGlHE5JyqdTBtR8msuF", + "TSEI/05lUpiz/EJBJBpxs0eXlhYsJry+dvLqEu8F+POC3XIivjq+FVJH3cxAVEiZphxzeGp6YZgKLQlN", + "EgAOx46nRds1xEon23Cs3rcSBGY176T86MMogZvogNsWgKm9OLwi/+Q6XtcJyxfrXljQxgbzoSirWb5A", + "1tdduRSE+vjIlteFlxLBN1j6yXx0p5HMpWLCjw7z9bqmzUG0F19bw0h1cbdlWZ7lbYHVg/JffuNSoPxY", + "Od5eW1+TgRKuDPGQ1UCEKD0t2Jm5td44HQ96DXwdCqVpjH9utlkPXzlLGMeqlU48/CAg9vFfJrfH3u8u", + "19yhNXqt+qC85s2vi72LIKMItgxW0w0nE1h8iXnXC0fUXRgNIqJPxan4+v7/MljCN2QpoYp8fb8q4EWD", + "3Cuh7OPR9dZMbjmeaXc043penE8SudiWSyZAUcll+ff28mK2vZApqs2gsx0Rf5yElAV2y2U0rTCGU6N0", + "QYnSNNfgSWyYV0Nlm8/HcAeRx4rj4ACu480pexPWZeuc4VLrMz646Yy1RwCbhlVEX0JGI8UGza/K1QW0", + "jtyZoZIGFlVx7tvGpLiMz8RmRcD2fJeIwtF9M+hmymdFjiDtuJxlRgU8i3OeZVzM9mnKRNJaeQ4UscS2", + "JQk2bm6LFAod37nCGU7FgX2Yc3lF5FQz4QUoRWjOYEyW2o6Hxy++/eb+DkmD5S6onpyKJ3jNapecjo52", + "np2OyJcLKfQ8W90bm58ewk9/FDTXLHc/7vxqfqRCFDTLVjX199HOswpk2CkD+ehxdbsxIP2Urc23IlJY", + "Df3o1fHBKC4tYxfU5DjREYAvLIdnV/I52cDDpbdGvaRN9sCbA4hTaOzcf/CIJHOa00SzXNVCOszXcF3l", + "PJFVsemUJZpfsqdRnG5z2duEI3zBymM2d0bOWSIXTBE/zIQADy2kdmw+S8dlewhnSXM6vaP860/cOiwZ", + "SmOVKcNtn8jNN80VEZJkUsxYvsnOfVNQXk+54Jplq7s+CEMb245h0zoDoWXqbu2Gbfs6PIjt44KtYhtR", + "bMG3+u3mnUOiAuz1E1t9hi4aPxYLKrbMvYAVGYyHjRnJY6avGBNkBx7Pg6+/acdTHcbCA66WGUULZewo", + "l3OqWIt1Cl4bNCCG4c95Ykh2bqgEzTJ5pcD0NjM/Umj8hSI56AdpnioiL1mOj54aXBVyM4aRm+VMKaYg", + "yg8nUVdcJ3Mik6TIFZEiWxGKyl7z8kBicGwSctpjwoQqyoBASgyrAznAgrms7Ir1agxS4SLJihSq+OYz", + "plBFV2rscDGgg+1fWN3wp0dzKGPSYpk/8qcZM84vc/kSfCb2gafcQOtV61jhHf4aMWFt/gi0RqAZ7ZrZ", + "zEWd4SYbNHV0YLnSZS63cnTlaPK63exp8IqPWkaBerZMu2K7sLS+27YM5HG1e5VxSnKWcn2m50ycWSCI", + "MlLlGsiizkqdikPQY7B84XltyFVmARF9RMmMCWZOVDloU/BqcQXKv+51HP0Wiax5txzG65JzdslloWrv", + "Abh+5+0y5bnSQDZFSz407lebhnObh7eLz2+jid0ZpLB1pyUhz2VwJpVmsVOZnIoTG62rA/HIjAj2qUQu", + "FlLUryyEtuPqJ1cEvtjAedg8VawZ3mL+qdaFs5e3LxfLwuzLZ5gD1FXjo5w+wDASatccOzBx5L8MJ1Th", + "Ic03il3/q/qFnBb37z9MTJcr+zcJ+DDomCdzfslSsk24aI5yIsMxTAez97Qw8mJ82GDecJg1pfkL9Xn4", + "4UFmRp5iVZ48l3mHQ1rZEg3r/YnIL9U5gIOocR1tW/ilPmmExlyyXHmZySLJnTp4/4KNKrBNDkWSw5Ni", + "aZODD67GWoXjKnq3UruKtY4a4MPjfIlaHB8vgEG89EN6wbuhffFYwPM8kTtt00ftpWlM1jSowH+2Aue5", + "1ZRSpWTCbU4Fy8ohl4ToMU23pIjoqtxMPfVU0DzK1G6ZS4RddEYp4ADjzyXKYghR+ODqGcMslOxw9NFc", + "sFWIYCzL7bkMfBxeJeLdgNDwUOSJaT6pZLftNZDtSitWg0CspNfOb6OvkxuUdAunSkCV4xeZVrXCwE2C", + "0kMjg5T4bWF/ZV2TUIxBs1JSemsG/jilC4o9SBxgFHOs+yDyckM+HhiBj4MR6BlTgJSo/pw3JZoYSxA1", + "lgEpxFeDwWdoU4EOLhduC4E8bCncbIdrKqq4wLw+sYqVd+KsX5LX6IIGvDngzd54M2I+DR+kexGd73Az", + "//r422x62DfYb8QlZzRAJuYfUfddt7RPwMu+lAEG9/q7cq/3Z/ySLTPqgtFi4WeWJUD4IgYIkN6Bt0bc", + "x2LAqwNe3QyvtoFoG0PjwdIyMGvBcvBK+SS9Uj5Sz46P0SNisCUPtuTBljzYkgdb8mBL/kxsyTWW0WJC", + "FIO7bE/2rbYxlZtL57cvi38iYvgggd+pBN4hJL8fEh6JMPoYeVsvPcTlJ0fbHPp3CoJQGvm1RRppYw4P", + "AoFlYLX/3qy2eVf75lnF4S98dlXpsReefWlHDxMFvvRDrjMoISGyKw/gulxzG/J5yYBtTqLqFfsJgs7Z", + "NU2031ONAqUd6Ovw4AMkaoo+Tr8kW0PjVt5fw1YZevxEZ7ctJj3dcapMxtp7PBTLQve/TMeiASsrK3yC", + "dWELllu99c/jjM0u2g/1dtXig/7xU9Q/fpzc0EDZByXaoEQblGiDEm1Qot1UibapzuzYB3V0xWdQD/w+", + "8UpOp5i1znCU5g8bKjEaj3wQRKuW7Dg4mn2DbCPkBH+v4jwfExIXWm6ZGXsNyNdzZOZyuJipxuW6zEdz", + "eslC5mxPJHOsIt88WwdoFNq4t1kBGYLZ7iBXA0a6IK4/Z0QY9ifjfxqgTBKZpwGvX+f27M+C0ZwpTXJm", + "NayMnLOpzFmYIIMcQiZgP+u4+jqqd1HdgVtaoSJupe+WaKOTWwvz17iXF4LX5O45LZ+i0jNaLmyB2TQm", + "jbvtTosbJsKt7KV+P6WvDXSxpRyjW17ahCD9Y7dq8mdLNkYzee5aGmBL8N1qObkrQtiT0DUOHACdi1lP", + "Fybgl7R072Pe4L8MFY29l0ozeBc4hFXaAwVzDGhVr1RjdhsZZ/jC/NX7EEPYOcG+kROEDy3yJl7muHQl", + "t7drMR4kqcM4tsmpeCrzkHUOjwEPhiYJW5pHAYEsiqQMMlLaGL/KsVWWM2lq53E3FqxbiVtIZlo8jvD3", + "gcx8eDJT3atvfZeUxek02jzhDw98TjTbckKObPYkxn12d8AaOTk8mJAfqSKQeQtPBYVFbPIBdKZu1T+1", + "6fUCfNdzh+tF9IF8D+R7IN93Sb6dJoAvFizlmEvnroh6qEg2AqybskmTPSkOQzWt2zZ8i1FpmWuancgL", + "JmKW10QKVSxYTpbQjmjTEEqS2wAtmZNUMiW+0ESesxVx64G9uuAuUpLvU3HM2C6Za71Uu9vbQU5DpeUy", + "47O55nJbLVmic5ptc6UKprZ3HvzjUYQLyOQVS58xzfLjrJh11I4fEz61CSBT1EAAnLmsTMQWfXGEzo5c", + "oRe/jWDv6gz8Eswxe/1dSxLOXhXHfnv5dP/hw4ff/f6lOxItZaYmnOnpROaz7bleZNv5NDGN7lm9vrZ8", + "ApBVV0ueC/LqZP+Okyez6yVC219tbYP6KNhYfQbbjhljP/pKO2t3pQpEA7t/BStxXMjWTjzlZhRRoNfP", + "BYNECvC+cqaL3Lw2amMhLStRTiQXZ4hUzg73xMHDo+Xr1w/2HrzOv1189z/TP9mP2Q///vZ6sf/vqx8m", + "q6//eHS8tff6j6fFN3/8z5Q+/fP+n//649GTPx98+1KJ1S9X/5xO//31H9fPLuX6fdeQpjuEqAiTM5+K", + "9ynlGUuPcnmesUXoW9aPlLwS7NogteYQTZr8QoBhZGGY9iAVMCag507ritWr5oymLCdTzrJUEWbkOmqr", + "DUBNJEtjmNJlLhcsVjGJkoOcJyxIm9vmjlbmPkbt5DSj2ub7PxWw/uku4eKMppegEpY5/CvPGc1rxTlc", + "G6iq4ZrEFZdm/BPO8mgcLlSl0Jzlk1Ox50osQIkK+OLvBJPzWirFBWE0mWO/ZshVRjVM2v+en/oucV6r", + "PKhgRS6Vu11Em0XwaaRv7BILwTdd9ivfJb5sM+RNl/0q0je67OWJvL1CHK+W5g1QkVqznJecuSpjvBzB", + "t5UgECD8npA9LbJs7H8D/LZkYouJ1AoKbpcwnxu5GZXl4SK8nzjSaVjsagqTBk8ZmNPO2ZxechkBZm+x", + "C9Lm4EXFq6YFg3JFbG/LwkaMcU+gQdArXjJtIyHGH0XECFczNcbqaGhJ5lSklVXBBmpGJuS+VYtpMWrs", + "cYdpd9R5j05wqzkhV2eoeEbDquE2WxfqS6pUjyGONtEmHl0DfAly/lBvQkfErqm6iCBGIIbNAZFIOiNb", + "3ccYbOm2a8CJFVzobx5FIyxVATWZmhMd44fOmaAzS3tPhox9f49mA1/LXMIC+83QlTcEEMyCWXuPvYJ6", + "upDbVL41+KDE7cTdEB5IvNpcCefeyzJClL3XRiX7vvP4wBxy8OQWlp5QMmVUFzlwDIZPsdUaUm4GXnBh", + "JE4z04Iul1aWN6j1bMrYOjdQQz6fMkDAis7YGSiZ13V6ZZo+hpZv/StYQdnCXTyLt+ORFKwHNquvY12J", + "g9gSui7gMaLZJ+WJNq8k+FjmnkcPGOwdXkjz3b83BykLBZOwpIVDeY6c3LxKhTuxjY8KPQ0KhQw2wrR1", + "JPKNQ3v9qXiKG8GO0pYC824PLDLHmFB4Jivo4pQWju13D2rdo3CHtAa2IjAD2l2Wr38az7BZta/SVPNk", + "XddjaBX2vK3HFVlU33cWW1S/npFT7HypDgNEMCbIB1PGIqiTGmkGdR8uD4LBktSaeoC5YZHiHH08VevG", + "JOdt6cHtVGAy8yLLCNdkwahQ5g9u14XEy86/STjIJ+ssal6fEVY2yDN44LvEpSw3ZPP4yVOZR2DDKlvK", + "AjR+CEQ4voAlSOXZKsj5AXoBlMq4IopVahAGCzWspgfrE4uj+m85hmrjm69xAnXwiy3fUomf2Mrv4e14", + "VP4ah3XHYehaqUa7AEDthbr1aCJLCchFPKpoCH36mzlI31Cv9JrreaigW1OjtRWLj0M+K+C2zUuY5qwa", + "5ldWuBzt3L8PKulARRjq7fxODbKKJfwrJWweYvvy6jS93tRX+cR3iZ+GptfWEtd6JIWwnJbV9TR6BCcV", + "OpA2G/p8wqqqIDrxLftXUHXYM5T4vbjzezWqzbQjeoP65pUAt6bbaquCqoPVim4oxuS64mKW1eyWOrg6", + "llP9M19wvb7o/+GUKNf6vwzIOZOyWT7kkSoUq9woA7X6tMGQG5JwPaeF0gYq5lTtoc4BlIY0u6IrRc4Z", + "MXNU/ITlVGNh4qgGDCyae1PN8pdMsciR/SoLWCbWtAZRldBCy4XhTsGcRDMpZoqnDdEDYde+WqISJmjO", + "JblyZUHREIO+YdaW75y2UdlZFsI19NSbR+csN2KJXZJXmqJVs305ge+GH8rWOz4VJ3OqwwHn9JIRrr9Q", + "JJdZBm473hHLWdFRDqLkiq5sYIY5R9Tg5+Y0y3AxPArnkQ4zoEkKfpc5n3FDeOxuq1udnIpnFGOfyiNT", + "RTIvjwBO1DDBZt3obc/IqcWSp6MxOTVk4aXdyZ7/2VCUU0NB6p+cBYfi2cKh0UWNm3aFAn1+8vtBHRzB", + "NaeZXaCvnFytKdiEv6Ocy9xnZmvLpn4QaG9wgqXtVxbFtQgRPk/qCrFvR74auKGaX1dzrPs9mLW5HcDV", + "4q26yT5sFrZQJwEeZvkle3HJcjpjezp4zGuwE5BBhELsbN6aGw/spbBp8FXCMaAxIgKwXZkj0ZLcryqs", + "cQA/qBsnioTqKhUn8cfUxzBxW7FISIghNMsvqS+QGsPpEM9ozkW1uS82CPOaIEPQihG7rnfWBDVl/w1U", + "Z6jz6KZhSYsxxxzgP49fPCdLmkMGxRo3EQ5KIIIFc9AbuTtTsrSzg0CUzFlyYU41xMIUyRaYwrTlTKZF", + "BnDtMCsoD7hgW7Mc7WC2U+kLK8M3MCbckBhbSoELspJFTuSV8Gnwf6S+zmyYv7/UXv9FTvEV482q09Eu", + "+e3UFjk9Hf1O3oYA8D/qA0dsdikkrc6rbwVkCwpd4BiofGPl2MzXLfSRjqmJkPn3PtTQ/I7UQp9rJPAd", + "KndUTAY5FU/blDtWhxNV8gw6m0FnM+hsPladTRObd7nY3I7KpnrwgzplrToltAV/aI1KHVDiznchnKBU", + "UGMF1tkG05Wgi3Yj3QF+9trGfblYcA2mTUPuMyD2mykpDS5zZexbyvnD55Y5Ne+yR57A15auheB6rdNb", + "vdu7GiPblbXjnm54zRWtebLtZ7Cua9d1r+vbdW1xC6gzVYYC5TJnCXi3RP3RfBfnBYWqQ1HKnZAWQNgQ", + "u7re2sbmdXnLuIEMBdj7Nfjh8PgFJLw5CCDCBR+0xPztBR7qNubPiEHU6hzz+mbqXtEbO/X4AmI4V0uc", + "XbnF3sSrelOHboAO/1CbuN+TZzfphPzIipwrp79c0KUih8cvIF0R11KAqGgQsotLhdgRI9iiysm19fFo", + "XuflFlW7s782XaKRYV0SpbK4TlS06SQE/pzHDkKqK+vxJjBqpzXl2Ht+DAPgvwvgR2G1DWR6wMZhuBux", + "srsJ5ISjL7/fPT1N/xP+MzF/3fv+13vfR359Fv31dfTXA/j1JPLlxw3GPr73/b3vY1GyN7qPJ4Z/a94J", + "NqokQgvgDzix9mOFMTdHHkHIw5uUrt6MyZsrxi7MfyHX2puxQWhvVozmb0LWE4nN6ydPfhqNR89ePD/5", + "cTQe/fpk72VUD1tb8y8PbgU7DI/7I6Zqa4lLHGUs5CWDGN3jOZ9qx/RHFFI5SxrpfYkynVBXQ+1PYHUw", + "o1YkJ8GuITVzzi5bAFYxHeiQQLpppWtg56E5xVDMZvSCq9Xc6TxNzcJ5MnfaAaYhmFbZaNqxkzPhaoS8", + "wtwL2DDxhVtdnHEBGt9qegavfdd5IRIXagVmDy4KzUhaQNDzXF6ROVda5gY80CZCQF3CFTE/33oqhZpJ", + "Khbp77ONXdkYj1YrlAR1FUScjaFFzlNn5gyUfl+oMselCzw5FVtkrZnLtQoMXEEzN/UkarzKmaZctCXd", + "aNklCsouqxiiFQBrG/cj89KwVql3vmdTZjS2tWbEyA5be3TNGzmCt5FXf0xFei6v95bLSLAEfiN0uXSF", + "tApfQ4spMG+/WDIBDh1OM6NAKw3VKJdLV1yrdCAQKz234bfs2nAfNLO2H2U2WzjnUEWnzCpnzXyn4pLl", + "fLpqmbJpNhsKIX/wQsgfp4WGx01jvbTu7znu2tH1g9g+Mq70RkkpntH8gmlIovyz7RvnXhZlQ2JnQa8Z", + "iN+DIniQQti+b2cvbJYpH4wIt2lEUD7hY8/MVculzREZKU3vE0Rqi6gTKQRyddF7bNeT0+XyC4Xacq6I", + "JRkhu6fwp7iPyCdfEDuWJd7eYFtlafdy/ZWO2/1MSvJ82/nPh0zanzm+uJMnG89duw58963lfW+5PLCX", + "G+c0XUOyt1wS0zSiakBOtWcippK7jdO6kpqpgNkFQgfgcs7ASRWyakXQYluxDTPI4UEsTxW3bqvOmXiW", + "yXN4ZygNOWCBVdgqs++pVDsseWNAAvBrg51g6JPe5tAoHKHB+pXwTiHvJaHKiU96Yh6KrcWRrUiBOQvK", + "PAFhZhUryFNw9pOQn86IqJmkIC36HMtkQbnQTFCRQEovnswRNDJ+wbKVzSfFLjGdHbq1Krlghqunq2gW", + "lmOZayiZFr8uCdXUvPomvLW94/3ReHTw5Hg/SqePdc6XbO/o8Ce2atHEmAmwGdk7OoSEbty0nJyKVzbu", + "lRZ6bvjrxDvy60qn5mNXLMmZxnkjGbPqoehh6ygY4TZisu5egArsigx0RzwQK8JlF6dhkEP3kw14+IQu", + "6TnPOO78twaCxCWB8wLNkgKDijW9hgRrAXV2qc0n1q0AD2vJzny3M02vHZOyO9p3P5uxS5jyrc2vb8ct", + "y/F51MsSI3Ct5glYh/36MmyXM9+jXMqhrYuwH3zybtvwqfzSuiQbYKRIIrOMJVoRWWilqQA1VM4umSgs", + "8NkebiWBTsrlKVowPZdp8yhx6DM3V3Ca+IUclV/cgeIX/yHGk9sz9b6trqrFShaQ4NEO7rcY7ALqQiAA", + "P4NFGyAamQZn0jy7B6Mx/osu+Zkts2PXjANUcTM6LWT8kmHiFVusgaoLlrrXOFIXZ6bF2VfB/+h5MmqO", + "7EQXIKAr+AEeYgKOh4fmndAk0Wc7Dx4++vqbf3z7XWM1FVGh/dG9HfRAgx5o0AN9fHqgEpXUz/xn+2UM", + "KnIXT2fH5FCZJy0SL8lO2hP1hemiKpgqXs/UtHCsivM5VnODb8tksd+ChAZ6hoc1uFubJXEQZT8P1VeD", + "VnVwvhRb2XTba0Gkt4juaXwZOgJkcdCprdGpNa8vwEU1PNEpMQzqtwFnbYazaqLrOmm54je4pEpdyTwd", + "vR+ksalWD8bZn7PkQhb6mCnFpYhnK7R7rLWd2OfnF8Z0sexQPKzXH9ppYurDQHBXldFA7kgKdXZd+V9M", + "EnoXFaTXOazVQJZqh0EBWSX/9WvreE4+ygtpcMtgNqrYiuMoMq8ZOK4caJtmQ6Vp+TJvpDONnFHHw62+", + "psfRogxtL4o8tqXca4q6T+6K6rrDG58f+l2/yJE1ONRs8aHx04AUBqRwU6SAdT0snW4FZH+etryHsnT9", + "VNTqdKQyURNcBhTroEu+7TrbNP7btrPatmuKp0CwDq+x+6gmtnZZNnEa/mct+BcnvZWV/h+2DoH9+Qx/", + "3arWlI0Vd2pXSu673Dj6TleIs9yuHynvXYrrLqCmZac8jevM1mmj7nJNgfzZ1FxlMqFZlB4bsXZyKgjZ", + "/uordLA8fHLylGRUzAo6Y0RTH/uKgzTO2/CUKLVA8o073SNuI3L26Mn+Ks9iQjQkWnr18ue7XBou4KzI", + "s5uTlRKmVRUhRtF+EdtseYvNUnXm51cvfzZYLGdor60+IC2tQRjy/UIKLCN6gJb/VOg547mzR0NOFsiU", + "MumnaWmcwLiBgSs6lFAlU16uh2TcfjvhOQnjzDtjxg0XUgq1dRrRkis/LRIXHd7nVWt6bf7/lmmtKvhR", + "Xyfp2c59/F+VsYFPp6fpX99WeJcTO+vaY0/aSgHgbl+z87mUF08uo+mFLEW+wkaQlE63+kO3JNozfXxa", + "Nu2UhBWNBBf64YNoHq00KpGX46ZRNx7pSgjVD0O2l9Xhnetv4bm6cX1Zrbs111XbfI4R7vGkLDvWfDQj", + "e3xrLz/0c+m8/9w2jDpOHX6K5ag2qv356e1mwZSyYTeNb0YiUEuasM9hqxElo9vb2AJn9BmUxcbWRfzv", + "+XSdkF08bsulLjWm1jk/L7Bs8Ipwrawh0E5osyixa658BclEioQtIbQPArO4mIUdIFW/U90bCQTrKFKR", + "kiuZXxCqCBRKyHkyB2nRydVu2RdsBd5fjk17Thds7JXnY8J0Up/P5mQDY85KFvBbzsApSMzsVgFfWXcR", + "n3DNjAiBmIcH5LzQ5IoKjYGHuQuEc8uyOVfnEe26zP3ybB3phVQa9AgJVUyNsZy0uxRz/5c0YzgVLTke", + "Q5j/3//r//7//p//k5ydHfh7PjvbJeV2FVlQQWcwOwSTcVsf4ZyZzRrwoNBtjAuoOiWFh9wEAS6UZjTt", + "9vT6ukVACjw1bLOH0WblrRpRzzFzz1Hdvt5dDJ2QfKE9IC2hxWZenKulRH8adKWJc7SgVPrnsxdZotVP", + "v3zbdK75euv+g8/cucY6c2I47xPRK6MIZi5LS3YdhnCBebXHHIvSxEO9vwv/b5Ni18FajzXNdd/VYv3b", + "G69352br/Wwcl8L32vQVquHDNDAIdh9u/eU3DKDv6qsUnfWDlAptyXSHSx/Xj7BjK0ZW5li3a7V0+awr", + "RAxou5eQG2XbPdpMz7d4urXz4OFaA7i3Xx+FaK/u0ebt1J3H34adW+6+5H/iCon1T7+p+e4GjwZNWAuV", + "n52jSZtzCRDaizYPETzMV0vF8tvlUlluYBoYndXHyiB1szR3xbA0OZGBmt8dNf9YqOBASz5XWlLDwx2o", + "tsNpLvwKqFUQdk0TbZYYfBBKQ92Kpn4M0mc8zWVLKieXy7ryCuNe4e9sS8O1nMjulQTY667WkfGZcGnt", + "e/re+i4Rj0D3jSSNWsQuZyukdYaUOpjffYOZg04Rv18Gl3bBVluYi2dJeW4JJkvJ+QrB2aah3/dJfRYy", + "xQof5yugyZMOjqOyAp/JtS3jjLlKYa4h43+y1KVMt/ldnHkpgN13u9u2NT+uzBsDgpskfA/Qg2+qsJoD", + "pNiZyysip5qJgAkBRoWDK1yhzGAusWKYlG0BlvEneAxql5yOjnaenY7Il5AxLVvdG5ufHsJPfxQ01yx3", + "P+78an6kAiu01BSgRzvPWhI3rju4jhz1n76CJFn1f3/7tsd+s+j2q+ODUYywuEnAThaF+VPx2pYNytkl", + "xwgTcz6M0DQliyLTvBzFprwPk6K5Ra0zHJzMq/Rt7ft7L8aBIQRsCAFbHwI2eO3fXqb+jIr+x3iUUfGS", + "TZnNDxpPz59REccmKMVirf9NU+0f1TpW0O1fIwYJCjxHj/bves3/t/FqAnIrx1xtcR6tStE7YPWoZSQM", + "jtA2E6ALG+i3bUtzj6vdq7QmyVnK9ZmeM+GizUfxxA5uEHACaKE+WyQy3q79UZUVuZeGPMlCeU7IpevL", + "wbkzMxwkxBRCSj+HrBeUi6CYHoY8whRpOLcU2WoX7ZEbTTxjguXoTyhSt4wJeS7LyP1qs9glh+JyUHHB", + "jAi2vkQuFlLUj7MLMo6rTW8S4RcKe62hflZnEoT71cl5I57ibxk8F0i+QfxcUvEAc2xUpD5FVcxpPO51", + "kvxemsa4gr2q3E7TdEuKMckZ5ALFDA8iyZlmXqbHCvqurdWjQkLQxsV/NKL/WgvKB1IFrF9X/NqOaK45", + "aNSWcgkZRFJ3H+WZR0q1rnW0xEHeX+RBnNVyoHZincN6aibMWR2GXTtiwcx1hsVnyo23coWVkT+W8lJt", + "q20pN3XJ8jLkoK2eqDkk29Adzx4Cl03fbGuWqSBHgVX2hXVD25b2i11D080xhlWxas+l71OBjTBqA15K", + "BAsOyUkGyXSQTAfJtJdk+kdBwRIcp5Pua41okD0sNw7FaYjiYpYFVAYbqQrQ7MSrRP/LzR7zAHeTx5DB", + "U5lb3LyUXKAnJV9gTJZftEEJ5jyzSwjdaqAC9Lv7er3xsg06/1WuMBaSYsuoqfjZhoU16ySZa7aAbn2F", + "FSAGrm4bxsPEl/zSz1oumeY5BU1myM72iFF5r0rMVqkvXHM80SRfsIwL1l6owXytgzhWYrDVjFH4RbFW", + "ydyJvokUmotCFlVg/63K+ldcPANQK1nwssWDSovyce68HbcN+mDtoA9bBr3fPujD1nX8flPoPLEHfcxm", + "aMdrv1PXNAKigyRNLd/3R4h8/ggQaXl4tfccoqRe4jOGjfYUop1f+rlMVxFZOC7XnfgXV3q2f9Ri3Lq7", + "7MOgD0l6BqbqQzFVmi82SusX4oQT7NtShRc+uj35RFUTsuciSh2CkLlFwWNCiWBXhAmdrzBTxDnzAYM2", + "OMahs0qxXbuQeIKhKi7E9F2IfnohPc9FRdBeWd4etYARNBhBfVBDh6UVTkWzxWEbZ3h4ENUsE6C7Qa7E", + "cjXVdD6ePn/qQWytDjH2RJvHY84uwjXkwZ1uViy7BdorxY0bvHUDMv38405o6AWfdT6qJ3VuieAd3NNu", + "B317WoOGARQYurD1OplyvbawwhX6NfeCobX5Buuoesg8ODA1A1Pzvpia7gccOs+2OcKmTFOeKRt2y9Ky", + "LoJz8K/a9Zvv2Xw3QKeeFUrDwH3cul/bGoc0y8hjO4LlWwxsOqqqyKJQmoAf8OS03BJZMGrLkUIR9y8U", + "eVyxCwf9AKLOJdQFcInthS9k2Fas0AdKwJwstcOX9d97Ospg+zjUtBwxgVzQc6pc1c4Yi6dwc863AlD8", + "ZD1QPKbpS0zM8iTPZd6e1yGoPWIrjMocodSmbkuYUrHCI0ouGNZYBAaUg7UlYRx1q1BWhCQZN/tmZgnk", + "SzaZTcZkQTNDdVnqB1Qroen1mHBxSTNe/m5TFpBpTs1LgCrFKUvY0pyBb5XLQnMxuzchv9CcUx+BDvt+", + "cq2ZgGQ9RC1Zwqc8gbXXnYvqpMs8lh5RKOx6mVGBsBaOD9y4TFxJZ1/AFivBVLmTk+Boz2W6QoiG4/vn", + "8YvnQWmQBgZmfnc3Q3W1I+qmcOUR1bbq94Xm5AWFmjLWfWISWrNjJ/rq5SHJnW+bBSUnYyDc+dl6HmiR", + "i117oLuQHGi7jBHZgrQ6OyHnV+S8Oxd48738eHJy5Dx+wKO49Gyy/v0y5zMu3MNCCt0bJB7dv1/NiLPz", + "DRJtJIJff/ddQBKhcYwC6ix63pSoucx1I45JFYsF1BCaNq60eryPaUosaunOPegc5ei5LPTueUbFRdNB", + "zkBMIoWmXChCARpiMNC+nOro3bcaz16IRzV2rz4A13Ws8/6cilglY/y9pg4wy5aC9XT3jEyzrhA9xlvF", + "Ov4eXbejCY9luopy/vAVcRIwayFdSmCISAIoJHU3w0dryGdlAedsKnObc9GvpeqNX+0BTDW7vuHSnlwv", + "qUhZG4U3DJ5BCFH3zjKHWmSpJ02lTskkQmtDTpsxxPac7Z7WQqoU04wnfZgBR4sSWWQpsdFJPutbWXYs", + "sUM2OcnKQWiaz5guhZNTMZDpgUwPZHog0++PTLdYLfdt3qzbItM4zQ3ItO1YJ9NPUq7XxB+zlGtb/zBC", + "ijExcRnfWh3oMdXJ3El4GD6xWFCRKngICyo4ONZCPbtCQPxAPczSvLILtrIBk0YGfLO9nFPF1PZf8N+f", + "2OrtGyO3RX7fBjXA9l/mP9DuRo4u5pBeOD0M1mS6PsRBdoI35zX/d6IacloOHYSo2vgINQc6CoGFoDNn", + "6QTHqQW+GKKaZfLK6/OQ+ivA3vSCEQaGAkI1SfkUMLHGJJqTCHdQufp1D6R6hvGanl7di7L9kuVWipci", + "6vyTcvPPBRdUY1Dygi6X7uTT9IxDAvv4mZv11FTUkO8ezHZnAEAbdD2C9uaAFvKSbTTxS+hi57b9N5oe", + "B3ArUDpnOplvNsQxdnJjFMJVdj1jgB/6jfLKdwOsUmY2cTlV5NL82A/ztd3POtTXcbybdvX3erM5b9a3", + "chWbdq7fwNpHWeP6Gs8SGpCSufSIo0IhoFWEeQZVG/UToVtNH+RbXVfJSzgUW0NFjXnW7ttJWs0N2y9V", + "sW4wYN5Jfo24haEr18bmJoYhA8eQgWPIwDFk4BgycAxxTkOc0xDn9F4zcIA6Io4e8FsbZthYRQHyQmlA", + "aOokhmwgQzaQIRvIkA1kyAZya9lAPIJfp26IF9KEMKREFzQDswfkAbG3GXYekyt0vmeYR3nGtCp/W5El", + "XWE1jcngaN1nHTcRQN2KvAP+qXht3olhW8bVT5gJWwpcAFkWeTK3ZWZj8mAb4/OZy4ODKHKXokjKVSIL", + "oTcgOwe+S5za+CE9zbcG/2hQSjDaeDRlVBc5a60db79/AUWLyJd86hwG7t1W+pbPVlbjIskKq8fenL2A", + "CCA3QvPaEcjOmUJiQxPw0uWKzCgXLCWXnDaIlbWzxNP2QFqg8nDtS3Du2VgNqjKSD4giCRXkPOiNdZ7n", + "1OBa7zKyeypOxc6EHE4JJU8RqgAdKyUTDmygVxfXp4LxDC/oZ3BKXDuQGXmHHGq3FCrI4UE59xiD81ye", + "7lpiH7eYL+0fCkZJrAtfkkulXBd1z8z0IJyJ/MRW4UyYg4JikAP8rtxrhIRBmnyJxJbInHCBf98L10TL", + "XZ2KB80TE1JvdGp+cf7UwJPejP6aEUVX5HTU1mZEcjajeZoZ6JJTUOZSApIc4VqxbFqdAeZMZJbJPwrM", + "zrWgF0wRxYRCp3GYbklX6Ddu5jeEGAb0YgCFvB1czE5HE3IoyNKgXQ5uR1wFBvWU5eBtDlKJeQdfKDOU", + "0KVV2kocJOOCbRnB/c7Q1qCauT3VjAGHzSMzXyk6Y4+pYikAb5tmBGBtPdNoKZ95porllxzl5GnOWK1G", + "Al0YajraHe3Yeq1Qof2E5Qtw9Tqjec5oHgShTjOqo2UUvAoDVj8e6bBkbb+zKKvctsQvlWVuI+IMMXjD", + "HUUhUjDhpGPrx1nvGZxQKKI3G4IyiiuomD5pFK7F1Q5CsEv01pB08Tn0kWMPA5ajeoLuSynNQv3HJwJ2", + "ZwB27O7RkpqmwMrKxv0BMpihBSSDYdthMuBV+89td9IyrwPfSsFrrtx6gIkuFGs6V7l1rLuRIzrjwtx0", + "u7+1b+Lr6TZTncRj94FfgzA6VzPU1emh6F++sZY6qpimsxYp3HwhXKTsuh6s2XRyNW2P+Z8tI1mHWSKK", + "xTlynrivJcv9ZsrxW9xopabZPuLhaE4n870+Q2Xgr2MD1x1Ry1ns0QR7cye+FirmVLE2j9QK4IMCy4WT", + "tvh4dsq4IBs2xdul03m8X9nUcmRYe6VFHPXKlzi8G9SVQgyCNQ/YHQl2ZXd1Kg7cN2BM8fJKmoFn6sMb", + "z5nlzJUuj6WPq4BfffBTzzpS4OuerTokWr+SO2FU4/wfuKhApd11QAL6SAh3jpEZzfJLmgURL5XYFuiL", + "AlFOheLOobScscGH4Y3ZjnyxYKmRe7JV9xT1e/x1QxUf1EvDKdbS+eBAHA2HM+6FCTb0dsPj2FiXDOpO", + "Kya5qst4sEYEtzHF71GjXAjNs2AtR3e6lkEZOyhjP4Aytg/B+2yUnZotXB4i1VGIcHO21Gkt66xpVL5R", + "kGfCaescCCE/KQVhNJmTC7YaE1TOgjdklkEUjRoT55+dutCLwHbXwORr+fIKISVoFc6LxKnxppm5F+GS", + "JZg7AmFY5gtHEY+M3Lx3dGgDbVyOEDSfl/1pksgc9mL7TWWWySuM28mY2j0VW2VQiRMTzLKQwr6B9b4p", + "47vA5K/RAsovcT8wgDs/N+DS801q3VDAYrUONC3gWPoNBQ4NdS1uY+ibiEBtsHZjTu62c90PWse70zr+", + "LfVP+FAqWih8NXWUvo6ZPW6Jwz2u8ebapkYWxaJMWQbBnP7PhIqEZcys3mPkYP7yxiKheT2iJW0KJ6vc", + "LK/ThdtZ+0IQcjc5FYc+3PaSWzVa4KVmrTLWKTmIMai4ilBhE+FceT9nzCbdP+S0ueMn5iDfjuvb/u3l", + "0/2HDx9+9/uXc62Xand7W0uZqQlnejqR+Wx7rhfZdj5NTKN71t0ewvsdJBI8Z8IFeXWyf6sc+e/Ru4Od", + "9L4/Jyh6iXAc5igqSXgldDIQH72gya61yyi1SrJew1iPH9O19EYxnUPI9nPZFA1ntuUZtIzC8wm9fszm", + "9JJHY0joNTm3X6FKO7jHmdmcah3saxCEvzJQjQGp9Brd+6z61yoLrREkJ+zafgg8+3hS3Yjpq/BpQnP4", + "u2X9pb0iGpNj308epCbwNoBIjNp5cBq97R/+CCP8ef0MD6f4cHE15gjDAN5cTnnGwuNNmWb5ggvmTSLB", + "cI3B7GHXxhuHmCT/QnnDiRuqzVTiT8MHOByCdXOjcOb9ase6vag7mRt2tkZVYDj97VUjMVqbldXBN3CL", + "gPabrdRWEo+vr/HRG9tSFo0YgYYpKw3dADyAPyDf3Bvf+Q2wKG9wixPT6Q1w645wjCttNRjHzU5Yap0k", + "EPt4a7x2UzNMpuhgsTmLeeUzIfM6+3GXtav8wcSEwliGuhPOcmuedS7YEYNA4BetoUMTKV3KrADSMstp", + "WgAcRDFSOd9rruf7crHgesGswF9n8sqp0KtCLRnUdPCdmhjKGi/2Fs720A+knxcLlvOkNd9RaY3K+IJr", + "j9tFaogPOECDfAbThqDtdCTWKP3WZyC5uxXi+dTXmDHavkhcUrjIjfzx61AUc4/C4ENeQpHBQwBZXBGE", + "nq1zClFmOfFABKLyoSBvsMUb28T2R8zt7FVlVRmu51wQ6nzgPZGwOVFYbiREbYHYzeDnfFMOb1qgY2np", + "gKSqJWxmubxSlcO0vuxmENWm/WW5ir6oU7HnrkoKxxb4E6+YULhVn5j+ve2LcEfmuiwkusQcYZJTlscS", + "dJf5aRq7CWrWuV2cihdQsGUX1CJjOG80aMNuQ8yBv0SwRTzrzAKdyfF0Y0LQq58PD15APHwuaGYdKalY", + "WTj+xDOuN40Sfp/oTJ1JqVgeamMu2KqHUF6TCMa3e1DEJkYwS3XqGbuu662Z3GoQileCFnouc/6nQSyQ", + "xCi02vfDS68Eu15CLvf6EC054206sTlV1hrJhHfhPWcJLRQjXJOMJheQI5anxCzTbDNByTPJGeyaZmX6", + "h3rGtZg6pn2p7brbhtJ1j9jO5MCG/uME5MuXT/fJP769/497BsO8e26yzyTxW99jvY0DCxzUpJEE97TO", + "+XmhAQzMD7/QrDCYrZkH5Le/RgmG7pXfzkBzYZ415uQd7Y5+8R9RrYFyfVNPPiSVG5LKfQ5J5aqkA4oe", + "qAmqPS0aDJts8cVS5sBwL6kheqMZ1/PifJLIxbZcMrEwXCKX5d/by4vZNg4Lq30luD5ynrA16liyk01X", + "gFtl9HE0BxgBG7spjxZwYGaU3vyX3U6U83IHtFa0K8+rt2D3Ho9xkCFvRYb8wND4S5WONldSp5fKKoXQ", + "GGHQD0tjDhBcqSL2zh1Bv7W8SQHfUQ4ejVdO2nU3NJlzYRgmS1oiG4LdVxG5zfx/Zl1rz9AstbY2/JSz", + "LG3zT9Vzbw83zWqUI02lUNvLXG4b2g31T7e1vGBiOwiJ67EEzw/FFgFkdtOzMJLAVBYi9R7K5yvS60Dq", + "fspwOva2ypV2A++hgbYu4IUGJKFLjJWiYkVKNhGBVZGcYUV+ewE2CgdV7tgC8TC7ZDnXK3I6SnJuhJrs", + "dITmsWUO9akqQTxgozhnYJUyo0SKlMQh85mFSi4sZwHXAdybE5pgwDHhU0IvKQfz9qTP/ftXFkkv6/Uo", + "OTO8gAt58g96/eCD49oHd1zrwDHwyZXfs/eKOjMH/VWAIlygyAjIyaY46wMHMS+xMnNVMjcCPxRHsa5l", + "H8A7rDdebMjoXSSvxzR34/8CYTLXuooeorTQ4bD+K6jh0mM3QEsqEYcju8/mc3RgaXNaAccWf+4hDt6I", + "yh0HN9dJ7VxDC6rnTjcR3AxtEME7IXaOaXUDjMajK5oLc3gx89cvkqdo6mV7SVcmdNvItMeGwVbn8srQ", + "8TkVaYZ270sJPjBQJN1H0jQd0uUGOa2Clf7MRXW1LSJV4oMH6AVzzrbhmt6OR1CRSmiLiHpX8nJ9mjP/", + "KK/Iokjm3poCgUXlrDY7Np7Q91jyiuzcv/+/bCEzmmUWX6MXJza81wD9YOFjd5hRkI7fcDypzcd8y+h6", + "Odx0/5s+FMtCx+r2oKpaS5iSUEHKfGS3dn03fqARqHo7HslLluc8jeXjO2J52Zr4hp4y4zRRbx7rSIwt", + "3ni3uyBJirmkKoD3Mms2DsJA8wu7tGhod738MKOqLcoNv8H+zGF5qcHKUGuppr1VP0kvYKpsoEkPq+/W", + "NWxFH7TU25dXx6sZGYALsRuc3BVo3hyrAFiaf7WlkC03dnhgRnGQ+d5ttLXrt2vui0sa1Hbd5a+hHDe5", + "+q5SEeYb1OnuRVEOsPWeewJLJlIYqFfvI2xdxW2NQglwmr1LJXQucF0JgT7r2/B+45zB3/qOXdTHx3zP", + "HpGtu+vqxOsuutJ6LTfIQ8Jdu/AmCm/Xx69FvaWg40Cjn4K+x/nE3tC6U6r0ueVTEuxaO8KlO4J3qQ7C", + "Zcvhy2RILoMroTPKK/xQ6Xta7VuGIWz5zkJe3XLw7a2AgXvjdwkGvTDjAAqfPii85iKVV/GEJHuzWc5m", + "qMa5gnZE8T8rBsNnh89fnTwZjUc/vnj1cjQeHez9OhqPnr14fvJjc1Hj0fWW6bh1SXNBF+aifxs946KA", + "uJAfZZGbEejKjCCFno9+9wtk6WPMz/wjV1rmLTn7rmxbn8x5jq0jwRRFbpqK1uF+yKnQxDULB+olFEH3", + "x0UuDspJjtkMM/80RSC38JvtDrxoNcaEYhiVIrm8QrEQeynDg2B+nxxVnIWiM3TALcdG4dzHuNjYHp7b", + "tLtUpMQHvZQfmUj9OKA4tbBi/bDUgmYZJKegCMkBKMGQLiTHjQpRBEyk/UXQKmwgxKytxVQ/83EDKJrv", + "BVTcSZFzvTo2cyMw7WeySPelvOBsr9DziPHLNCB7R4fkip0bkZsk0Bo2aBrgP12E4u7o7EwxpSpx+nTJ", + "f2IALDDakcw1zU7kBRNdcyZSqGLBcrKE9gSsuhMbTAhTPWY0D/N6zLVe+lnWjm/21HfMt+AAN5WxlAdM", + "PGMa3R8oSWBoQSHeGuCUoIOQmLn0czYKvOxoFgIVAxVZycIgTy5mTGkCymQ1Jn8ULF/hODjmGPOnQyEk", + "r/0HmMt4wqz3p72PvSVN5ow8mNwfjUdFntk97W5vX11dTSh8hUhC21Vt/3y4/+T58ZOtB5P7k7leZACO", + "LF+oF9Nj3IIdQ+1ul25PE9j6NjTcktMtu9vA1aPcsb+A0XhkPY5Hu6Odyf3JfeDUl0zQJR/tjh7CTyBh", + "zwFet+mSb1/ubKPd3/wyYxEa+zNXGpRCNE23bKUBX/nwMLUt9nAQM3xOYRMq4uttUxI486Ub0rABLtkX", + "kGZIW7hL3nxvg/QOsP1/6bxgb4AALzOwak9ppph9PXC15eOpdnVwSSu+eLa7hc9zKTNGsSyCXsE5GyIe", + "cfl+yjNz9ucrAoc34WnpHjJqWU51CS2pEj45Z/gGDdvw5C7Yau3RoaPH2rPbg3zMgDqse7sN10UHyjJi", + "0fpSriAX7x0nI7iN4xGp/ZeLKAj8nFpP7BeLC8KDW5uAJOI3G41BCThHt6GUseUL92sDs5c8iX/zPknv", + "jF8yHwdfvn7DS7z5Hn/+LwyEf7PrBvGJL2zujmzlEnPY4Su905xOdaQz/B7tQfNkzi9ZGunkPrl+LVfg", + "qzdE4LbTH83ctCuk8c7w44uDrXtjQVmJDRdcLXzWY8WxwUqqsW3zP3IpJpBPcPMuIMb06AZH/SJPWf54", + "Bf/hYjaR5o936/0Y/RYcRYMTfHD/PvpiQapReIzLZWZDVrb/x1o+yqNfCyLNTJrAWXVH1KgiSRhLGdaZ", + "fNS5Juti/p+bre0xTa21rRHvE1+eDQlIsOSkywRhBXPI4B4kHyBpgSmz5YJBNmyP28FkCM8SbZCGfeRM", + "aJteAkyRY7Kgma3Q7AZUK6Hp9ZhYb0v/u/WZINOcLiAOUeYkZQlbApJxrXJZaC5m9+xx7tz6cXbFYPW4", + "77uMoIIdP7z1HT+V+TlPUyY2g59CpCxXWsq0Ai/nhVnytFBYM9wfJuEad7Dz4NZ3cJSzRAqktE/BhbnH", + "ViBWMycLmUP8B/ZWljZyUdnUnNGU5ehqpwi7pFnhPEuBobXeTJisw5Uih2OCPX99B88eklwKmh3DNODt", + "vdn9MQFeehCHSwUpfCxeeRr41q1fEEsNDIND0LTIpjadRHBKdqu3D6BWbnslvA/jZjvlKmBaCigPV1OT", + "1pAdJZotljKHaKRLlmeSQoR2mZptQSENLA2qLQAWzfgFy0D7QrOMXWJxBMwRajCoEcPoaoKeqb5i3S3j", + "r9bwz+Yh7VXuHRG3FwtR64JBWV4q9RyYpjNQIx7lMi0STfapppmcgepwKVXMExlzCFNIlIsDNSVbbAT0", + "doRqI6b0Y5mubpeWO7tlVTdlXRhrbMTO7U69EdeAogicmPeTNA2AxFjPRGJrnKgi0wOXMXAZA5cxcBkD", + "lzFwGZ8kl+GYBKe16uQ03o5rKvXtv+C/h+lbZD8yFq1vIKfaKsTtLOR8RXhqU7gkhsrY37nymnOuHTE7", + "Z4CWfDxQlYNB9bfjYGrKeVAEQSi21wPZFY/qjEioFnq/rnxNTcqjqGHUVQJz5VyAgjORltkGLMSPAV+b", + "J4AoTjkTZaHYtMgmZOBaBq5l4FpGj/Ch3eoOnkv9VBai731V04akPIVbm3IQQ1za7pzZHC/V8ui1SyGY", + "RNL0v3J0XEJ0YCaVTbQiBSPsmiutBrZtYNsGtu1TZdsOQm5qjXYo6vPwA9MVXsyc6AVbTaxzE9QsXRbn", + "GVdzlvpEb8BiYPpqwqcEihFUMtdWWbMfmL5dvuydDdj/+x0YtbYsctFf2/xC7NHW6hg47lcozagvt+5P", + "XTjTr9JUx/1HfoZxb+I+gj3fyXvkzk2Bg+Vv4G4H7nbgbgfuduBuB+72s+duS+Z0neEzFgtvk41UNI0N", + "1hQbffJawzsy175ky4wmDA+pn9V24PgGjm/g+AaOb+D4Bo5v4PgGjm8zjq/Cs93UBr1tAxcg/XbUJW4P", + "G5T2Zqtia/KHtuXnZVYeeLSBRxt4tIFHG3i0gUcbeLSBR9uMR/PMU4V1ujGzZq3L7czaETbowazZlgOz", + "NjBrA7M2MGsDszYwawOzNjBrf2dmzTNPm2nUlst1aZKWy7b8SKZvg/l6T6kw7pR9Wi6HVBQDNzVwU0OQ", + "6MBMDMzE3zYVBdJ3x0cAuW8wD9tY39PmE+Zitv2XTS18mL7dhmxk22olknkuhUGzofanZoBbLvdhrEM3", + "1IHpfRx27qPq8dN//q5b687L1XDu5c81hKAOPNHAEw080cATDTzRwBM1eaLj4nzBtU2wWrI0iL8wOVSN", + "XdolSKCJp9Cb8k9cqcL8dlMO6hD7DzxUbx7qKRc0G3ingXcaeKeBdxp4p4F3Gnin2+OdLDvzvrinJV0t", + "mNDbNm/9BnwTeqcfYf9jl/Z+4Jva+abIiQ0c1MBBDRzUwEENHNTAQQ0c1O3Ey1mWhvhSPJsyTH/x7tSt", + "rwQXSkNtNMCikUQKrsXectmPKRpSrw6cx8B5DJ7Vg2f1wHoNrNfAen1qrFfJEgHHU3OI6si3Cpk+YzzU", + "D0x/JtzTrXpdD07WA2M1MFYDYzUwVgNjNTBWf4+sn/8/e+e63MatJP5XQXF3K/YuRVFynMSqSp2i5Ut4", + "fJFjyXHiyGuDMyCJoyEwATCSJv7nGfb7ftrH2OfZFziv8C80gOEMObxJpKxLV6VikRzcMcCvG92NeqSa", + "G+dzlmLKRfi8sVy1gdCeafp1A3si0iHSIdIh0iHSIdIh0t2hsJ51VFd3FLltEShl9vutEwbkU6Bfqlhk", + "uybAWS0M2oE5hDxI500XbjQ6Fsfi//77f/75v/9FPn16UmTz6dMeeacZ+f3zm3dHZKomnz/e+xdDB+6L", + "NDNTD9wPt/XMIk9Xjc6b7guWI4KG17LUKV1hxxbNwRA0ETTRHAw5CzkLOetynFUln0lzMPfrAvI6Y72h", + "lCezo3L+5EbGPU78425hrI8N1UlTV/J7nzWyUJmFfK88ta/xVSvkKjXA0FZITkhOqKJDFR2iI6LjbUdH", + "FmWKm9zyl+Wbkm9mBeyWYciemzPe+RKgbl4E0fAYDIHiMdMk02HO6ZRFvG93mD5PLCCC+s5tR67+bkD8", + "3dWQZipDuxllTBMq3CI+Ympg9yw/t1Ml+zwJT0EBXXfhts+1kyT7oS12lmkGqiWAUHgugXZIYSgX2k6J", + "og66RY6GXJORjBnh+lg4DRMstANmTGhnWI9Zv8/c1d6hdmdSnfQTeWZLtY97tE4SkmlbH8UGVMUJ0/pY", + "cKh2Tob0tNwNquhYqewiXh+v9bEr8I3rjdDgg5B25VCu1fxsCVN5vrFP61av8uQyMV+Xz7sYiPfcDGVm", + "3nAh4J1Zf1E1s2UzbenGm8n3tZW1NpLzC5ZvJuM3itt16umI8mS9JbDzlIoLdPRkfgcqZupxDv9wMWhJ", + "+8eGsn2cXyBg8rWMsTy/8fZdfsIM5YnGSMworqK4iop+lNZQWrurkZinJaiSmOZ30gUi2vaXMVzOdQB/", + "At+DBmlSyurl4y957AU1rt0YKDaSp7PksyCYFb9Akh4jOuv9g0VO2hragYLhORYTots3eiwd0QHlNVeC", + "uXrPx4qlTiJKEI5u6whOCE6o50c9P5IjkiOS440ix9kgVwuPc9zYl2bBq1HaT+fkl7S+XVSbZZAk0xwZ", + "SlW2siZTgsVehd9jQ3rKpToWNEnkma7o8GmoX6jXWC1P5Kx6wTLKhN0MayIA3FZWbfqq/pExlY/r6vWt", + "5Xpxw0b6cprCp0GLG6pBlaK5/axNDk22PHdNdJmoukQCRwJHAkcCRwJHAr8b8Q2Wxu/akAdHtVwZUeFV", + "dfBCpVwQ6l/D4mEYlAn8PRYx7/cZLFcwLcuoLAUbq3QnSrDvKTzszFcs8Y5zmijEgnTfLhEjeuLn++hY", + "TJQElipgxTLOp94QxrOr+9u+fKnimpXsb2q88TRT5lZrgtdvmz6/u/YV+wrhI5CrkauRq5GrkauRq5Gr", + "kasDVzsaIZQIdmY7I/NBJ5ZE7aXNJLb9dT56O2Ui5mKwlXDB9GxXyUrFfBpi0xBu2Ijci4Z20bpfxuwk", + "sZMicHY0P4Ow9o01730ScMwlOhYDaoZgMUp87QtbC5e509V3oIQZTxDe3zsWW7aowp4gPMoFGZegDTXM", + "P+kndpQHdfi42rFkWnxjyIiaaDj1LBV5yF3XZD+F966T37jOcVcdsJdcINJPr8vQN76nbBe5rlshDMfO", + "xitzIateODNyL0mx/9sHgPfCJKaaUH+zGCI/Ij8iPxIvEi8S700m3iki1OsCXM1HWUKdPXA92x76J+x8", + "DTAIjooFjU5gLYyJXpiK9Kgev7jTLSxMS8aZOrsNt05LQxNCR/ZtCuAZygmGJeO83DsVaNdbp8RhwfHp", + "phXKoemeYRA069nOd5PtteUJs73uWqAuGMEQwRDBEMEQwfAOXKy+kK+WJcSAgvNjeRSKugq1zQ7i4Yw+", + "iUzdglq1KgjmwTR2M5smhAu7Mbnl916PaQhqUYY6/9ID21n20/ePRbEu+D4iz0p2A70c8vdvhavPj6DH", + "DbUqZ+9+mEWIRQm2ec8nFa0+HU3OaK6JHsqzSuSPDDbSiCYRjFjRef0kr4/X0Q0jsmpgjkIpqo2PdeCu", + "i2VLhauYTs3ODRMxiw8vlQvXOmNxx752l8ngMRiXXCyHlCkubTOUuUQ9SrlcpjJeT3mJivgcLlOJ5YNg", + "1BS/ShCUmuF0L5dzU4ivMq7F0rW9cGiPeekf55u1Rg+adoybgYIRCkYoGKFghILRHY2bwccEvZIMFP5Y", + "0tKjELyCSfVMLTYHuSBL7EJLpEhy0GqDxQUspNDrilEtBTljRLAgKHmNdsnCJTNWOAo6b2GlpqQwxY7y", + "KHFSyvthOBIHL8ZCSmzOqGgh+4yoOnGn6D5FXCjUZ5mNnHEznKmVD0WNu+N1nY2Lnso1bDAOu0mPmTO7", + "Ywl5du9+USXBzk219d9o0mMDLuwXYB4EYrHICSAaLA9sVD1csOKpP1sYZYnhVnwcW6b0Z/UYVWAWMzZk", + "99YtnNUYp0/bQehOBJPqqoxAfHkbswJZyqmzUNZP+m2iFQgyLTItMi0yLTItMm2VabvTGLjAeGJl8P3i", + "/1oySFyBk5ajDizPFrwEE9ejETj/Kdo35J5UhFGVcKbuE6eVDqcCrixnntydysViOOlzQRP+Jy0OEwCh", + "e4ycSg5Kq/qgcKvYbRTtx+BvSEpISugihy5yiIqIioiKNzP4WwFoK8d8G9uT9HLSfbJ5k4fnzNx0UFs+", + "8lkxoX5vOJ/Cj82VFGfLhj1r2i5IExmzxh4sfs3aGlbP4kFLWF9dn4cvtCdlwqi42mhraOeLQItAi0CL", + "QItAi0B7p2KpLaLZ2hBq/qrsebpKLrx6cqydnFBOuhATcV2wsZjeEg3jxg6f37I0oRFzXYVuYYiLiIuI", + "i4iLiIuIi4iLm8HFKei7zEn4No1PbefNNgftuAfK1pHfaBe/KlxtBhaKDiqrVochOtax7U8V7lALrNpo", + "2okM59y+FlV/uOncg6WiUVRo92acBZNTmhk5ooZHRRVoVPbM89aoboGYakumfbzVb3wy7RaZcDM2JDlu", + "+HoeN/xT09Dsu8ujWWH/eFtO5xFeEV4RXhFeEV4RXhFeEV5XhdfVaPJyZOuQcw7ZeiYt2QNQEduilSHs", + "nEWwSzrzU5qPyvc4TIa5FdpQmBiaibiWYguz1kyHTCMp+nyQqZqb4WiaTkfSdZueXVTOxn5TIfwBRLX9", + "DKrez3u1rkzam02Wa9MMTyaZz4vZzVaOmCYuJgFkO6Iio8kn16M0+SSAxi5STlHnyXKmQdqNDoI0gjSC", + "NII0gjSCNII0gjSCtI+OxiY81ieI61LorJhR+Wxwfmt/9jrbMOsKgobepaQPLz6x+DRKzSZ1slDZORpZ", + "qC1iJGIkYiRiJGIkYiRiJGIkYqTDyAug3KXIUgua6qE0W39kVBhu+Lw7xw79w2T8MKxZzvfKxQeoi0NV", + "uqMh5GDbNZGLfag+p8lbE6Y0sWCzUKhjnda1dUa53cU/9aX6FMkkYcCanz3K2gnFFPOK3/Crj/x0LDwQ", + "6xOepiwulMRcz8Ta0Dk/F61CxkXGRcZFxkXGRcZFxkXGRcb1qtKVMPJSeGvoOdPbihVxAeYpUYuHShYI", + "32hi6LmPL6rJvbG1AE1TopkJL3jQ836jJ40H7kMAUmnYHnGX8moy4oOhgZ0tb5KYhWBa/n23BaZKnvLY", + "vvXT6tOinh6fjug5MiYyJjImMiYyJjImMiYyJupRl6C5S5HlqeTxbJj8RfJ4ccjSIT1lfgNKFKOxN70M", + "p/E+0qhNbPOrBtV3Izii6sROdKr9086wM9OOGfxtaTmBaFmVSeQeL6trp0jTFnqLdJjrjzkw1UF4GS0C", + "LgIuAi4CLgIuAi4C7gYBd4Iwl2VZr5NccPUuTZJJLaYmI2qiYZhkV3AN77QadfXLd2maVu7ehc9QmV5e", + "V8ixWHgfb+39ub7P34TenQLlFSKjdlQ0tCRzqaioy4eHXSoUbLV9K0SEvTbXrFZbcOHbVpfIZtOXrlar", + "gHevohyAcgDeU4UYjBh8V+9enUTVWSFbF1+vOoWDx+LxJAdTxSbkcU1kv3RTVskEoAS3LbJfXKh6ypSy", + "nFvYmYZ1GYZ5MviAkT5ru2CVobXHhvSUS+XMZwOTR0VFplnVNbZKEBu6DbRaiCt4E3eALl8HvPETSQpJ", + "CkkKSQpJCklqkqTmcdCq2sXtL3y5Sz2nWKeXE+6OvOG8XGfRcFoTWb3Fs7i4E0IuCe9c5PufSMHC1ykX", + "wjOWyCcDQEU1cLblHIvgmN7fBwoKweKm/7obQKfgaokjc7wBFMkJyQnPovEsGtER0RHR8YbeALoUNs67", + "CHQODt7Jo+XnzNx0nLwWB9FXdxyLp69Ivki+SL5Ivki+SL5346rQJbF37o2hC8gX4NIH23R79PiiUBJz", + "xSKT5E3C+3bW0jQl0ZCKAWjoYqY5TGci2NmxCPnrYbioyR9mzrpv9FboMzd9vF25dvQ9N8P3/mKCq3YG", + "QhpFGkUaRRpFGkUaRRq9ozeRrnp8H86+F3gFFY/V+8DsF7lMMeK18QIJdbyw/8fcDB7ny2QBmtCQj+24", + "llcIOzV6fLE8TtgFCwdmv1DKVHE78Z6OKE8uloPOev9gkblg8QkVLy7aaq9/3qhmOBSILjqI5YjlaFiK", + "VIpUeldddKISHAYWHQPjkt45i/xa9sd3LW1C5Rey/zq+LEXj0IsFYQNhA2EDYQNhA2Gj3oul5tbFMm3U", + "6b62v4Q/u/GBesHy5RxYCr+RXk66T1oznEJKZLL4+HSiHnPPUud28svukwP19Ny9gqAqQe8OJAokCjxV", + "xFNFRCpEKkSqFbw7FiDVXLeOKiTZHj1hea27w7UBpRUPlZ4zczWHSXh2hPCF8IXwhfCF8IXwdSccDBaS", + "13zPgkUaKvfg9dJQbe7wrmKpf9XW+QhxCHEIcQhxCHEIcQhxd80ufy2Hkts0sjvtTEt9C4x2XGzn0yQh", + "7vFqgOK5mreOy//6HVSuH8N8UxHGEMYQxhDGEMYQxhDG7pJGzdNRCcieCsNNwkbM3Q98ET5L02X9KCFS", + "R0wNne9Q2UnTJ9TQG3AkenWOnMl0/7yxv+oWxP+4GnwM5aJ7HwIlAiUCJQIlAiUC5Z32byyQrlbJ12x0", + "LB3OObPVTNVkVndoa5+8boR4ibPbpaL/TrTXOXscKKdf7Ro2mg4FvP4D3ovUtL5eiIiIiIiIiIiIiIiI", + "iIi3+gC4nuvmQ+IKCsftLzRNu0vdubYEXFZ9Vq+R+rGmRGg3Xp+GdIh0iHSIdIh0iHSIdHijHWzXS4es", + "dKC9/aXPqMkUg1/su8ZmnlTvD5ndVCZOyt0YujfZ50Xu9XJywvL7LdJJElIqj1g20kQPqXKTYUi1M7mz", + "QJAyZXK/HHBFoDZFFznoGWWJ4WnCiDRDpkIizjSxOSpmMiXsTkj1eHGYLH+urWPptP8X6I3rybjjUZtb", + "2Iiev2RiYIaNve++bTZGXISPO1W8pVt/trceffyPe3/b+1R8uP/vK1zfZviINeohe7e9+2CrvbPV3jlq", + "7+zBf612e+dDo9lwt/E19hoxNWzL5zFR4lVe3TY1/KiVRe5G7kbuRu5G7kbuvlOWoGVuPPUsuD6jUEs3", + "KZvrtOMeKeAfFqiSy86xOBBJ7qFXu0d4H8Z67OA9cYcc1yTh4sS91rRUwlwoPoTHrpVJwYb4z7V06qge", + "IRAhECEQIRAhECEQIfAuQeAEg60acAcO+ZfjOHd37/o5rmoXeg1Rbv2RfWop7jHVVx7dB3EScRJxEnES", + "cRJxEnESLT2XJ8qVtIjbqVSGJraJc+9MczgyropLRjTTmksxqVB89/blxTkUrhkrIe6xeAfGifY5xWKu", + "WGSqWRsJn2fU0UgyosJu9M44IKU5KGYtXshYN49FNKSi+DnUk8axsmgCl55FgVK4shghecTIkGsjVb7o", + "/jhXqzdQl0PXXbc2LCY0vEqulYY7r/qrvuxuToXw/jsEcARwBHAEcARwBHAE8PoLAOfD7yUxPOsVtZsf", + "6knb/iWV5yf1wXMjPx1WSrouxqkTtqDaUJPpijXoUi7y5cYdujymvOQnrUEXB4aq67oDFTP1OId/uBi0", + "pP1jrZk9zhtXGB5rozYRpaZiZCtkaWRpZGlkaWRpZOm7HtlKT8DoAoKOWS8bbI+YUTyaTclvgz2rfZr4", + "p8k9LshBysQr/9k5Dt2HvobRE9moxxSRfcLFwL2DMGM10VxEjIy4iAUfDA15d7QPCmk7OcpZ7rs34Z6+", + "b5vPjE2vchLTnFBDRryUvM5Y9omtr8+rsRDHDDs322lC+cSoTnpbIVwhXCFcrQRXyBbIFsgWN9PuEiZC", + "2PRLRAGba5Umym7sFZhIFYtstwT1Vk28dVp1S/cquCRx71XW+weLjDs09o7WukWOhlwTJuJUcgH7EwxQ", + "zFx8HhqPuODaWCY4ZSTNVCrtCiVFkreOxZEkfWai4aRDur+GR6cs4n0ehbJJmjCqIaAPpAhtDlXb/uL/", + "esHyA9V9UnXqL2rZOhbdPkntpsfBw/6U2/rCS2foCbPfschuDBGD1tqy0qDiKQaKQOgh51oP5PR///0/", + "//zf/yKfPj0pOvvTpz3yTjPy++fnT498fXcrtfr88d6/GDqohh8YMFP37H3ChTaMxvXK0AnvqwkdaHW8", + "n/HEgFqO9PJx+IBiWJ1lAh2wPfL5b/7bH/2/WzvHWbu9+93k17ufG81avad/oF7xOeXVvlCvuUxDwoyo", + "NsR/+2Mg9dCSqe9nNsU/eZVNmYoTUW1T6eejPGU/woiz2DVs8seelAmjYlbrJh5fXVP9dCKD1fvg6XmU", + "ZDEjXNAIlozKG1zggX8D75mh1Ky0P9g1J6F22ZeKMKoSztT9RrPBztNExqyxB9gwo/Wu6K4vudL6Ytfw", + "6X2rfH9eRP1+dTdAvOQjbg76fc1MS8I/q6ZK7N/LJCqN/4WPEhbl8TjfrF5/ciV9C/YuKHOizIkyJ8qc", + "KHOizHlH9NmT0uCsOA8fm43zLe6nqLd4nSGQbn8pffJReJcUUEEMLqGwu6P/wmLXZE1WEcMm084Ry56z", + "Mks8ziEC72LjlEr+1zpm70ZijCFsIWwhbKH1BFpPIG0ibd6NE45JtJtJmxW2PJ065pg61Ji0ezjjdru1", + "I8FHjCgqBgwwsut8+mAagmaQAKeFVag4JuCG+B6GdTih2pDvd8lQZkrP0MufLqOR33ebfPdJ2SfQKBqd", + "2LIH4K8HpyJQudaSSk2HDgCRtfFvH3w3Gf92QZjZKY3toaHKkCJQrV3g3j7bJw8ePHjkzVFc94ooyTQ/", + "hTjDdTUN49Qxz5QcVep7kXC405plEa+1lkdy/XW0S4s76/OyTSeynKbtVLQMY79ecuB5dcgvXhN/5FFb", + "nfDbknWqOz25eMUKeyvXKbWzvzDyrz/LmIhL87L7hNx7J/gpU5omSU7eCf5HxshLds4jOVA0HfIIfjiU", + "ysBq3wW67HOm7rteuEJxbOXDlXW9qv1r/IKaDbyWrwsjOr+HgLe2yZRYdua7E5TaE6WddrtpV2Q+ykbh", + "Exf+U1FXCwUDOEBZc9jvpc71un7Vg50Mr2hEaR2ldTwaQWEVhdU7ejQyIVOWZdVTL6U2Z8SccVuptnPN", + "YaxUpEdNNCzhRV8miTwL82o/kZnbeXVhEeesQKakTZd5IW8uFwclsvm7klfsZI8DfzVn5bcFLfuPC1LH", + "LNpoXuKUodxD0C9LxWvBmwkRihCKEIoQihCKEIqmocjtqnNoqKSzDzbm87X2hSV6rUb9WchjKSt3MKe2", + "jxwm2WCG2qj8+wZMu0FtFTNCVTSEfTG0z64m415dUrXrMuv4vNBQeXVDZT+BLmykPC/9VRgohxcAjZMR", + "NhE2ETYRNhE275QGrj8mwACbb5SMs8iQfWpoIgdzdHBh94TbkRmHO5O93xz0rqGGRy3SKW5u5rr4nffH", + "LFlxH6XGxcl1IaOfyXGWBevlMrO7HUmp1oTGbm7ThPQBU7Wb5TB8PVas2/BGRzSJsoTaHaeoVGZ3qWb1", + "Umco8htNBkpm6ePcLxStY/EKuAWMX8jhu1dNsn/w7vVRk7x73f353dNP8Al8XV92jp4eHhE6GCg2oG4p", + "st2kszSVyngfu9l47sIKPitcPjcRi9nn7orqijQzVx53OTQQYywjqSGpIakhqSGpIanVhxgex3+YjWo1", + "CsLtL/4v7ygWs4QZNk1zXg9GaEFGY9+wAwjhUea4QgPHTdjPeswOsf++Rbr9+hRN2Lkr8QjGGYTt267E", + "3B/4uYRhyoccY8ncmk/7fRYZ58FgHyrn3DoWEFhlxKjQTQudlh3PqDtkdIV5lAj5AtrBKkJHjJywvBli", + "lwS4mI7tYmsKwU0UO+Uy09UnhvSU+Z3a9X1M+lxpY5crajfzIi5Lj2pew4JPINWYBRc7vhUjPtfpbbFb", + "Gh7YIpkhmaHPGfqcIZoimiKaTqGpQ5Ol0LRZf0z9nJkp5Kzz//8a+NP+qnou1FshHSEdIR0hHSEdIR3d", + "VI/8FbV2A0UvGHHYpZwda7iiF1tjvGFfbjXScDkOwaWiDVeCRB0oz1H2KV/utYlG7OqzKACWe2pBBOLn", + "bhJg7OEbF3s4GKh6Re9qlqhPikRoiLqiISq8MRc2Q52deh1GqFTkB30nqq4Y/BnqVTML52cAqWqu0vuI", + "wicKnyh8otEEyl4oe90N89ZBAOnFMdDco9tf4N8FphK/SB7b2URdAc68wE43dyyeSDFgyq2cTQh0JpkW", + "3zg5BII+2Re2nymwmO3RxI7L2DZVCt0ik0UU5g6KGSXd1QpJ7nJkYAHRhGpAGpE7q1b3Qth1niaK0Tj3", + "a70xivcyvyIUMpybEorZyeJO7vvZ2EK2ZKTRyxTU6Ey496vIwRvs+uhNhb0FGEBQorkYJKEsu2vkMhtb", + "95YlRrDBoHZZ4xAfi47sq29FzJ1229ljaLuUKfJd29euMAD1+TVL7boXxL1yGdxolvTvkzOZJXGoYhgL", + "2SfftsGExdYfbD9OJffSJGTaLJ7tsUiOmCbtsbXDd+2xKYirXsEs9lWD4WI1sp8ddMd8y5xy+Jm60hlH", + "bRwwCBRFjV8Yxv2mh9A3PQaNB3n4VaZNaIffdPwksX08sr/2WIgNaH8NylHXDSlTXMa2eyeGo3UsnpSi", + "AZZTujBWfSjV6xdc39VJUrQq143jiO22dx9stXe22jtH7Z09+K/Vbu98aDQvFNsKTWWQx5HH8TDoKxwG", + "tR+tvQP2pegnPDIrTtgItodguSntSmuZoqDSyGc7tqkMvaMNNSxsA7UTFcUuFLtQ7Lp5YpdFWIePS0ld", + "XPTltuv2iC8KZkGTpOQ/N05Vf4iyP871KmJ7+uJyDOuJlIeUh1pX3P5x+7+jWte6PbpEAy+lPMlS0hVO", + "8WILmWaCcFfD9hc+cb/ZpPFweLLOaPjN+LfF+jR+fcyFi3ojPCA8IDygigjthZGekJ7ugr1wCWeWBaYR", + "VSfMpAmN2HbivOAXaVLCKNtNRAdFLE1TUsqrXq3yavzAy1DWFF1dkQniJhFsup01JnVIZ0hnSGeo2kE4", + "QTi5G5fZV8ChxCgd+3EhlWx/MXnK5utzaJlBiE9JejmxSWtdw6e36qX0PaDQmafxmdfNnTQ9sun/umII", + "QeZA5kDmQOZA5kDmuBsKEZqmJGaG8kQHCrgod2xzoQ1NEtueWdfKwQN2ctpyC/P2uWqR0i7dSVOfxcpK", + "kVIuPgu/xbagyY4z1h8Eemaxb2hu5+ByEaHbG60PqlsQfRB9EH0QfRB97s5dcJ5E0vSyuGMfPWH5UtRT", + "1r1YAjrllHTedMkLli8Cn86b7guWrwF/OikfZ7Q2CEqVrbzxVsYUyqj12YL2nrC82Bl8MBk16d5ofzs0", + "iqdFklad55iLGv3YvcFvlOzzhFVCe9SF9en2CXxNKOn5dz91SYubTcqxsv3xHcS7Liplx6+4BiXRkmiL", + "0443fOFTmfN+xVEjPMY1oeSQirgnz6GgRl0oEqdYm+zS13TESkeMYYjsm+8nKIR46faJTR+MHYoIPvGE", + "X2CNdvAbDUlrer+Crr+HUf9YPCddLBhkXGRcZFxkXGRcZFxk3K/BuAVoWlC9LO9Ku0TszjxlnFDy2ZIP", + "OpkZto7FWwj9Z2Hn3duXsEkZqpxfPjxCdltt0k/k2VwYhkd3fTHPmXn39uVtOZHchw25k6aHtmMQWxBb", + "EFsQWxBbEFvu1qmk2+KDAoO4HX4d1LJdrBMz+aVTrCS+FpGMWetY/MIU73OmS7hif3HRn8+jIRUDBmHK", + "IMQzMfLErs7Cbjx9xfTQfbM02BTVWFnX57IJ6aGkfRkzCH11aDFB6zf2ad2CQCHL2Icvn6Xtksvm6BYZ", + "lx/MlbVn+Kk85GvPPFN8mUwXjnyNcrbEnQ/cClidvG9ZzBWLfLuQA5EDkQORA5EDkQNvvPrK7ZHzOdAz", + "0jznPPfMDO87l/5rOdwtgQz2nwsH4p+d+nG+THqIBgqZ2M5qTdyrcGnF2FKBoKB4jAKFYIRghGCEYIRg", + "dEddBUcBVQINeXb5+FdzhhnafriPH5JOA5D73e2vGzKGt3m7YpazCdpZb9ErYQKo7igR7GwcLKYIgx+M", + "w6gm1P6cJQaxArECsQKxArECseJGYoXng5EHgCmumNKzbH+Bf7vxgTpMssHcO338TfYz4cP9HuBjsS1P", + "peS5Rj0jev6SiYEZNva++7bZGHERPu7Ygox9yxp7jf/8nW792d569PE/7v1t71Px4f6//+v/+8/f21vf", + "f/y9vfWos/XT31+8ev1m6+iXrQ90a/iPk5FIt8zp1p8fv+w+/Otfayyk8SoT5BDkEOQQ5BDkEOSQZTjE", + "o8JMDmnODW5knyK9nHSfQEcm2aA+qNFdII32V1SfoDoEMQQxBMNlI4chhyGH3VQ77DkQlmY1EPYujeee", + "Mbnfbyt8bejEzHXalXvRI/Ih8iHyoeYJiQeJ524Qj6eXi5+AbQ+UzNKtXr79Bf56nL9g+V/b9mViy5gl", + "E0hFejlxSeZYKT93+f/isr5VLNWsrf64Q1e6R6452dvgWU/sQG8ZPmJ2HXz7bJ88ePDgEXE3wLh4SSJK", + "Ms1PWYs8KYVI2v2WDGWmNKEDCc+VQlbtkb/ZtePH3fbuw632zlZ756jd/rcHHf+/Vrvd/tBouraBKfW4", + "cTZdo9wMn2Vjr7Hb3n0QctvZg/9a7faOzclVt7HXKFpTFyBLmxwysk83pvvjqYhX6Y3pNhvpW7y7SouN", + "vJr2rs0ofaocNEBHTkZORk5GTkZOvqsG6JPAejFqdmgwC49/tr/64uyCmNm9YZqMfy6c024dDS/j1gfN", + "b7l9txs3VksG+LlaEiNXTHDGRSzPVnJ0LCc84iP2QYpVE+vMhyBdrT94Ypjaz7SRIztLLpTcS2grpqXx", + "qV1K4rKQ9wzy0yvmNAjlb9wwAMp7C14QsFIYdm62I31azWZyYiMwIzAjMKMtAdoSoMSAEsPtlhhKDD/f", + "ZXUW07+xv6PFwGpABrl/FbsBJEIkQiRCJEIkQiRCJEIkwpWJcLHS2Gv2FphVhKd8UN4ZZqmFVcVhyPS2", + "qZDXaQNhp3iPDbgQ9pWVfWLzQGMINIZAYwgkeSR5NIZAkEWQvYvGEHpMj/OAVkjD+6E10ZAKwZIFGEvd", + "TlQkIyFZPcu+Lj26HwqYQtrJa7sgmi9xEXzi+uLsAlB0hKWfd3Zv2iOf/1YNBvyjJeDPjWaDnaeJjFlj", + "D9aDevqZiCNcJqFiNvjk05eiLgC6olVc2/l94Wb55D9CPVZtmE982ZZdmyjUNdPrwjGpl81r04YMNfXw", + "vcNivIcNwRbBFsEWwRbB9o6BbS0ulfi2vG0uFXxasLPaTGfFo67ZlzcUnbqmJFeFlQ7SdzZZHwxgjcCC", + "wILAgsCCwILAMiOANa3liznMskg1t/3F/9WN58a4PpR949VntVUgvZzwGPRLByKaVVE7GYIOjpuwCfYY", + "LGfw9azo2fWotPgcu2jd3DPs8aFke+f5dw8/fP/wYefZ+86Ln57u7L7+rb3/86NnPzWqp9kYNhvpB+kH", + "LQrRohDxD/EP8e9K4oavjH9z44nP4bi6sOK3G8Ha10a3hboqpDWkNaQ1pDWkNaS1mxpdfGVQmxdzfLlD", + "RffwrcO063oaisSIxIjEiMSIxIjEiMSIxLiG6OxrO96FSbWq34VLtNjr4qnLfIHPxVJ+uGN30xvpL7uw", + "+lfl/DpVeRdW0S4ivZyMssTwNGGkz6jJFCM81vaVO2G5rrqE+Ad+9P9u7Rxn7fbud5Nf736eNVzugUqj", + "l3WsvWCbvGPS7Db5B370/4Y2TX49s00hzOYVtkllCQxStSH22x/bO3//4e+7v/72Yff1w/ePf3vRfvT0", + "yYdnjw8/vHLNGj/07dtvf/nw084P7RdvX/z83YPXj3d/6Tyc1UibrL6FEwLpy+4Tcu+d4KdMaZokOXkn", + "+B8ZIy/ZOY/kQNF0yCP44VAqA9tBF/Czz5m63wLvoisUIdc0IIX9yuSY+B9Cj//60/ff//Dr4/bD7/5+", + "2P7hhzf7vx25Yak+d7jzduf5o6e/vP5u9+3z3QedR6+++/uskRlvAndxcK6lXxhsgGvxCpud01X6hEEt", + "0CMMVRCogkADa5TAUQJHj7BCHL6w8L39Bf71dtXLmuFAmiWNcGDbXupsx9dkpcvFrhQ+kDWQNZA18LgD", + "jzsQthC27p6BDPMoc1nU2oaFJrYNq4+6/xZ+3xxF3Tr7GOge12srWcfs1rq0VTZ4t7lHlkuYc2rz1ATM", + "Yne/8eeCCHJmiK2y9xZEEkQSRBJEEkQSRBJEErx5JPiWbYFL+1poUGUJW9XoBdIstnl5C1lfJswoFHTL", + "Yowu2abrEGB0RfOY7Su2jVnvQf6x6JATlts1ipLMJXVCQ0GamXY7DXfJchcqy0GRbfbRwZODPRdlAnIZ", + "r11aJplbxyXRWZpKZUhPmiGBWlMRkxe2aL9f0REjOmURbPaRjNmACfu6fd1rI9ZkFuJeBhpVY5zMthHp", + "vP3w4PWTpy+ODn/59u3bZ89+/u7R84fPOr/U2Ijs/vbw129fv37+8+GD3f1nP+y8f/Tw6YML2YjcEqML", + "uwKvxeZiZkZXaXJhK4EWFyj7ouyLFhco+qHohxYXQZxYawBem+My0XffOvPnTSvTbTHXJu4utBmD7iKh", + "IKEgoSChIKEgoSwVdNe7Sl1IOb39xf5z0Vi74BY2P9Cu8xxbR5Rdj0SLzSJcizC+LoIOgg6aIaAZApIe", + "kh6S3m2Ir7uA9JYPrlsCt0VOPbcJu9rXQ2+FeijEM8QzxDPEM8QzxLNb4S+0kMyWjqZbf0I4HUr3hnPZ", + "tTzXRD5EPkQ+RD5EPkQ+RD5EPlxz+Ny1HNRu2zen7E8+MZR2aGZo+zQTsZ2HFN4+H9rnjJshUVTEckRi", + "aug0e9osb6tGcOeahBBCUzZERERERERERERERMS7gIgAahfEwzShYgm/cnis3pX8DeSwovs45HfjPMad", + "p6zlX1v/lt0tjVG8lxk2w3uVxxh5frrjTli+sOdOWL5M113KGXwdvtob6h3h3pGWnRH2jS66S8/ur1/c", + "s5Vuo7HbMGjyRtl313Anr0y6UNtFcwAOx1O195+luyqi1JyYsfQgfPtlahNPcqKYyZTwbzuIh3ZNdxu5", + "NtRkZXfyY7FFPv/Nff0jjSxdf94LWUibnU083i/cI5B5JWmsaN/UpITvpx+nKhpaaaEmRfjJNWDWHRqQ", + "Tf1cnYtGCRWHLu2lp4zrlGjxWxUeXL26+z7lvl2Ab5Snve3oC3vXz0y8aY96WzB60aNgj4I9+qihXIty", + "7V31og/oFWTZN0rGWWTIPjU0kYNlXecBk2Z4y9utdkMe8jZrV8hVu8NDo/DcAPEC8QLxAvEC8QLxYpYL", + "fOr2/9mEMakv3/5i/+nGB+oFy//aFux8wowiVSyyPRWsFOaAidNKBTUfzEZglWPRNV4hpX1DeN+OrXPt", + "poliNM597e3r7TKSiri6kVgyt3or1meKicjNjISCxUaa9RKuhywORU/D0Wt2bjwaLTbQKHXIXCuNrxob", + "s9k43xrIrSl9bd23H5HNkM2QzdCmA206EE4RThFOrxZOXxdoeGE6XToQExDk2KihHIDJweVFYy6tSI8Y", + "ZwmJDYkNiQ2JDYkNiQ2J7UbGWVqIa3NDKwUU49CfJyxvkaM5SjsCgGEyJezs69vnjBvQTLP6gEzrZLIb", + "o8ybefeT79jQnRI0rOSNU6lqw+y8dt8VPS6C4aE21NTbLb+EXC9ituxSXspqedNGaWiDhliLWItYi1iL", + "WItYeyfiUy3BtPOCUo2hdlY0qhuuKNyM3eBbliY0Yq6HrjrqFJIekh6SHpIekh6SHpLe3Yo0dfET520a", + "x3KZeALFQBMax1v2tex7y8XZQQY6Lu/boLv8a85t9KUICb5zCNWaD8TIToMbFicB5kMlUEILIyWs0nWV", + "UAktjJVQ2z8WbODTdLSE1rUNl3Ct/ONhbb2Uk/zsHK7CUx5KR3d5FGBRgEUBFgVYFGBRgL2j8QLmS5eX", + "CSQg2Nm0QDZHbh0HFwA6wfONOmb7esER3KCgFx4SJRIlEuVmibL9aO0dsC9FP+GRWXHCRjJLYj9lic3W", + "aRsLrIh8tuNojaF3wNwxWEPWTlTkZuRm5OYbGwhjPt9e6kDIfQbiWuCXGG4rns3Za/VOvMFk3pxZTd/P", + "6E6J6I3ojeiNylyEUoRShNIb6U55QSCd52Q5M8dZNurea3KtrPj1zY8uAY9fufJXYkyAtgOIm4ibiJuI", + "m4ibiJt3ws3xwqw5z/lxFYuBsTMk6iVvhXXDV3fhRJRFlEWURZRFlEWURZS9W36caz/Kd7ehVm+6qFTS", + "PRAO5mdeLOGfu03RgTHwBgIbAhsCGwIbAhsCGwLbSsAWuKlMTRdkNB8heDajvXEPLGQ0/xwyGjIaMhoy", + "GjIaMhoyGjLanWW0wE0r6c+kMjTZ9kFyvsC/h0k2+GvbBSOaFSXtZ/srgcdh6Ymk0NmIKeIybJGjIdeE", + "iTiVXLjt2NYuSnLCzlOpwxCHdLpF1p/lFDFCEW8gu1e2nKWwseiTzdob1h9TL4hqBK2AVrUc3HTjxmrJ", + "7HKxYhIjV0xwxkUsz5aN9TSV8IiP2AcpVk3chzBc+5k2csTU6h0DyZ8rmaWP8xXT0vjULjwxfOWzcFHB", + "9Io5DUL5m5QVxuW9haAAsK4Ydm62I31azWZyiqJ8gfIFyhcoX6B8gfIFyhe3Ur5gUaa4yQGP9xOZxQ6g", + "j+QJE53MEu7vHy2ejAWRMsmX/i7LJJBFrShibL4LwjO7Z2aEYR7XriYQ8zJhhxM+4jPuN9t9CCFm+Sgb", + "NfZ22m0Aff+pWRN4db3XnhURXucuheP2T4d+RV5DXkNeW43XEFcQVxBXbmiozQkloieHOhJZEFmT1mc1", + "M6RmaRfekANHeZ+/Yq+NyaIRKRApECkQKRApECnuQBTCWhJYRbux7Rd+aua4KnSLZ/QMjCG9nHSfwKhk", + "cGnLNI2MM5nQi1wUSdLqnTPxvHoTWqmvq26r7oYdX//5mSXJRPPtLkHLbZ86QJ286WYZTsKwfwhBCEEI", + "QQhBCEEIQdMQVNqSFypVSgBkN+WUbUdDFp3IzGxrpjX3F3HO1byEFMSnmKVyOYQC9v3Th+7hDSlf5pTo", + "9+Crvi5kbo28UQ9eI4JQg1CDxj1o3INUh1SHVFen2pqArRLUddJ0jzjAmCA7p4Cp2uykikW2e4KlfI0V", + "T0gH12X833//zz//97/Ip09PiqSfPu2RQ/+MhY0RFXQAw2s3E8OZJlQx0mN2ptoSKSRrErsjRd7uW7tb", + "gnxZcLt0BjtxuH/ZvghcaMNoXG9QFKrQuArrHV8YWu4gjCGMoYYJWQRZ5I5a7ujxthsIpNiJq9Y681Hj", + "XaqZsgBRHBQRxzra9nOWugO28JtFka67PzAgQyyZFt8YJ+U07cyE/u+xoAhpTSVxAlHl2ZQqu+baaQFF", + "xuPbC1MlT3nMYv/SX2Mccn0ZGOXiqrVVUMiVWQ9E6zV5QkBDQENAQ0BDQENAQ0CbH77V7smBIuoJrUZB", + "tP3F/9WND9QLlk/dsjqf5Px1W4FdCuOnE5ZfY2ZytR4z0+KAE9VOmht1Ai8xRZRBlEGUQZRBlEGUucQd", + "nnNRprnssdZzZm4anjxn5quxyfo80gqtDGphEF0QXdBmCW2WkN2Q3e7AhZiX1kFtA2olbGTrvKoJE00S", + "Uk4/4ZJGnknlTKrsxCw9SGhk93UHcna4t+0LzErRTT2vzQHHd5qR3z8/f3pEXBt3twsi3P4SFWEva1r5", + "+eO9fzF0UPlue8DMqvncX8pw6mm5fzfMmM3lIjxxESVZzBz7x/WhnnxyX0JPyoRR8ZViOpW6EA8eEXkR", + "eVFbh8SHxHe3LcMq4FXivwpvrGIpdpAyAaGwYRE1Q8UYsVutJrJfKWzPxbNkcZN4LmiCw5y2omnUInbY", + "bULigyXkJLbPj7hgbl+DH6uZulSwniW5ndR9Rk2mnNud29xsR1PD7cwpbMfKTAm56pRFvG8X/Ynlw++F", + "NNS9klQwFmtCi0Kp1jLiYzM1n+o+8OgWeexaXUXfmPW5YL4Txjl50LWlk+PGvn3LNSOHhwcT289xo2Wz", + "PnTJKzknzJBcZiSlWhOaSDFw4bj6fJA55rTTP2FkoKiwO/Nkqe+0Wya4LuoFzfqV/EY0MzaJPm6Qe7aA", + "cc+5Eu5DtV5Nd5omQ3rKyIiK3OljqWa66RYnnynJUqeL3epRm7Grlh1OPkpdLvYpO7AJO4cNmFs40RYK", + "W4Q8dddR7cHcCChuoQkK3Gm3223S6YZwGHGmwmroFMApU1zGdqJNTBUYxo7fZsLrZLOVIslds6SwYwfY", + "c09IseWO6eP7lWmT2v3IdegLlrdItw/jZFQOFzGEyGmCnVWSOSFpnNAt8TRRjMY5THgqQuGldM3KfIal", + "rk95Embot+1HbvWA1h2IiJHqFIU12Puu2mp6+BzJmPdzwk3TNd+11KLCQuHrzcHhmqQvu0atUfxyFq5l", + "seEqlPvr97MutcA1qSvSzOirdq6uyF/oRo3yGcpnGz6SeLT2FuxL0U94ZFYcr0hmSexHzG/U9qUtID3y", + "2Y6RLJxXWBBiYfOtHSeUQlEKRSn0xvpK0zpJdLYguvJhxPaX0if7xLOCmP/aBlHnQucVLiXhWmfMGXxW", + "MdlJomVutpJBj3kBLyaMmyFTpGeZWRMO86EkBWzkyGKJvljXqcYSRS04+CgN/HM3TJs/9qjJcGYzrvmR", + "ypIlShUz9TivFEWT5KAPHTxvYYBBOfDJrehS1LDhnfM65uuf9EAt8bgHxQkUJ/C4B0EbQRuPewoiHQSs", + "uvShjwO0cHhBSY8N6SmXygruxXGCU6c7tXXN8QkQcw6YDLpzUBNwKJQo5uYBaKNjomSS2OElKkuYbtrZ", + "Lk5g1XIj6vXS4/qc8ZgRRcUAVAn+AMHfJ6yD6ltzMQjHH3aXIyOpjTuQgBxjKb4xrm5G+mMBHkE0Aq+k", + "F+zMd2qL/ObrANpwEBOCzAA94PTyNd2gw7GCfdi3QBPqlzc6sq++bYTrTXjPvWThw5vHxT40JY64PLm2", + "jWP9PhjYM3Nmdz0rhLivbL1cqHARu6/PU+4PiOz3LXIIp2NwvtaTZmgzHFERUyNVDoWX+sE2xs8O6DlK", + "UsWl4iYvjnegDdWzPa4IgKlrKGuRl/KMKSKyUY8pn9OQD6wAFbJrumFsezt/cLazT2hTPFKuTDHNaHly", + "hSrBGhG7fYJmRo5sf9gsR1RkNCGK2RG1T4YJrp2ZGnNnTU1CSUx5kpcz55qwPzKI9FrKAFqv6SiMDjtl", + "Kicxzck9PhASDqOK+R6O2dwR4tvJr8OEP7N5DmmaMgFvhVsp7dIHY0YTu/zBm+ALpcZpz5lpkcfu508d", + "u/h9emu/JD+SV93X917R81BkB+Zhk7zq/HovJHjM+lIxl6JJXnFRffj+/Wr3B23g0L6WdvONilgglTOk", + "2N9ZzqEpTOhM+XkfGsJ1MX24Njwiig2oihP7ksu+2+I5zHsr/HAWb+hM6qLi9UWOrS4nXzvdi5ONbrBU", + "vfnzMuii0qHZVzwz85IsHpyhpIuSLh6c4cEZyvMoz9/hg7OZEv1VHZ7ZAVE8dpdvZcsZh7okYFxYtSqL", + "fDTBGjs3O9ErEf44mC85Y1HZN15O0P4hdsplpqdM5So5+DZvBTvGlHIFhnczs+C6MK3zYomdh9IMmTrj", + "mrn4hkV4Q5tN6J6xjR2IHSDLjD2UtI8BA3XM0oGiMdNNEsszEf4O5XhRyYtBJQtKWBw8k9Z0oLd79bwH", + "G8WfTEkow/ARW0IaerdmYSj0Tb04lJmNFDZHHvLz8ipt/W62XIR2hCgOoTiEoQ3uRmgDlAdRHkR5EOXB", + "6ykPBnj9moaUEHhhBTvKqhSkh7CsuYCY3prSndFC2Acn6jHRlyryp5mdasgI72Goh1S5eTOkuuNPeYP3", + "oFs5uCIuSEToTRebc5QlhqcJ85LW+H5mCB2mmMmUsGgADmh+HZksH+QoiFUhxSkTHA79FKNaCt0MsSnO", + "pDrxJ85wdlrpU2jnVzUChUpeiQ0olHR/bki10oz9BebXzTYArTO/tPJ3xfbSHyA39hq77d0HW+2drfbO", + "UXtnD/5rtds7HxpNMKWkprHXiKlhWz6P6evA12p4uaRE5gYK7StRzEIxC8UsjCCHAggKIHcoglwFik89", + "tG1IArnIxQc1J0+KncoTC/pFWAk77qXYHR7IW6Sjx1ais+M9zA7t0HSLwXFjxAeWdMXguBF+diamwbjU", + "R0+AY6RkIl4G1eSMJUnrWHSKSoe4KVkhMXmb0CHXRioe0cTbvummy7ymI1KZZgkNB2n+lKtjiOVLbego", + "bZH3tv7eiM5b8tpfSQ9M/2BRaE7JRlwTbewrEEmheeyWFbAzbZYjSEDbFTNKeuPY0nFXiETi3ieuCR/B", + "rfnubK9J6EiKgZfdAMZ0k9DMLlVisFiKevL05dOjp2sVpGpFKNel6yzm/qIbM67XgRbewoGCCAoiKIig", + "IIKCCAoiKIhs9hqS5c5BVrqWpIy1vZzw+LoGp16ZTdes3l9asX/zqbT91Q2bUIOO4IrgiuCK4IrgiuB6", + "izToG9SdbzvNcL6Czc5bsILRZZ1y8MCmIvYBCWJq6OwABEF17AsHLbVOIU5xpKTWYzsccEYn8HK4IAKP", + "MyVieSZ+8kmVrw3YPBouZKaLbGWfaDaAdoPO3RsFhe/ApkczoFK7jea+HB9NwTuk+wBtpoib0PM1GEcw", + "8M0sx4mGur7n9kEWT9b1zH9f11c+zDQTits3wZsIBQ934Uw+7Lph+9omSLg24/ADru5nrLjo0NbWgI+H", + "W3Dtr1D8V7Aq8uNyJXZFvqylBRA/RjdNDmlOasIPDVUwH+BAxsU6MRLeuLz8Iu6RwmjIToy3z/bJgwcP", + "HhE3wVrkiVs7i4OwhGoTQkM8Z/Z7lYko7NDh7cgS6t4IZ19cisAPPWoHoc78ye54V2P+NNVfT0W85t4S", + "8G51+4BsQp7ZnhBksO4+M/Ir9Zhb1TT/0yZeJragW28OXYLZU3vejvt+nMXiCsKNEXzE/rRYDJakgI4R", + "TaIsoSYglauWbq3UiiM+Yh+kYPUxGRvvjva/rgle2HJ8MJawqqEaAdUIqEZANQKqEVCNgGqEu2qINyxk", + "nI2pE0BCgEgQS4aMdIHlRlSduN1cB/nFeWhX7l6q0Se46ISCGw4Wa05CD3HyWqRjJjP1Wbl8uYYQCDGR", + "mcvJC9Hg7CMTO30gsF7Z34er6Th8LdI15Aycl0ye+mCQPWYJIgoyPNTDdyrp+XfS1wYiOYBbk6/YRIE6", + "6xV9BnL7u1B9H5XQF+m0Jbab6iJKTuZa7ttgFFV2x6JJIs9gb3ThDosCuIsUKHLAbG8OGEvbIC3LWgwq", + "oqGL/mnqo+AHJQvvw61pXyckHzTqaiLyQVFzdBLwNpReShjnG3k2uv6wE7V9s0I0PjQbRLEJxSYUm1Bs", + "QrEJxSYUm6bEJieKXOL8tShYlyWgupDLh6WHG5vBpXIRrtCrDtBVaeSNjNBVbsEYw2ApuhsQRn6hioNI", + "DDIstPzpuWFCw1bi78eOoO7l+Y/0hjGP61ciH5hqqXdow9GujsWlZjdiHmIeYt5NjptcRrAAeIcVjJtN", + "eKAXLz7WeKFP+ZxDVOOKJpcciCQvDUalgPFFoe72kxmevRMkuZSisFTtuYq9sU1Je+f5dw8/fP/wYefZ", + "+86Ln57u7L7+rb3/86NnP0GZcIFSY6/xn7+3t77/+Ht761Fn66e/v3j1+s3W0S9bH+jW8B8nI5FumdOt", + "Pz9+2X34179OW0ncIkdfxEbERlT6YWxY5GbkZuRm5Obb5lW9DDcX/tRTRve3h1hnWh4Tavyk8FYfxUOl", + "GLfhEkLiTcWLW0nKC7GzOIfbQeJZluDU3PzQoeVJ8fQ8pSJmMVot4/E7kjiSOB6/I18iX94Vq+Xl4DKl", + "JhpOqwcf26/DPmunTyRHIypit+qPqOBpcAFTmYBrsKsS6rGw43rCcu/aZ8f283Y6pJrp7S/wL8TOsaNV", + "8/02N2ykt7/Yf+C5abXt05ibW6a03azxgu2w5UwX2l/fdAFNEVCnjCSLJIs6ZdQpI/Mj8yPzz2V+y3Zr", + "t8TYpnHsbXCLkEblCr7kGpzbiHvO+QVWDTO64VX1F35BkB0YjBFIGDCemhmSCf5Hxkgvd5l1a+w0bHHl", + "tnRc7W6ZrcZq7A1i0ip7FXSaneK+JlQpimEtUEGMWI1YjQpihEWExdsPi8BtlcN0GlBqjqK4iENRLtbb", + "ADsfo+ksmyHqozuTD9PshBWxHnkcJFlIME19035eDmFQ27sE6H19fzXPmzfRaQ15FHkUefRuq3mDanfF", + "Cbsh5S5SN1I3UvftcZdzzLtGVW31+47TpP41U4H7nJkJja2rkb+LqS7S9y0D8ebC6vpOvEU6482hO6I4", + "ojiiOKI4QipCKkLqbbAdXkioMy2I36UxnQ7V4Pnyng+JC2Frwwz7I6PCcJPvkTRT0ZCC3TG8uVxoY0dB", + "2/GJ7F/jeRnWsuKZ+1PY6qqC5Hpn1N5uwL+mrTOyM7IzsjOyM7IzsjOy891gZ0cdm1LwOuyt3ghSscSA", + "3/VUoITWsXhvO94dltv3loZhcn59/iSKw5GTYnBnhwSjjWoYtfHY2u0eLgJx4wYU7qDcrYVwmcW0IQc8", + "gh57dgSV7RrDHYMabnkGUiXJQR86YlnOPHJpbWWq06EuFkZlZnLtB80uW6MRi+2rmORuUvu2SojgjD6D", + "6DOIPoNI4WhMgj6D6DOI8grKK7fEIAXwb/1eg+4uujmSil10wX63JnIIWP+CdKG9EbBdmGkUSRX7dRve", + "Rb8kUS/i7LsYz3BJtd0EsnSgaMx0E27sD3/bvNOECn9dnq4RUuAHFFJW2cnccH9FIcHVILwW0FAUG1Bs", + "QLEBxQYUG1BsQLEBxQYUG9YnNgBtrV9sGPGBomaO3PDKPVA94uDGTk9/WXZQdp8yZZegsHCF1cyif+tY", + "dPsklVrzXsKa8Lsr2SaAsesxEttlvawVh1RCmlkJKocj7o7ueLL46l3l07KHbx8KH1MnJL7nOnALeu1d", + "NkXnVm9KrwajOSrPETirC8MnpBrRxFLhtKgZco5ozETEwteCUQWwy9z4Roz0WN9uIu5szN3oPnEM0/Tz", + "lJ1ymemq4DvRglC1ELB8rdHIqbKA/mZINavvTvDQdn0IMTnHZ37TB0mieDsm2ll5DNrjsvCbap8rbXz2", + "oSz7hjaajREXL5kYmGFjb6emAY5EfnFveX0DJpYAkPqN9G+ubc7ylR6ngQcSuwaZuWuMawEfZaNy/e1O", + "MWAKGrCuIz+/dzSKtaoxtf/B48B4fJCpKvAWC1nTk0tlcfMh9g09YYT1+ywy407TWZpKZXeLXj7Vb03y", + "bbtdzOAQ/OmaHS2i1gC1Bqg1QK0Bag1Qa4BaA9QaoNZgk1oDL9yuX21ghTCpJtQGqWKR7bwgAVfr/dYl", + "0XYRCyZwEyaTHZFPXDc1bf1oBYGxnOavl4UzRrg8dVqQgHVUGC4y+zaImPW54M7oblIX4Kt4my+lvc0G", + "g+hzgwCOAI4+N4iViJWIlRvESs9J68fKTIR+3XKMSI3XNS/hflOMSCnpNOO9K4rYL5WAlIduIaipRVBE", + "UERNLWpqEakRqRGpr9aNvcDSMr4uA9W721GmjRwxpbe/hD+78YGCG13tDmkSNrKtWHylVPlpWL/t4u5y", + "bJFnUpFoyKITOzNLTxIaWXZqkky78d62bzAYY6WS+yBRjM64W2rf5/+0VPQvu0sB+URj5xL53EF92X1y", + "AGusfeVtThDoiZ2niYxZYw8WoaarwR8ZU/m4ClxESRazJ04N3SiXWExBn9xTe0/KhFHhLIJykBEsJjZs", + "iXWVHHfD9hs64MKJNSkdsAskOeR/LpWsNBgHKmbqcQ7/cDFoSfvHOvJ4nDc2KrmUyv9l1/cDi1cBU9RY", + "o8YaBZGyIIJ0iXSJdHlD754KuFShvBJhPq1+HcBs3kVUBykTr+x2D+unGSrGiOUcuJW0XMweASpgcZN4", + "AGoGn2PDI2ckbhMSb4Kek9g+P+LCex7Aj9VMXSpYypLczuc+oyZT7t4it6/ZPqaG20lTSOFlcoVcvUQN", + "1gGVGeW3QRrqXkkqGIs1oUWhVGsZuTkDRflU91vH4lhskceu1VXCBlsE5jthnJPHaVs6OW7s2xdcM3J4", + "eDCx8xw3WjbrQ5e8knPCDMllRlKqNaGJFAOvkRhbI58NecLIQFFhwAC+Wuo77VYIrot6QbN+Jb8RzYxN", + "oo8b5J4tYNxzroT7UK1X052myZCeMjKiIocmRVQz3XTrks+UZCnJLEts9ah2jgFANZLwUepycYbV9tM5", + "7L3ccok2bKRbhDx1mvc9mBvFjI98H+602+026XSJkSdMaBJnKiyEUKj3Egm6mfJks8PY8TtMJV8pkty1", + "y/nMA/LcE1JseeOU+5V5k9q9yPXoC5aDr4IdKKNy28iofLNbOZkTxsYJ3fJOE8VonMOMpyIUXkrXrExo", + "WOb6lCdhin7bfuRWDmjegYgYqc5RWH/97V+2mh48RzLm/Zxw03TNdy0FTKi/Sa5GyrsGQt6G/PQrjXTt", + "74o0M/qqr4Sr9jZeB4cSEkpImz6qwdvQUA5EORDlwOt8GxqtlQWXEwUvcO6w/aX0yT7xrMDYv5xMaZem", + "aekStOrOObfCpIqdyhOmS7IB3GQ8FsA8JrdIB27C4GKQsHnQPpvPvYfmccP7Z4rBcSP8rIGIIRMjAwLb", + "mshkQuqhmpyxJGkdi05R6yD9ZtodqkBgWDvphlwbqXhEE/JHxhSHcFozeiKVaZYU3vle3ug4N2ht6Cht", + "kfe2/i6j2EsR9tfgNm1Xh+aUXMw10ca+C5EUmsdufQHholkWA6DtihklveThI3zB++flSfdicW3lN6kM", + "dbJMk9CRFUpdyGNAL90kNLNrlhhMSxHugOV6ShH1d4LMnPJzyx7R8+CC/d23kx7ZZXMxuvVne+vRx/+4", + "97e9T8WH+//+r/9vzZZk39Y6eivmTDiIX/aAoZmIPd1xHVbjJhCTnV5u+9VkRHPvYN/PkhZBuQHlBpQb", + "0MQLRQoUKVCkuIEihSOzSwgUzdm3JJeRtJcXBxEnLF+DNRIEVSkp1LmGqD+1MGwXtuSUxcWCF9bDMWjX", + "XduMvHrlvNq+BspzVIYj1CLUItQi1CLUItTe1AuZr42KfBtsdJaw3nfPEa51FnS9Ytpgqoy2XuXs7JBi", + "wjioY3s54TYfmAclW5Vl7fefQz2QdNdJunfbH+ElH3Fz0O9rZloS/lk1VWL/XiYRTN4LOz3MTr1pdwco", + "GR0dUHJByQUdHRDcEdzR0aGCuh6iL+Xu4MA2mO1T0mNDespd4PvCkN4ZkjtLixrHAYDwHMgbzCfAMo9D", + "3MRyVHsqYqJkktiRJSpLmG7aiS5OYMFyg+ktMcb1OeMxIwouipD9YGji2VQHm29vDgP1tRscGUnbZ1R7", + "g5ZYim9MYdbiDOJ5RJMkD9bpgp357myR33wdwKAGJI8ghkAPOLOQmm7QwaDePuxboAn1Kxsd2bfeNsL1", + "JrziXliJpNDZqKSLn5JwXJ5c28a5COqkx8yZ3fCsXOO+svWC2whsT8PX5yn3rhH2+xY5BL8Q8CzpSQM2", + "LCMqYmqkyqHwUj/YxvjZAT1HSaq4VNzkhWMDtKHq1cIVATZ0DWUt8lKeMUVENuox5XMa8oGVyUJ2TTeM", + "bdJjYWWDJ7QpHilXpphmtDy5QpVgeYjdFkEzI0fUWzCNqMhoQhSzI2qfDBNcu4MXH9+oSSiJKU/ycuZc", + "E/aHTW1kKQNovaajMDrslKmcxDQn9/hASHDDKOZ7cDBxzjNvJ78OE/7M5jmkacpEYQWmmF31YMxoYlc+", + "eBN8odQ4g3VmWuSx+/lTx657n97aL8mP5FX39b1X9DwU2YF52CSvOr/eCwkeg+GUS9Ekr7ioPnz/frX7", + "gwEuWEbZfTdiwYC+4jwR27lr5yw0hQmdeeusoiFcF9OHa8MjotiAqjixL7nsu92dw7z35l4rOGN46QEl", + "9jWfTW3UuQQGreRfEo6pvoqDSZhB6GWC4imKp+hlgl4mKISjEH6XvUxmi+Ff5xjNOVbkM8/R3sKNWbrs", + "gBHQ23KKk0RjauhsyTP4WfiiQPzSKXhmR0pqTUZZYniaMCeFEHhdnPT4OFMilmfiJ59U+dpQf3uBzHSR", + "rewTzQbQYnBQUcyvIwPvb6LsByB/d1WYK8eL0V4S8Yd9phCYe74GY9HVN7PsGg91fc/tgyyerOuZ/76u", + "r7xnPROK23fD7QeFaCPcHXrhKnq48Y1rM5Y7Xd3PbFOd5Gtra+CeebcE21+h+GUt8XzlUehZ8zFl9aU6", + "hEs77C7PR0E3ZSS8KHn5/dkjxeWJdjzfPtsnDx48eETcvGiRJ24R1OP7AOEWSBDlnzP7vcpEFLbaMKmz", + "hLqJ7CijFCsERttOlbpTVLt1NerjOa/hGsiJQ9Zqfz31N5iur7eEPBtfICjkme0JQQbr7jMjv1KPucVI", + "8z8Z3Ne5+IzcLROHLsHF3uL34ywWVxBi2/AR+1MKd7GoY8CIJlGWUBPYyFVLt1ZqxREfsQ9SsPqT/sa7", + "o/3FPbrJU+mwU3jlmV9z8UwahX4U+tGaFq1pUR+A+oA7a00b5Nmvow6ww6N47O4wzOqCG7oHasIuuKMJ", + "XRemzU5yU77xnkPkLxfuQfaNP+3T1SvpJyO9VXIITdwK/m8p5QoCx83Mg+siNFy4IVEqF2zhjGtGYsm0", + "BQ67uDqHt9Ab4xhxIOnDkeTYdU57v32oZJYOFI0hPIU8E+HvUE45FkQlGAasDB67a3rQB270hz+gJfiT", + "KQllwO3+U+K9H6c7EB0C49thfDsUQlAIQSHkVl1FhEevKGqhqIWi1hpErcDC18h7EQ5pZl/h6SwvR1Sd", + "+Gs8w4GRo7NKWO6ac1dnviu44SCRuZPMYEjaIh0zmanPyuXLNQgXMZGZy8kfNlLFIBO7UNjJ6WKRuzWD", + "q2lD1RbpGnIG67HJU28t3WOWlqIgxZhSQHJNev7V9NUBIakv7Z7kajZR4sRF+cfiXai/t9v1ZbpjZdtP", + "dTbXk7mWOzdEaivLezRJ5BmAgDMILgrgzpZW5HCw4YMMxtI2SMvycS8V0dDZx5t619NwGs37EFG/zmgV", + "ZkiNcAddgMe3N8BmFUZwcuRAZFxOYsQghCjcoXCHwh2eMKHYg2IPij1TYo8TIq6PzAMhB2camu77eN+h", + "uuM45sH/MZz03Ovl5ITl91ukU72d1d+ypYfU234Oqe54f89wgxYPmO8CIIa+czRUGKK6wxqfiDMv+4BB", + "p90iSwLDVPlLxzy05SOor9nOstYIz5nQXYEZ3lVFXvRTBw3GEOcR5xHnEecR5xHn76zBmOPqVZG+ct/t", + "wiiKFYU5BDFJkgnlPRXFHUPah20o20gVYTUgdeziNVhKPmUkzVQq7YotRZK3jsWRJH1moqmrabU7rfB3", + "00ZEZ71/sMiQNGFUs3Fw8xWllqKe9cEcy/1ZB+zVLnvGEwMR7kgvHwsURccUxxR75PPf/Lc/+n+3do6z", + "dnv3u8mvdz/PcslxD1Tglhs2ggGdYlX/BVWK5kt4aNQ3pOjTakvC1y9Yrn8sbPN8e+p/fDCrVeXHr1HT", + "urH+sb3z4tv3nZ/bf3/06MOH9qsn3z/86de3Ozu7P/1QbencZx8tang3vtJ2T0nQ1faXfj7KU/ajP0Nz", + "DZ780QfOnNXCicfrW7mkFAQZrN4HT88hGCjhYvpiYD3mDrcGk3tmaEFqvPHY1Suhdj+RijCqEs7U/SW9", + "k5gruutLxkCkqwciLY3/hcORLspj00FJKwaaGJoUpXqU6jE0KQq1KNTe1dCkkwLmLFl2pvw6cez010x5", + "tub+rO6T2hObUsGP82685EFNpRpzj0rGZxDtneffPfzw/cOHnWfvOy9+erqz+/q39v7Pj5791KgemuCV", + "UEgvSC94JoFnEohviG+Ib9fkTGKKp5bDt9PFBw9cDNzb4yO1uVjt8SkF/4F+ocykIraDqaUi6ViDVa/L", + "P52lxV+gNNqH/EsKMlfgMvqmqaRjbdeECZSDhe6TY/HOeZQbSYyi0YnFkIHyMa2pC321bEwkhyDd6r1H", + "JUudB99NWuosDja1NDgWVjRTjzUbY/MqmPCF8nvh5gwD333y9JxGthsbfMkkh0WDwszqmOVSHvGRC2oF", + "O9yqpfljqlWTgc3RStVzA7dKKX/NWCXdyzX2LTr152SRjJ0P+N8PD14TN0NmBoyDPDarS+36gYT3uvKi", + "oUYVZRKUSVCjikiOSH7nNKoT5Fwm8tNpFl/xKtXZ5j+Vq4zWaALkC64a/5TljksaAC1x0ezYRgjCxqbe", + "0biIRwWvoKEnzH7HIrtN+BDZ4PgbmGRsWQCemM6hoF5UmX1h7N00OCL3xjfxdp/Y9xycQGptdWaaII1/", + "2F1khbO6cUqNe8XKndB1d9WGCGVLynh4wy3ecItCDwo9KPSg0INCDwo9d1LomX+Z7UcoQrMoU9zkwNH7", + "icziI3nCRCczw8be7x/tVg/f7kt5wlnx9Ueb0o5XHYBDgkazkamksdcYGpPqve1tmTLh7oaI4Pdp1Hsp", + "I5pMpdvZ/b7VbrVbO3s//PDDDwAPvj3TdzyYITksxUDSzeL2W0Y1T3IX4qlpv4lY0gRxZESF3ckKT5Jy", + "EKXJi0xButFcCv82jez6URLB0oQKO/eo1nwAD7lsiYKrjqiK4eYGD6mVqtb0x//99//883//i3z69IRZ", + "EcpOz0+f9mwL/8EiownVrvLwjoDAFjyz3eU3MUsVjdwdonZXG0sOcHAUnEVOWO5jPFFjFO9lsJpwoQ2j", + "cYtYeaJUpioV5W4KcjftFlufux/4jOshhISCESdHQ2YrQIW/rgRWpkwzpZv+xdduNLRbPmA7ihn86S5N", + "ipntUrjUKNQlSNC2vhB2asAEUzxqEmbXDdsF/YSdc9s9pXeVUHfL0ilVEBIZqghBqSIm7He2xBCfq2mH", + "13cU9Z1OSSb4HxkjHDCgz5mCHuXCNl0RnWvDRv5yZ9tIOyVC57fIK0Bk6Ek6GCg2cLd7+COFPpjRR8Xw", + "VOcLNLzupEyKPh9kipWnNFQmVTLOwCWI2vchVTyCycvHXV6ahkT2+9AZukXGBb/xeexTQxM5qL1exccu", + "23ezQZE3UhmajF/AXsaTmHCxRdMUOmWrT6EmMdXDnrSvhr+kCqoNcwMSuvO+cigyLohiNNlyUcV8rxAd", + "yZTFJIVyibGrmA7xw2BiUL/fQ/49NqRJH/aPJJEQ39coDivrONCCbdBBygSMGOm86ZYGw7WvpiteSzsl", + "3FQr9CHFxckxMYoPBvASWgyp1d74C6906UYxM1RMD6UlGhd6gdrtremuAC5IH5pWVUFpmti3idGRn3LJ", + "Gc21v0uLxS0C9c0nUnEPLD5htaolALM5jphpwl7qamUr8/3Df2uSnXb739wM23nY/jcf3Y1biBNmmBRr", + "ju1+29oW+f0tozEw3sd707sGl9uxjPT2IOMx09ui3M0Qpv2Us7P7pRGqDETNQPn30DUrJ0N5BtPBv5Ks", + "/EKGOHwQD1rQJDc80oWKrnilx3ePu5fRx/QrVDfF6y6F7bWhjLWPJyiz1L10r8Kzo2qWPth0EDfgjmyo", + "IHgo1a14NcvauG9chWv3YHmSpZWr1myZ2lDDI3dXGwy1v8ibMz3O1KftjtPWuRudFpfPwS1HxYm+mw6y", + "X122bNluS2iRUlIv/MLRay6ioZJCZtrCXO6uJof2NX2cwRxCufkYuHw0YrFlvSQnBaNCI0GH5M9vfZO8", + "dnjGglfmqebURfug/y1HawTdi24SbmECXvQ/Mmnolguf4lfmCpSMl6KgviRhkyltaOX6lglvutZPWC8b", + "DMJMtiIQ7Dxek1ueIPBk3Uszh5ZIwvssyqPEr1xAQw6FvAZ8nP/YCXdmGW6dDhEwlezzkDEXp9KRwTjD", + "x+7BWg2iYapPI7uIchWTlLq4NzaP0BUpzWFA3NZd7ohOmu4RV1vSDWlqSjnMUrv1wEQ6NIqnLNR9MjP3", + "6+x227V3oPz+AThwbpiAGyaKzegbTfqZiBz5cJOXe6KTprrx18e//n8AAAD//8pUYYrAQgwA", +} + +// GetSwagger returns the content of the embedded swagger specification file +// or error if failed to decode +func decodeSpec() ([]byte, error) { + zipped, err := base64.StdEncoding.DecodeString(strings.Join(swaggerSpec, "")) + if err != nil { + return nil, fmt.Errorf("error base64 decoding spec: %w", err) + } + zr, err := gzip.NewReader(bytes.NewReader(zipped)) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %w", err) + } + var buf bytes.Buffer + _, err = buf.ReadFrom(zr) + if err != nil { + return nil, fmt.Errorf("error decompressing spec: %w", err) + } + + return buf.Bytes(), nil +} + +var rawSpec = decodeSpecCached() + +// a naive cached of a decoded swagger spec +func decodeSpecCached() func() ([]byte, error) { + data, err := decodeSpec() + return func() ([]byte, error) { + return data, err + } +} + +// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. +func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { + res := make(map[string]func() ([]byte, error)) + if len(pathToFile) > 0 { + res[pathToFile] = rawSpec + } + + return res +} + +// GetSwagger returns the Swagger specification corresponding to the generated code +// in this file. The external references of Swagger specification are resolved. +// The logic of resolving external references is tightly connected to "import-mapping" feature. +// Externally referenced files must be embedded in the corresponding golang packages. +// Urls can be supported but this task was out of the scope. +func GetSwagger() (swagger *openapi3.T, err error) { + resolvePath := PathToRawSpec("") + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { + pathToFile := url.String() + pathToFile = path.Clean(pathToFile) + getSpec, ok := resolvePath[pathToFile] + if !ok { + err1 := fmt.Errorf("path not found: %s", pathToFile) + return nil, err1 + } + return getSpec() + } + var specData []byte + specData, err = rawSpec() + if err != nil { + return + } + swagger, err = loader.LoadFromData(specData) + if err != nil { + return + } + return +} diff --git a/api/client/go/client.go b/api/client/go/client.go new file mode 100644 index 0000000000000000000000000000000000000000..cb4c39f4ca227b3decf8113287b1305700983153 --- /dev/null +++ b/api/client/go/client.go @@ -0,0 +1,48 @@ +//go:generate go tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=codegen.yaml ../../openapi.cloud.yaml +package openmeter + +import ( + "context" + "fmt" + "net/http" +) + +func NewAuthClientWithResponses(server string, apiSecret string, opts ...ClientOption) (*ClientWithResponses, error) { + o := []ClientOption{WithRequestEditorFn(func(ctx context.Context, req *http.Request) error { + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiSecret)) + return nil + })} + o = append(opts, o...) + + return NewClientWithResponses(server, o...) +} + +func NewAuthClient(server string, apiSecret string, opts ...ClientOption) (*Client, error) { + o := []ClientOption{WithRequestEditorFn(func(ctx context.Context, req *http.Request) error { + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiSecret)) + return nil + })} + o = append(opts, o...) + + return NewClient(server, o...) +} + +// IngestEvents is a wrapper around generated client's IngestEventsWithApplicationCloudeventsPlusJSONBody +func (c *Client) IngestEvent(ctx context.Context, event Event, reqEditors ...RequestEditorFn) (*http.Response, error) { + return c.IngestEventsWithApplicationCloudeventsPlusJSONBody(ctx, event, reqEditors...) +} + +// IngestEvents is a wrapper around generated client's IngestEventsWithApplicationCloudeventsBatchPlusJSONBody +func (c *Client) IngestEventBatch(ctx context.Context, events []Event, reqEditors ...RequestEditorFn) (*http.Response, error) { + return c.IngestEventsWithApplicationCloudeventsBatchPlusJSONBody(ctx, events, reqEditors...) +} + +// IngestEventsWithResponse is a wrapper around generated client's IngestEventsWithApplicationCloudeventsPlusJSONBodyWithResponse +func (c *ClientWithResponses) IngestEventWithResponse(ctx context.Context, event Event, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) { + return c.IngestEventsWithApplicationCloudeventsPlusJSONBodyWithResponse(ctx, event, reqEditors...) +} + +// IngestEventsWithResponse is a wrapper around generated client's IngestEventsWithApplicationCloudeventsBatchPlusJSONBodyWithResponse +func (c *ClientWithResponses) IngestEventBatchWithResponse(ctx context.Context, events []Event, reqEditors ...RequestEditorFn) (*IngestEventsResponse, error) { + return c.IngestEventsWithApplicationCloudeventsBatchPlusJSONBodyWithResponse(ctx, events, reqEditors...) +} diff --git a/api/client/go/client_test.go b/api/client/go/client_test.go new file mode 100644 index 0000000000000000000000000000000000000000..ac322c82b4f325df93c92447f880bae639c7a114 --- /dev/null +++ b/api/client/go/client_test.go @@ -0,0 +1,327 @@ +package openmeter + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + cloudevents "github.com/cloudevents/sdk-go/v2/event" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + + "github.com/openmeterio/openmeter/openmeter/meter" +) + +func TestIngest(t *testing.T) { + ctx := context.Background() + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPost, r.Method) + assert.Equal(t, "/api/v1/events", r.URL.Path) + assert.Equal(t, "application/cloudevents+json", r.Header.Get("Content-Type")) + + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.IngestEventWithResponse(ctx, mockEvent()) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) +} + +func TestIngestBatch(t *testing.T) { + ctx := context.Background() + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPost, r.Method) + assert.Equal(t, "/api/v1/events", r.URL.Path) + assert.Equal(t, "application/cloudevents-batch+json", r.Header.Get("Content-Type")) + + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.IngestEventBatchWithResponse(ctx, []cloudevents.Event{mockEvent()}) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) +} + +func TetsListEvents(t *testing.T) { + ctx := context.Background() + + event := mockEvent() + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v1/events", r.URL.Path) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + err := json.NewEncoder(w).Encode([]Event{event}) + assert.NoError(t, err) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.ListEventsWithResponse(ctx, &ListEventsParams{}) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) + assert.Equal(t, lo.ToPtr([]Event{event}), resp.JSON200) +} + +func TestAuth(t *testing.T) { + ctx := context.Background() + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPost, r.Method) + assert.Equal(t, "/api/v1/events", r.URL.Path) + assert.Equal(t, "application/cloudevents+json", r.Header.Get("Content-Type")) + assert.Equal(t, "Bearer test-api-token", r.Header.Get("Authorization")) + + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewAuthClientWithResponses(server.URL, "test-api-token") + assert.NoError(t, err) + + resp, err := om.IngestEventWithResponse(ctx, mockEvent()) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) +} + +func TestGetMeter(t *testing.T) { + ctx := context.Background() + + meter := Meter{ + Slug: "meter-1", + Description: lo.ToPtr("Test Meter"), + Aggregation: MeterAggregation(meter.MeterAggregationSum), + ValueProperty: lo.ToPtr("$.tokens"), + GroupBy: lo.ToPtr(map[string]string{"model": "$.model", "type": "$.type"}), + } + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v1/meters/meter-1", r.URL.Path) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + err := json.NewEncoder(w).Encode(meter) + assert.NoError(t, err) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.GetMeterWithResponse(ctx, "meter-1") + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) + assert.Equal(t, &meter, resp.JSON200) +} + +func TestListMeters(t *testing.T) { + ctx := context.Background() + + meters := []Meter{ + { + Slug: "meter-1", + Description: lo.ToPtr("Test Meter"), + Aggregation: MeterAggregation(meter.MeterAggregationSum), + ValueProperty: lo.ToPtr("$.tokens"), + GroupBy: lo.ToPtr(map[string]string{"model": "$.model", "type": "$.type"}), + }, + { + Slug: "meter-2", + Description: lo.ToPtr("Test Meter 2"), + Aggregation: MeterAggregation(meter.MeterAggregationSum), + ValueProperty: lo.ToPtr("$.tokens"), + GroupBy: lo.ToPtr(map[string]string{"model": "$.model", "type": "$.type"}), + }, + } + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v1/meters", r.URL.Path) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + err := json.NewEncoder(w).Encode(meters) + assert.NoError(t, err) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.ListMetersWithResponse(ctx, &ListMetersParams{}) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) + assert.Equal(t, &meters, resp.JSON200) +} + +func TestMeterQuery(t *testing.T) { + ctx := context.Background() + + result := MeterQueryResult{ + Data: []MeterQueryRow{ + { + Subject: lo.ToPtr("customer-1"), + WindowStart: time.Now().UTC(), + WindowEnd: time.Now().UTC(), + Value: 123, + }, + }, + } + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v1/meters/meter-1/query", r.URL.Path) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + err := json.NewEncoder(w).Encode(result) + assert.NoError(t, err) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + subjectFilter := []string{"customer-1"} + + resp, err := om.QueryMeterWithResponse(ctx, "meter-1", &QueryMeterParams{ + Subject: &subjectFilter, + }) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) + assert.Equal(t, &result, resp.JSON200) +} + +func TestListSubjects(t *testing.T) { + ctx := context.Background() + + subjects := []Subject{ + { + Key: "customer-1", + DisplayName: lo.ToPtr("Customer 1"), + }, + { + Key: "customer-2", + DisplayName: lo.ToPtr("Customer 2"), + }, + } + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodGet, r.Method) + assert.Equal(t, "/api/v1/subjects", r.URL.Path) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + err := json.NewEncoder(w).Encode(subjects) + assert.NoError(t, err) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.ListSubjectsWithResponse(ctx) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) + assert.Equal(t, &subjects, resp.JSON200) +} + +func TestUpsertSubject(t *testing.T) { + ctx := context.Background() + + subject := Subject{ + Key: "customer-1", + DisplayName: lo.ToPtr("Customer 1"), + } + + // Create a mock server to test the client + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPost, r.Method) + assert.Equal(t, "/api/v1/subjects", r.URL.Path) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + err := json.NewEncoder(w).Encode([]Subject{subject}) + assert.NoError(t, err) + })) + defer server.Close() + + // Create a client with the mock server + om, err := NewClientWithResponses(server.URL) + assert.NoError(t, err) + + resp, err := om.UpsertSubjectWithResponse(ctx, []SubjectUpsert{ + { + Key: "customer-1", + DisplayName: lo.ToPtr("Customer 1"), + }, + }) + assert.NoError(t, err) + + assert.Equal(t, http.StatusOK, resp.StatusCode()) + assert.Equal(t, lo.ToPtr([]Subject{subject}), resp.JSON200) +} + +// mockEvent creates a mock CloudEvent for testing +func mockEvent() cloudevents.Event { + e := cloudevents.New() + eventTime, _ := time.Parse(time.RFC3339, "2024-11-05T22:35:52.457Z") + e.SetTime(eventTime) + e.SetID("ec2672e8-458d-4c5e-8a3c-f3235dd38ba5") + e.SetSource("my-app") + e.SetType("usage-reports") + e.SetSubject("customer-1") + _ = e.SetData("application/json", map[string]string{ + "reports": "123", + "type": "type", + }) + return e +} diff --git a/api/client/go/codegen.yaml b/api/client/go/codegen.yaml new file mode 100644 index 0000000000000000000000000000000000000000..241a0737b2746c93fa4d163b08ca86086785753f --- /dev/null +++ b/api/client/go/codegen.yaml @@ -0,0 +1,11 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/HEAD/configuration-schema.json +package: openmeter +generate: + client: true + models: true + embedded-spec: true +compatibility: + # See: https://github.com/oapi-codegen/oapi-codegen/issues/778 + disable-required-readonly-as-pointer: true + always-prefix-enum-values: true +output: ./client.gen.go diff --git a/api/client/go/error.go b/api/client/go/error.go new file mode 100644 index 0000000000000000000000000000000000000000..918fb4998fc3751e65619285a589ff3ad71aea1a --- /dev/null +++ b/api/client/go/error.go @@ -0,0 +1,14 @@ +package openmeter + +// ErrResponse renderer type for handling all sorts of errors. +// In the best case scenario, the excellent github.com/pkg/errors package +// helps reveal information on the error, setting it on Err, and in the Render() +// method, using it to set the application-specific error code in AppCode. +type ErrResponse struct { + Err error `json:"-"` // low-level runtime error + + StatusCode int `json:"statusCode"` // http response status code + StatusText string `json:"status"` // user-level status message + AppCode int64 `json:"code,omitempty"` // application-specific error code + Message string `json:"message,omitempty"` // application-level error message, for debugging +} diff --git a/api/client/javascript/.gitignore b/api/client/javascript/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5ef3210dc1dbd644340977c4884da269785eefbc --- /dev/null +++ b/api/client/javascript/.gitignore @@ -0,0 +1,23 @@ +# dot-files (.env, .git, ...) + +# logs +logs +*.log +npm-debug.log* + +# dependency directory +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git +node_modules + +# editor +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# build +.duel-cache/ +tsconfig.tsbuildinfo +dist/ diff --git a/api/client/javascript/.npmignore b/api/client/javascript/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..dbfd09b51d0c7d70cd6b165635e9091188aa01b2 --- /dev/null +++ b/api/client/javascript/.npmignore @@ -0,0 +1,27 @@ +# dot-files (.env, .git, .npmrc, ...) +.* + +# logs +logs +*.log +npm-debug.log* + +# dependency directory +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git +node_modules + +# editor +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# source +index.ts +src/ +scripts/ +vitest.config.ts +eslint.config.js +tsconfig*.json diff --git a/api/client/javascript/.npmrc b/api/client/javascript/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..cffe8cdef132f31903a4971117f33f60cd9a56e6 --- /dev/null +++ b/api/client/javascript/.npmrc @@ -0,0 +1 @@ +save-exact=true diff --git a/api/client/javascript/Makefile b/api/client/javascript/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..9df3c869483ec6537e3361259e1f3e33e4f920db --- /dev/null +++ b/api/client/javascript/Makefile @@ -0,0 +1,42 @@ +# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html + +.PHONY: generate +generate: ## Generate JavaScript SDK + $(call print-target) + pnpm --frozen-lockfile install + pnpm run generate + pnpm build + pnpm test + +.PHONY: publish-javascript-sdk +publish-javascript-sdk: ## Publish JavaScript SDK + $(call print-target) + @if [ -z "$$JS_SDK_RELEASE_VERSION" ]; then \ + echo "ERROR: JS_SDK_RELEASE_VERSION is required"; \ + echo "Usage: JS_SDK_RELEASE_VERSION=1.2.3 make publish-javascript-sdk [JS_SDK_RELEASE_TAG=beta]"; \ + exit 1; \ + fi + + @if [ -z "$$JS_SDK_RELEASE_TAG" ]; then \ + echo "ERROR: JS_SDK_RELEASE_TAG is required"; \ + echo "Usage: JS_SDK_RELEASE_VERSION=1.2.3 make publish-javascript-sdk [JS_SDK_RELEASE_TAG=beta]"; \ + exit 1; \ + fi + + pnpm --frozen-lockfile install + pnpm version "$${JS_SDK_RELEASE_VERSION}" --no-git-tag-version + CACHE_BUSTER="$$(date --rfc-3339=seconds)" pnpm publish --no-git-checks --tag "$${JS_SDK_RELEASE_TAG}" + @echo "✅ Published $${JS_SDK_RELEASE_TAG} JavaScript SDK version $${JS_SDK_RELEASE_VERSION} with tag $${JS_SDK_RELEASE_TAG}" + +.PHONY: help +.DEFAULT_GOAL := help +help: + @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' + +# Variable outputting/exporting rules +var-%: ; @echo $($*) +varexport-%: ; @echo $*=$($*) + +define print-target + @printf "Executing target: \033[36m$@\033[0m\n" +endef diff --git a/api/client/javascript/README.md b/api/client/javascript/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a13b4ca40fa74146d8413537fca1a3c3ed16a3b8 --- /dev/null +++ b/api/client/javascript/README.md @@ -0,0 +1,267 @@ +# OpenMeter JavaScript SDK + +## Install + +```sh +npm install --save @openmeter/sdk +``` + +## Configuration for accessing the OpenMeter API + +To use the OpenMeter SDK on your backend, you need to configure `baseUrl` and `apiKey` for OpenMeter Cloud: + +```ts +import { OpenMeter } from '@openmeter/sdk' + +const openmeter = new OpenMeter({ + baseUrl: 'https://openmeter.cloud', + apiKey: 'om_...', +}) +``` + +## Configuration for accessing the OpenMeter Portal API + +To use the OpenMeter Portal SDK on your frontend, you need to configure it use a portal token in your configuration: + +```ts +import { OpenMeter } from '@openmeter/sdk/portal' + +const openmeter = new OpenMeter({ + baseUrl: 'https://openmeter.cloud', + portalToken: 'om_portal_...', +}) +``` + +## Configuration for accessing the OpenMeter React SDK + +To use the OpenMeter React SDK for the portal API, you need to configure a Portal Client and a React Context: + +```ts +import { + OpenMeter, + OpenMeterProvider, + useOpenMeter, +} from '@openmeter/sdk/react' + +function App() { + // get portal token from your backend + const openmeter = new OpenMeter({ + baseUrl: 'https://openmeter.cloud', + portalToken, + }) + + return ( + + + {/* ... */} + + ) +} + +function UsageComponent() { + // get openmeter client from context + const openmeter = useOpenMeter() + + // ... +} +``` + +## Ingest usage events + +```ts +// Ingest a single AI token usage event +await openmeter.events.ingest({ + type: 'ai-tokens', + subject: 'customer-acme-corp', + id: 'evt_01234567', // optional: auto-generated if not provided + source: 'llm-api-gateway', // optional: defaults to '@openmeter/sdk' + time: new Date(), // optional: defaults to current time + data: { + model: 'gpt-4', + type: 'input', + tokens: 1250, + }, +}) + +// Ingest multiple events in a batch for better performance +await openmeter.events.ingest([ + { + type: 'ai-tokens', + subject: 'customer-acme-corp', + data: { model: 'gpt-4', type: 'input', tokens: 850 }, + }, + { + type: 'ai-tokens', + subject: 'customer-acme-corp', + data: { model: 'gpt-4', type: 'output', tokens: 850 }, + }, +]) +``` + +## Client API Reference + +The OpenMeter SDK provides a comprehensive client interface organized into logical groups. Below is a complete reference of all available methods. + +### Overview + +| Namespace | Resource | Operation | Method | Description | +|-----------|----------|-----------|--------|-------------| +| **[Events](#events)** | | | | Track usage by ingesting events | +| | Events | Create | [`openmeter.events.ingest(events)`](./src/client/events.ts#L19) | Ingest a single event or batch of events | +| | Events | Read | [`openmeter.events.list(params?)`](./src/client/events.ts#L41) | List ingested events with advanced filtering | +| | Events | Read | [`openmeter.events.listV2(params?)`](./src/client/events.ts#L60) | List ingested events with advanced filtering (V2) | +| **[Meters](#meters)** | | | | Track and aggregate usage data from events | +| | Meters | Create | [`openmeter.meters.create(meter)`](./src/client/meters.ts#L19) | Create a new meter | +| | Meters | Read | [`openmeter.meters.get(idOrSlug)`](./src/client/meters.ts#L34) | Get a meter by ID or slug | +| | Meters | Read | [`openmeter.meters.list()`](./src/client/meters.ts#L55) | List all meters | +| | Meters | Read | [`openmeter.meters.query(idOrSlug, query?)`](./src/client/meters.ts#L70) | Query usage data | +| | Meters | Update | [`openmeter.meters.update(idOrSlug, meter)`](./src/client/meters.ts#L100) | Update a meter by ID or slug | +| | Meters | Delete | [`openmeter.meters.delete(idOrSlug)`](./src/client/meters.ts#L124) | Delete a meter by ID or slug | +| **[Subjects](#subjects)** | | | | Manage entities that consume resources | +| | Subjects | Create | [`openmeter.subjects.upsert(subjects)`](./src/client/subjects.ts#L21) | Create or update one or multiple subjects | +| | Subjects | Read | [`openmeter.subjects.get(idOrKey)`](./src/client/subjects.ts#L39) | Get a subject by ID or key | +| | Subjects | Read | [`openmeter.subjects.list()`](./src/client/subjects.ts#L60) | List all subjects | +| | Subjects | Delete | [`openmeter.subjects.delete(idOrKey)`](./src/client/subjects.ts#L74) | Delete a subject by ID or key | +| **[Customers](#customers)** | | | | Manage customer subscription lifecycles and plan assignments | +| | Customers | Create | [`openmeter.customers.create(customer)`](./src/client/customers.ts#L37) | Create a new customer | +| | Customers | Read | [`openmeter.customers.get(customerIdOrKey)`](./src/client/customers.ts#L52) | Get a customer by ID or key | +| | Customers | Read | [`openmeter.customers.list(query?)`](./src/client/customers.ts#L123) | List all customers | +| | Customers | Read | [`openmeter.customers.getAccess(customerIdOrKey)`](./src/client/customers.ts#L143) | Get customer access information | +| | Customers | Read | [`openmeter.customers.listSubscriptions(customerIdOrKey, query?)`](./src/client/customers.ts#L169) | List customer subscriptions | +| | Customers | Update | [`openmeter.customers.update(customerIdOrKey, customer)`](./src/client/customers.ts#L75) | Update a customer | +| | Customers | Delete | [`openmeter.customers.delete(customerIdOrKey)`](./src/client/customers.ts#L99) | Delete a customer | +| | Apps | Update | [`openmeter.customers.apps.upsert(customerIdOrKey, appData)`](./src/client/customers.ts#L200) | Upsert app data | +| | Apps | Read | [`openmeter.customers.apps.list(customerIdOrKey)`](./src/client/customers.ts#L228) | List app data | +| | Apps | Delete | [`openmeter.customers.apps.delete(customerIdOrKey, appId)`](./src/client/customers.ts#L254) | Delete app data | +| | Stripe | Update | [`openmeter.customers.stripe.upsert(customerIdOrKey, appDataBase)`](./src/client/customers.ts#L285) | Upsert Stripe app data | +| | Stripe | Read | [`openmeter.customers.stripe.get(customerIdOrKey)`](./src/client/customers.ts#L313) | Get Stripe app data | +| | Stripe | Create | [`openmeter.customers.stripe.createPortalSession(customerIdOrKey, params)`](./src/client/customers.ts#L337) | Create a Stripe customer portal session | +| | Entitlements V1 | Read | [`openmeter.customers.entitlementsV1.value(customerIdOrKey, featureKey)`](./src/client/customers.ts#L372) | Get entitlement value (V1 API) | +| | Entitlements | Read | [`openmeter.customers.entitlements.list(customerIdOrKey)`](./src/client/customers.ts#L401) | List entitlements | +| | Entitlements | Create | [`openmeter.customers.entitlements.create(customerIdOrKey, entitlement)`](./src/client/customers.ts#L428) | Create an entitlement | +| | Entitlements | Read | [`openmeter.customers.entitlements.get(customerIdOrKey, featureKeyOrId)`](./src/client/customers.ts#L454) | Get an entitlement | +| | Entitlements | Delete | [`openmeter.customers.entitlements.delete(customerIdOrKey, entitlementId)`](./src/client/customers.ts#L479) | Delete an entitlement | +| | Entitlements | Update | [`openmeter.customers.entitlements.override(customerIdOrKey, featureKeyOrId, entitlement)`](./src/client/customers.ts#L505) | Override an entitlement | +| | Entitlements | Read | [`openmeter.customers.entitlements.value(customerIdOrKey, featureKeyOrId, query?)`](./src/client/customers.ts#L588) | Get entitlement value | +| | Entitlements | Read | [`openmeter.customers.entitlements.history(customerIdOrKey, featureKeyOrId, query?)`](./src/client/customers.ts#L617) | Get entitlement history | +| | Entitlements | Update | [`openmeter.customers.entitlements.resetUsage(customerIdOrKey, entitlementId, body?)`](./src/client/customers.ts#L653) | Reset usage | +| | Entitlements | Read | [`openmeter.customers.entitlements.listGrants(customerIdOrKey, featureKeyOrId, query?)`](./src/client/customers.ts#L532) | List grants | +| | Entitlements | Create | [`openmeter.customers.entitlements.createGrant(customerIdOrKey, featureKeyOrId, grant)`](./src/client/customers.ts#L561) | Create a grant | +| **[Features](#features)** | | | | Define application capabilities and services | +| | Features | Create | [`openmeter.features.create(feature)`](./src/client/features.ts#L24) | Create a new feature | +| | Features | Read | [`openmeter.features.get(featureIdOrKey)`](./src/client/features.ts#L39) | Get a feature by ID | +| | Features | Read | [`openmeter.features.list(params?)`](./src/client/features.ts#L61) | List all features | +| | Features | Delete | [`openmeter.features.delete(featureIdOrKey)`](./src/client/features.ts#L84) | Delete a feature by ID | +| **[Entitlements (V1)](#entitlements-v1)** | | | | Subject-based usage limits and access controls | +| | Entitlements | Create | [`openmeter.entitlementsV1.create(subjectIdOrKey, entitlement)`](./src/client/entitlements.ts#L40) | Create an entitlement for a subject | +| | Entitlements | Read | [`openmeter.entitlementsV1.get(entitlementId)`](./src/client/entitlements.ts#L68) | Get an entitlement by ID | +| | Entitlements | Read | [`openmeter.entitlementsV1.list(query?)`](./src/client/entitlements.ts#L91) | List all entitlements | +| | Entitlements | Read | [`openmeter.entitlementsV1.value(subjectIdOrKey, featureIdOrKey, query?)`](./src/client/entitlements.ts#L147) | Get the value of an entitlement | +| | Entitlements | Read | [`openmeter.entitlementsV1.history(subjectIdOrKey, entitlementIdOrFeatureKey, query?)`](./src/client/entitlements.ts#L180) | Get the history of an entitlement | +| | Entitlements | Update | [`openmeter.entitlementsV1.override(subjectIdOrKey, entitlementIdOrFeatureKey, override)`](./src/client/entitlements.ts#L213) | Override an entitlement | +| | Entitlements | Update | [`openmeter.entitlementsV1.reset(subjectIdOrKey, entitlementIdOrFeatureKey, reset?)`](./src/client/entitlements.ts#L247) | Reset entitlement usage | +| | Entitlements | Delete | [`openmeter.entitlementsV1.delete(subjectIdOrKey, entitlementId)`](./src/client/entitlements.ts#L116) | Delete an entitlement | +| | Grants | Create | [`openmeter.entitlementsV1.grants.create(subjectIdOrKey, entitlementIdOrFeatureKey, grant)`](./src/client/entitlements.ts#L283) | Create a grant for an entitlement | +| | Grants | Read | [`openmeter.entitlementsV1.grants.list(subjectIdOrKey, entitlementIdOrFeatureKey, query?)`](./src/client/entitlements.ts#L314) | List grants for an entitlement | +| | Grants | Read | [`openmeter.entitlementsV1.grants.listAll(query?)`](./src/client/entitlements.ts#L345) | List all grants | +| | Grants | Delete | [`openmeter.entitlementsV1.grants.void(entitlementId, grantId)`](./src/client/entitlements.ts#L369) | Void a grant | +| **[Entitlements](#entitlements)** | | | | Customer-based entitlements and access controls | +| | Entitlements | Read | [`openmeter.entitlements.list(query?)`](./src/client/entitlements.ts#L404) | List all entitlements (admin purposes) | +| | Entitlements | Read | [`openmeter.entitlements.get(entitlementId)`](./src/client/entitlements.ts#L425) | Get an entitlement by ID | +| | Grants | Read | [`openmeter.entitlements.grants.list(query?)`](./src/client/entitlements.ts#L453) | List all grants (admin purposes) | +| | Grants | Delete | [`openmeter.entitlements.grants.void(grantId)`](./src/client/entitlements.ts#L478) | Void a grant | +| **[Plans](#plans)** | | | | Manage subscription plans and pricing| +| | Plans | Create | [`openmeter.plans.create(plan)`](./src/client/plans.ts#L28) | Create a new plan| +| | Plans | Read | [`openmeter.plans.get(planId)`](./src/client/plans.ts#L44) | Get a plan by ID| +| | Plans | Read | [`openmeter.plans.list(query?)`](./src/client/plans.ts#L66) | List all plans| +| | Plans | Update | [`openmeter.plans.update(planId, plan)`](./src/client/plans.ts#L85) | Update a plan| +| | Plans | Delete | [`openmeter.plans.delete(planId)`](./src/client/plans.ts#L105) | Delete a plan by ID| +| | Plans | Other | [`openmeter.plans.archive(planId)`](./src/client/plans.ts#L123) | Archive a plan| +| | Plans | Other | [`openmeter.plans.publish(planId)`](./src/client/plans.ts#L141) | Publish a plan| +| | Addons | Read | [`openmeter.plans.addons.list(planId)`](./src/client/plans.ts#L168) | List addons| +| | Addons | Create | [`openmeter.plans.addons.create(planId, addon)`](./src/client/plans.ts#L191) | Create an addon| +| | Addons | Read | [`openmeter.plans.addons.get(planId, planAddonId)`](./src/client/plans.ts#L212) | Get an addon by ID| +| | Addons | Update | [`openmeter.plans.addons.update(planId, planAddonId, addon)`](./src/client/plans.ts#L238) | Update an addon| +| | Addons | Delete | [`openmeter.plans.addons.delete(planId, planAddonId)`](./src/client/plans.ts#L263) | Delete an addon by ID| +| **[Addons](#addons)** | | | | Manage standalone addons available across plans| +| | Addons | Create | [`openmeter.addons.create(addon)`](./src/client/addons.ts#L15) | Create a new addon| +| | Addons | Read | [`openmeter.addons.get(addonId)`](./src/client/addons.ts#L48) | Get an addon by ID| +| | Addons | Read | [`openmeter.addons.list(query?)`](./src/client/addons.ts#L30) | List all addons| +| | Addons | Update | [`openmeter.addons.update(addonId, addon)`](./src/client/addons.ts#L64) | Update an addon| +| | Addons | Delete | [`openmeter.addons.delete(addonId)`](./src/client/addons.ts#L84) | Delete an addon by ID| +| | Addons | Other | [`openmeter.addons.publish(addonId)`](./src/client/addons.ts#L99) | Publish an addon| +| | Addons | Other | [`openmeter.addons.archive(addonId)`](./src/client/addons.ts#L114) | Archive an addon| +| **[Subscriptions](#subscriptions)** | | | | Manage customer subscriptions| +| | Subscriptions | Create | [`openmeter.subscriptions.create(body)`](./src/client/subscriptions.ts#L24) | Create a new subscription| +| | Subscriptions | Read | [`openmeter.subscriptions.get(subscriptionId)`](./src/client/subscriptions.ts#L39) | Get a subscription by ID| +| | Subscriptions | Update | [`openmeter.subscriptions.edit(subscriptionId, body)`](./src/client/subscriptions.ts#L61) | Edit a subscription| +| | Subscriptions | Delete | [`openmeter.subscriptions.delete(subscriptionId)`](./src/client/subscriptions.ts#L180) | Delete a subscription (only scheduled)| +| | Subscriptions | Other | [`openmeter.subscriptions.cancel(subscriptionId, body?)`](./src/client/subscriptions.ts#L85) | Cancel a subscription| +| | Subscriptions | Other | [`openmeter.subscriptions.change(subscriptionId, body)`](./src/client/subscriptions.ts#L110) | Change a subscription (upgrade/downgrade)| +| | Subscriptions | Other | [`openmeter.subscriptions.migrate(subscriptionId, body)`](./src/client/subscriptions.ts#L135) | Migrate to a new plan version| +| | Subscriptions | Other | [`openmeter.subscriptions.unscheduleCancelation(subscriptionId)`](./src/client/subscriptions.ts#L158) | Unschedule a subscription cancelation| +| **[Subscription Addons](#subscription-addons)** | | | | Manage addons attached to specific subscriptions| +| | Subscription Addons | Create | [`openmeter.subscriptionAddons.create(subscriptionId, body)`](./src/client/subscription-addons.ts#L16) | Create a new subscription addon| +| | Subscription Addons | Read | [`openmeter.subscriptionAddons.get(subscriptionId, subscriptionAddonId)`](./src/client/subscription-addons.ts#L58) | Get a subscription addon by ID| +| | Subscription Addons | Read | [`openmeter.subscriptionAddons.list(subscriptionId)`](./src/client/subscription-addons.ts#L39) | List all addons of a subscription| +| | Subscription Addons | Update | [`openmeter.subscriptionAddons.update(subscriptionId, subscriptionAddonId, body)`](./src/client/subscription-addons.ts#L82) | Update a subscription addon| +| **[Billing](#billing)** | | | | Comprehensive billing management (profiles, invoices, overrides)| +| | Profiles | Create | [`openmeter.billing.profiles.create(profile)`](./src/client/billing.ts#L42) | Create a billing profile| +| | Profiles | Read | [`openmeter.billing.profiles.get(id)`](./src/client/billing.ts#L60) | Get a billing profile by ID| +| | Profiles | Read | [`openmeter.billing.profiles.list(query?)`](./src/client/billing.ts#L80) | List billing profiles| +| | Profiles | Update | [`openmeter.billing.profiles.update(id, profile)`](./src/client/billing.ts#L101) | Update a billing profile| +| | Profiles | Delete | [`openmeter.billing.profiles.delete(id)`](./src/client/billing.ts#L123) | Delete a billing profile| +| | Invoices | Read | [`openmeter.billing.invoices.list(query?)`](./src/client/billing.ts#L150) | List invoices| +| | Invoices | Read | [`openmeter.billing.invoices.get(id, query?)`](./src/client/billing.ts#L170) | Get an invoice by ID| +| | Invoices | Update | [`openmeter.billing.invoices.update(id, invoice)`](./src/client/billing.ts#L192) | Update an invoice (draft or earlier)| +| | Invoices | Delete | [`openmeter.billing.invoices.delete(id)`](./src/client/billing.ts#L213) | Delete an invoice (draft or earlier)| +| | Invoices | Other | [`openmeter.billing.invoices.advance(id)`](./src/client/billing.ts#L235) | Advance invoice to next status| +| | Invoices | Other | [`openmeter.billing.invoices.approve(id)`](./src/client/billing.ts#L257) | Approve an invoice (sends to customer)| +| | Invoices | Other | [`openmeter.billing.invoices.retry(id, body?)`](./src/client/billing.ts#L278) | Retry advancing after failure| +| | Invoices | Other | [`openmeter.billing.invoices.void(id)`](./src/client/billing.ts#L302) | Void an invoice| +| | Invoices | Other | [`openmeter.billing.invoices.recalculateTax(id)`](./src/client/billing.ts#L325) | Recalculate invoice tax amounts| +| | Invoices | Other | [`openmeter.billing.invoices.simulate(customerId, query?)`](./src/client/billing.ts#L346) | Simulate an invoice for a customer| +| | Invoices | Create | [`openmeter.billing.invoices.createLineItems(customerId, body)`](./src/client/billing.ts#L377) | Create pending line items| +| | Invoices | Create | [`openmeter.billing.invoices.invoicePendingLines(customerId)`](./src/client/billing.ts#L401) | Invoice pending lines| +| | Customers | Create | [`openmeter.billing.customers.createOverride(customerId, body)`](./src/client/billing.ts#L427) | Create or update a customer override| +| | Customers | Read | [`openmeter.billing.customers.getOverride(customerId, id)`](./src/client/billing.ts#L450) | Get a customer override| +| | Customers | Read | [`openmeter.billing.customers.listOverrides(customerId)`](./src/client/billing.ts#L471) | List customer overrides| +| | Customers | Delete | [`openmeter.billing.customers.deleteOverride(customerId, id)`](./src/client/billing.ts#L489) | Delete a customer override| +| **[Apps](#apps)** | | | | Manage integrations and app marketplace| +| | Apps | Read | [`openmeter.apps.list(query?)`](./src/client/apps.ts#L32) | List installed apps| +| | Apps | Read | [`openmeter.apps.get(id)`](./src/client/apps.ts#L50) | Get an app by ID| +| | Apps | Update | [`openmeter.apps.update(id, body)`](./src/client/apps.ts#L69) | Update an app| +| | Apps | Delete | [`openmeter.apps.uninstall(id)`](./src/client/apps.ts#L89) | Uninstall an app| +| | Marketplace | Read | [`openmeter.apps.marketplace.list(query?)`](./src/client/apps.ts#L115) | List available marketplace apps| +| | Marketplace | Read | [`openmeter.apps.marketplace.get(id)`](./src/client/apps.ts#L133) | Get marketplace listing details| +| | Marketplace | Read | [`openmeter.apps.marketplace.getOauth2InstallUrl(id, redirectUrl)`](./src/client/apps.ts#L151) | Get OAuth2 install URL| +| | Marketplace | Other | [`openmeter.apps.marketplace.authorizeOauth2(id, body)`](./src/client/apps.ts#L172) | Authorize OAuth2 code| +| | Marketplace | Create | [`openmeter.apps.marketplace.installWithAPIKey(id, body)`](./src/client/apps.ts#L193) | Install app with API key| +| | Stripe | Create | [`openmeter.apps.stripe.createCheckoutSession(body)`](./src/client/apps.ts#L223) | Create a Stripe checkout session| +| | Stripe | Update | [`openmeter.apps.stripe.updateApiKey(body)`](./src/client/apps.ts#L243) | Update Stripe API key| +| | Custom Invoicing | Other | [`openmeter.apps.customInvoicing.draftSynchronized(body)`](./src/client/apps.ts#L271) | Submit draft synchronization results| +| | Custom Invoicing | Other | [`openmeter.apps.customInvoicing.issuingSynchronized(body)`](./src/client/apps.ts#L295) | Submit issuing synchronization results| +| | Custom Invoicing | Update | [`openmeter.apps.customInvoicing.updatePaymentStatus(invoiceId, body)`](./src/client/apps.ts#L319) | Update payment status| +| **[Notifications](#notifications)** | | | | Set up automated notifications for usage thresholds| +| | Channels | Create | [`openmeter.notifications.channels.create(channel)`](./src/client/notifications.ts#L40) | Create a notification channel| +| | Channels | Read | [`openmeter.notifications.channels.get(channelId)`](./src/client/notifications.ts#L58) | Get a notification channel by ID| +| | Channels | Update | [`openmeter.notifications.channels.update(channelId, channel)`](./src/client/notifications.ts#L84) | Update a notification channel| +| | Channels | Read | [`openmeter.notifications.channels.list(query?)`](./src/client/notifications.ts#L111) | List notification channels| +| | Channels | Delete | [`openmeter.notifications.channels.delete(channelId)`](./src/client/notifications.ts#L131) | Delete a notification channel| +| | Rules | Create | [`openmeter.notifications.rules.create(rule)`](./src/client/notifications.ts#L164) | Create a notification rule| +| | Rules | Read | [`openmeter.notifications.rules.get(ruleId)`](./src/client/notifications.ts#L182) | Get a notification rule by ID| +| | Rules | Update | [`openmeter.notifications.rules.update(ruleId, rule)`](./src/client/notifications.ts#L205) | Update a notification rule| +| | Rules | Read | [`openmeter.notifications.rules.list(query?)`](./src/client/notifications.ts#L229) | List notification rules| +| | Rules | Delete | [`openmeter.notifications.rules.delete(ruleId)`](./src/client/notifications.ts#L249) | Delete a notification rule| +| | Events | Read | [`openmeter.notifications.events.get(eventId)`](./src/client/notifications.ts#L282) | Get a notification event by ID| +| | Events | Read | [`openmeter.notifications.events.list(query?)`](./src/client/notifications.ts#L307) | List notification events| +| **[Portal](#portal)** | | | | Manage consumer portal tokens for customer-facing interfaces| +| | Portal | Create | [`openmeter.portal.create(body)`](./src/client/portal.ts#L19) | Create a consumer portal token| +| | Portal | Read | [`openmeter.portal.list(query?)`](./src/client/portal.ts#L34) | List consumer portal tokens| +| | Portal | Other | [`openmeter.portal.invalidate(query?)`](./src/client/portal.ts#L52) | Invalidate consumer portal tokens| +| **[Info](#info)** | | | | Utility endpoints for system information| +| | Info | Read | [`openmeter.info.listCurrencies()`](./src/client/info.ts#L18) | List all supported currencies| +| | Info | Read | [`openmeter.info.getProgress(id)`](./src/client/info.ts#L32) | Get progress of a long-running operation| +| **[Debug](#debug)** | | | | Debug utilities for monitoring and troubleshooting| +| | Debug | Read | [`openmeter.debug.getMetrics()`](./src/client/debug.ts#L18) | Get event ingestion metrics (OpenMetrics format)| + diff --git a/api/client/javascript/biome.json b/api/client/javascript/biome.json new file mode 100644 index 0000000000000000000000000000000000000000..554f850d47722fb88399d11fae86e57afbbb610f --- /dev/null +++ b/api/client/javascript/biome.json @@ -0,0 +1,67 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "assist": { + "actions": { + "source": { + "organizeImports": "on", + "useSortedKeys": "on" + } + } + }, + "files": { + "ignoreUnknown": false, + "includes": ["**"], + "maxSize": 20000000 + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "useEditorconfig": true + }, + "javascript": { + "formatter": { + "arrowParentheses": "always", + "attributePosition": "auto", + "lineWidth": 80, + "quoteStyle": "single", + "semicolons": "asNeeded", + "trailingCommas": "all" + } + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "style": { + "noInferrableTypes": "error", + "noParameterAssign": "error", + "noUnusedTemplateLiteral": "error", + "noUselessElse": "error", + "useAsConstAssertion": "error", + "useConst": "error", + "useDefaultParameterLast": "error", + "useEnumInitializers": "error", + "useNumberNamespace": "error", + "useSelfClosingElements": "error", + "useSingleVarDeclarator": "error" + } + } + }, + "overrides": [ + { + "assist": { + "actions": { + "source": { + "useSortedKeys": "off" + } + } + }, + "includes": ["package.json"] + } + ], + "vcs": { + "clientKind": "git", + "enabled": true, + "useIgnoreFile": true + } +} diff --git a/api/client/javascript/index.ts b/api/client/javascript/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9cda0f58cfcaed4c17fe588abe1d21681ded0ca8 --- /dev/null +++ b/api/client/javascript/index.ts @@ -0,0 +1 @@ +export * from './src/client/index.js' diff --git a/api/client/javascript/orval.config.ts b/api/client/javascript/orval.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..02acc4e411c5c0faac83f841b534784fe4cbc3f0 --- /dev/null +++ b/api/client/javascript/orval.config.ts @@ -0,0 +1,38 @@ +import { defineConfig } from 'orval' + +export default defineConfig({ + openmeter: { + input: { + target: '../../openapi.cloud.yaml', + }, + output: { + formatter: 'biome', + clean: true, + client: 'zod', + mode: 'single', + namingConvention: 'PascalCase', + override: { + useDates: true, + zod: { + coerce: { + body: true, + header: false, + param: true, + query: true, + response: false, + }, + generate: { + body: true, + header: false, + param: true, + query: true, + response: false, + }, + }, + }, + propertySortOrder: 'Alphabetical', + target: './src/zod/index.ts', + tsconfig: './tsconfig.json', + }, + }, +}) diff --git a/api/client/javascript/package.json b/api/client/javascript/package.json new file mode 100644 index 0000000000000000000000000000000000000000..32c4804f0c9875d226c3b39cc2067702bb704e62 --- /dev/null +++ b/api/client/javascript/package.json @@ -0,0 +1,102 @@ +{ + "name": "@openmeter/sdk", + "version": "0.0.0", + "description": "Client for OpenMeter: Real-Time and Scalable Usage Metering", + "license": "Apache 2.0", + "homepage": "https://openmeter.io", + "repository": { + "type": "git", + "url": "https://github.com/openmeterio/openmeter.git", + "directory": "api/client/javascript" + }, + "type": "module", + "files": [ + "dist" + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "default": "./dist/index.js" + }, + "./portal": { + "import": { + "types": "./dist/src/portal/index.d.ts", + "default": "./dist/src/portal/index.js" + }, + "require": { + "types": "./dist/cjs/src/portal/index.d.cts", + "default": "./dist/cjs/src/portal/index.cjs" + }, + "default": "./dist/src/portal/index.js" + }, + "./react": { + "import": { + "types": "./dist/src/react/context.d.ts", + "default": "./dist/src/react/context.js" + }, + "default": "./dist/src/react/context.js" + }, + "./zod": { + "import": { + "types": "./dist/src/zod/index.d.ts", + "default": "./dist/src/zod/index.js" + }, + "require": { + "types": "./dist/cjs/src/zod/index.d.cts", + "default": "./dist/cjs/src/zod/index.cjs" + }, + "default": "./dist/src/zod/index.js" + } + }, + "scripts": { + "build": "duel", + "format": "biome format --write .", + "generate": "pnpm run generate:client && pnpm run generate:zod", + "generate:client": "tsx scripts/generate.ts && biome format --write ./src/client/schemas.ts", + "generate:zod": "orval && tsx scripts/add-as-const.ts && biome lint --write ./src/zod/index.ts && biome format --write ./src/zod/index.ts", + "lint": "tsc --noEmit && biome lint .", + "prepublishOnly": "pnpm run generate && pnpm run build && pnpm run lint && pnpm run test", + "pretest": "pnpm run build", + "test": "vitest --run", + "test:watch": "vitest --watch" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "openapi-fetch": "0.17.0", + "openapi-typescript-helpers": "0.1.0" + }, + "devDependencies": { + "@biomejs/biome": "2.4.16", + "@fetch-mock/vitest": "0.2.18", + "@knighted/duel": "4.1.0", + "@types/node": "25.9.2", + "@types/node-fetch": "2.6.13", + "@types/react": "19.2.17", + "fetch-mock": "12.6.0", + "openapi-typescript": "7.13.0", + "orval": "8.15.0", + "prettier": "3.8.3", + "react": "19.2.7", + "rollup": "4.61.1", + "tslib": "2.8.1", + "tsx": "4.22.4", + "typescript": "5.9.3", + "vitest": "4.1.8", + "zod": "4.4.3" + }, + "packageManager": "pnpm@11.1.2+sha512.415a1cc25974731e75455c1468371be74c5aa5fb7621b50d4056d222451609f11412f23fd602e6169f1e060466641f798597e1be961a10688836a67b16569499", + "peerDependencies": { + "react": ">=18.0.0" + } +} diff --git a/api/client/javascript/patches/openapi-typescript.patch b/api/client/javascript/patches/openapi-typescript.patch new file mode 100644 index 0000000000000000000000000000000000000000..440b0c15ed5be90aa82d800063726bfc59129eb2 --- /dev/null +++ b/api/client/javascript/patches/openapi-typescript.patch @@ -0,0 +1,7122 @@ +diff --git a/bin/cli.js b/bin/cli.js +index e07ff7b33d0b867c9a4719c1e2d98b0a88c66c58..31be6e7958e2ce66d79d9926181696c1895cb2c8 100755 +--- a/bin/cli.js ++++ b/bin/cli.js +@@ -4,6 +4,7 @@ import fs from "node:fs"; + import path from "node:path"; + import { performance } from "node:perf_hooks"; + import { createConfig, findConfig, loadConfig } from "@redocly/openapi-core"; ++import { kebabCase } from "scule"; + import parser from "yargs-parser"; + import openapiTS, { astToString, COMMENT_HEADER, c, error, formatTime, warn } from "../dist/index.mjs"; + +@@ -31,8 +32,8 @@ Options + --path-params-as-types Convert paths to template literal types + --alphabetize Sort object keys alphabetically + --exclude-deprecated Exclude deprecated types +- --root-types (optional) Export schemas types at root level +- --root-types-no-schema-prefix (optional) ++ --root-types Export schemas types at root level ++ --root-types-no-schema-prefix + Do not add "Schema" prefix to types at the root level (should only be used with --root-types) + --root-types-keep-casing Keep casing of root types (should only be used with --root-types) + --make-paths-enum Generate ApiPaths enum for all paths +@@ -71,32 +72,34 @@ if (args.includes("--root-types-keep-casing") && !args.includes("--root-types")) + console.warn("--root-types-keep-casing has no effect without --root-types flag"); + } + ++const BOOLEAN_FLAGS = [ ++ "additionalProperties", ++ "alphabetize", ++ "arrayLength", ++ "check", ++ "conditionalEnums", ++ "contentNever", ++ "dedupeEnums", ++ "defaultNonNullable", ++ "emptyObjectsUnknown", ++ "enum", ++ "enumValues", ++ "excludeDeprecated", ++ "exportType", ++ "generatePathParams", ++ "help", ++ "immutable", ++ "makePathsEnum", ++ "pathParamsAsTypes", ++ "propertiesRequiredByDefault", ++ "readWriteMarkers", ++ "rootTypes", ++ "rootTypesKeepCasing", ++ "rootTypesNoSchemaPrefix", ++]; ++ + const flags = parser(args, { +- boolean: [ +- "additionalProperties", +- "alphabetize", +- "arrayLength", +- "contentNever", +- "defaultNonNullable", +- "propertiesRequiredByDefault", +- "emptyObjectsUnknown", +- "enum", +- "enumValues", +- "conditionalEnums", +- "dedupeEnums", +- "check", +- "excludeDeprecated", +- "exportType", +- "help", +- "immutable", +- "pathParamsAsTypes", +- "rootTypes", +- "rootTypesNoSchemaPrefix", +- "rootTypesKeepCasing", +- "makePathsEnum", +- "generatePathParams", +- "readWriteMarkers", +- ], ++ boolean: BOOLEAN_FLAGS, + string: ["output", "redocly"], + alias: { + redocly: ["c"], +@@ -136,36 +139,10 @@ function checkStaleOutput(current, outputPath) { + + /** + * @param {string | URL} schema +- * @param {@type import('@redocly/openapi-core').Config} redocly ++ * @param {@type import('@redocly/openapi-core').Config} config + */ +-async function generateSchema(schema, { redocly, silent = false }) { +- return `${COMMENT_HEADER}${astToString( +- await openapiTS(schema, { +- additionalProperties: flags.additionalProperties, +- alphabetize: flags.alphabetize, +- arrayLength: flags.arrayLength, +- contentNever: flags.contentNever, +- propertiesRequiredByDefault: flags.propertiesRequiredByDefault, +- defaultNonNullable: flags.defaultNonNullable, +- emptyObjectsUnknown: flags.emptyObjectsUnknown, +- enum: flags.enum, +- enumValues: flags.enumValues, +- conditionalEnums: flags.conditionalEnums, +- dedupeEnums: flags.dedupeEnums, +- excludeDeprecated: flags.excludeDeprecated, +- exportType: flags.exportType, +- immutable: flags.immutable, +- pathParamsAsTypes: flags.pathParamsAsTypes, +- rootTypes: flags.rootTypes, +- rootTypesNoSchemaPrefix: flags.rootTypesNoSchemaPrefix, +- rootTypesKeepCasing: flags.rootTypesKeepCasing, +- makePathsEnum: flags.makePathsEnum, +- generatePathParams: flags.generatePathParams, +- readWriteMarkers: flags.readWriteMarkers, +- redocly, +- silent, +- }), +- )}`; ++async function generateSchema(schema, config) { ++ return `${COMMENT_HEADER}${astToString(await openapiTS(schema, config))}`; + } + + /** pretty-format error message but also throw */ +@@ -230,6 +207,8 @@ async function main() { + await Promise.all( + Object.entries(redocly.apis).map(async ([name, api]) => { + let configRoot = CWD; ++ ++ const config = { ...flags, redocly }; + if (redocly.configFile) { + // note: this will be absolute if --redoc is passed; otherwise, relative + configRoot = path.isAbsolute(redocly.configFile) +@@ -241,7 +220,18 @@ async function main() { + `API ${name} is missing an \`${REDOC_CONFIG_KEY}.output\` key. See https://openapi-ts.dev/cli/#multiple-schemas.`, + ); + } +- const result = await generateSchema(new URL(api.root, configRoot), { redocly }); ++ ++ if (api[REDOC_CONFIG_KEY]) { ++ for (const name of BOOLEAN_FLAGS) { ++ if (typeof api[REDOC_CONFIG_KEY][name] === "boolean") { ++ config[name] = api[REDOC_CONFIG_KEY][name]; ++ } else if (typeof api[REDOC_CONFIG_KEY][kebabCase(name)] === "boolean") { ++ config[name] = api[REDOC_CONFIG_KEY][kebabCase(name)]; ++ } ++ } ++ } ++ const result = await generateSchema(new URL(api.root, configRoot), config); ++ + const outFile = new URL(api[REDOC_CONFIG_KEY].output, configRoot); + checkStaleOutput(result, outFile); + fs.mkdirSync(new URL(".", outFile), { recursive: true }); +@@ -254,6 +244,7 @@ async function main() { + // handle stdin + else if (!input) { + const result = await generateSchema(process.stdin, { ++ ...flags, + redocly, + silent: outputType === OUTPUT_STDOUT, + }); +@@ -278,6 +269,7 @@ async function main() { + ); + } + const result = await generateSchema(new URL(input, CWD), { ++ ...flags, + redocly, + silent: outputType === OUTPUT_STDOUT, + }); +diff --git a/dist/index.d.cts b/dist/index.d.cts +index be9d8f0f771cbe5e77dd36e5b90c952800e12060..a038dd93ee68e5cd291f22ca7ef2cd2e45c105db 100644 +--- a/dist/index.d.cts ++++ b/dist/index.d.cts +@@ -206,6 +206,7 @@ type SchemaObject = { + const?: unknown; + default?: unknown; + format?: string; ++ additionalProperties?: boolean | Record | SchemaObject | ReferenceObject; + nullable?: boolean; + oneOf?: (SchemaObject | ReferenceObject)[]; + allOf?: (SchemaObject | ReferenceObject)[]; +diff --git a/dist/index.d.mts b/dist/index.d.mts +index 2af2cee65dfe6973f592e6e9dc3399de1a641cbf..6729248654aaedf683747a9f98a3829d38266c4a 100644 +--- a/dist/index.d.mts ++++ b/dist/index.d.mts +@@ -206,6 +206,7 @@ type SchemaObject = { + const?: unknown; + default?: unknown; + format?: string; ++ additionalProperties?: boolean | Record | SchemaObject | ReferenceObject; + nullable?: boolean; + oneOf?: (SchemaObject | ReferenceObject)[]; + allOf?: (SchemaObject | ReferenceObject)[]; +diff --git a/dist/index.d.ts b/dist/index.d.ts +index be9d8f0f771cbe5e77dd36e5b90c952800e12060..a038dd93ee68e5cd291f22ca7ef2cd2e45c105db 100644 +--- a/dist/index.d.ts ++++ b/dist/index.d.ts +@@ -206,6 +206,7 @@ type SchemaObject = { + const?: unknown; + default?: unknown; + format?: string; ++ additionalProperties?: boolean | Record | SchemaObject | ReferenceObject; + nullable?: boolean; + oneOf?: (SchemaObject | ReferenceObject)[]; + allOf?: (SchemaObject | ReferenceObject)[]; +diff --git a/dist/transform/schema-object.cjs b/dist/transform/schema-object.cjs +index 7142e84a60d4856d42179e8d6dc80ec78ea6e881..a246e622559f6599e4bb5f23a8ff306e8dc7c9a8 100644 +--- a/dist/transform/schema-object.cjs ++++ b/dist/transform/schema-object.cjs +@@ -39,80 +39,84 @@ function transformSchemaObjectWithComposition(schemaObject, options, fromAdditio + if (schemaObject.const !== null && schemaObject.const !== void 0) { + return ts.tsLiteral(schemaObject.const); + } +- if (Array.isArray(schemaObject.enum) && (!("type" in schemaObject) || schemaObject.type !== "object") && !("properties" in schemaObject) && !("additionalProperties" in schemaObject)) { +- if (shouldTransformToTsEnum(options, schemaObject)) { +- let enumName = refUtils_js.parseRef(options.path ?? "").pointer.join("/"); +- enumName = enumName.replace("components/schemas", ""); +- const metadata = schemaObject.enum.map((_, i) => ({ +- name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], +- description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i] +- })); +- let hasNull = false; +- const validSchemaEnums = schemaObject.enum.filter((enumValue) => { +- if (enumValue === null) { +- hasNull = true; +- return false; ++ if (Array.isArray(schemaObject.enum) && (!("type" in schemaObject) || schemaObject.type !== "object") && !("properties" in schemaObject)) { ++ const hasAdditionalProperties = "additionalProperties" in schemaObject && !!schemaObject.additionalProperties; ++ if (!hasAdditionalProperties || schemaObject.type === "string" && hasAdditionalProperties) { ++ if (shouldTransformToTsEnum(options, schemaObject)) { ++ let enumName = refUtils_js.parseRef(options.path ?? "").pointer.join("/"); ++ enumName = enumName.replace("components/schemas", ""); ++ const metadata = schemaObject.enum.map((_, i) => ({ ++ name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], ++ description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i] ++ })); ++ let hasNull = false; ++ const validSchemaEnums = schemaObject.enum.filter((enumValue) => { ++ if (enumValue === null) { ++ hasNull = true; ++ return false; ++ } ++ return true; ++ }); ++ const enumType2 = ts.tsEnum(enumName, validSchemaEnums, metadata, { ++ shouldCache: options.ctx.dedupeEnums, ++ export: true ++ // readonly: TS enum do not support the readonly modifier ++ }); ++ if (!options.ctx.injectFooter.includes(enumType2)) { ++ options.ctx.injectFooter.push(enumType2); + } +- return true; +- }); +- const enumType2 = ts.tsEnum(enumName, validSchemaEnums, metadata, { +- shouldCache: options.ctx.dedupeEnums, +- export: true +- // readonly: TS enum do not support the readonly modifier +- }); +- if (!options.ctx.injectFooter.includes(enumType2)) { +- options.ctx.injectFooter.push(enumType2); ++ const ref = ts__default.factory.createTypeReferenceNode(enumType2.name); ++ const finalType2 = hasNull ? ts.tsUnion([ref, ts.NULL]) : ref; ++ return applyAdditionalPropertiesToEnum(hasAdditionalProperties, finalType2, schemaObject); + } +- const ref = ts__default.factory.createTypeReferenceNode(enumType2.name); +- return hasNull ? ts.tsUnion([ref, ts.NULL]) : ref; +- } +- const enumType = schemaObject.enum.map(ts.tsLiteral); +- if (Array.isArray(schemaObject.type) && schemaObject.type.includes("null") || schemaObject.nullable) { +- enumType.push(ts.NULL); +- } +- const unionType = ts.tsUnion(enumType); +- if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { +- const parsed = refUtils_js.parseRef(options.path ?? ""); +- let enumValuesVariableName = parsed.pointer.join("/"); +- enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); +- enumValuesVariableName = `${enumValuesVariableName}Values`; +- const cleanedPointer = []; +- const extractProperties = []; +- for (let i = 0; i < parsed.pointer.length; i++) { +- const segment = parsed.pointer[i]; +- if ((segment === "anyOf" || segment === "oneOf") && i < parsed.pointer.length - 1) { +- const next = parsed.pointer[i + 1]; +- if (/^\d+$/.test(next)) { +- i++; +- const remainingSegments = parsed.pointer.slice(i + 1); +- for (const seg of remainingSegments) { +- if (seg !== "anyOf" && seg !== "oneOf" && !/^\d+$/.test(seg)) { +- extractProperties.push(seg); ++ const enumType = schemaObject.enum.map(ts.tsLiteral); ++ if (Array.isArray(schemaObject.type) && schemaObject.type.includes("null") || schemaObject.nullable) { ++ enumType.push(ts.NULL); ++ } ++ const unionType = applyAdditionalPropertiesToEnum(hasAdditionalProperties, ts.tsUnion(enumType), schemaObject); ++ if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { ++ const parsed = refUtils_js.parseRef(options.path ?? ""); ++ let enumValuesVariableName = parsed.pointer.join("/"); ++ enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); ++ enumValuesVariableName = `${enumValuesVariableName}Values`; ++ const cleanedPointer = []; ++ const extractProperties = []; ++ for (let i = 0; i < parsed.pointer.length; i++) { ++ const segment = parsed.pointer[i]; ++ if ((segment === "anyOf" || segment === "oneOf") && i < parsed.pointer.length - 1) { ++ const next = parsed.pointer[i + 1]; ++ if (/^\d+$/.test(next)) { ++ i++; ++ const remainingSegments = parsed.pointer.slice(i + 1); ++ for (const seg of remainingSegments) { ++ if (seg !== "anyOf" && seg !== "oneOf" && !/^\d+$/.test(seg)) { ++ extractProperties.push(seg); ++ } + } ++ continue; + } +- continue; + } ++ cleanedPointer.push(segment); + } +- cleanedPointer.push(segment); ++ const cleanedRefPath = utils.createRef(cleanedPointer); ++ const enumValuesArray = ts.tsArrayLiteralExpression( ++ enumValuesVariableName, ++ // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type ++ fromAdditionalProperties ? ts__default.factory.createIndexedAccessTypeNode( ++ ts.oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), ++ ts__default.factory.createTypeReferenceNode(ts__default.factory.createIdentifier("string")) ++ ) : ts.oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), ++ schemaObject.enum, ++ { ++ export: true, ++ readonly: true, ++ injectFooter: options.ctx.injectFooter ++ } ++ ); ++ options.ctx.injectFooter.push(enumValuesArray); + } +- const cleanedRefPath = utils.createRef(cleanedPointer); +- const enumValuesArray = ts.tsArrayLiteralExpression( +- enumValuesVariableName, +- // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type +- fromAdditionalProperties ? ts__default.factory.createIndexedAccessTypeNode( +- ts.oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), +- ts__default.factory.createTypeReferenceNode(ts__default.factory.createIdentifier("string")) +- ) : ts.oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), +- schemaObject.enum, +- { +- export: true, +- readonly: true, +- injectFooter: options.ctx.injectFooter +- } +- ); +- options.ctx.injectFooter.push(enumValuesArray); ++ return unionType; + } +- return unionType; + } + function collectUnionCompositions(items, unionKey) { + const output = []; +@@ -148,12 +152,7 @@ function transformSchemaObjectWithComposition(schemaObject, options, fromAdditio + } + itemType = transformSchemaObject({ ...item, required: itemRequired }, options); + } +- const discriminator = "$ref" in item && options.ctx.discriminators.objects[item.$ref] || item.discriminator; +- if (discriminator) { +- output.push(ts.tsOmit(itemType, [discriminator.propertyName])); +- } else { +- output.push(itemType); +- } ++ output.push(itemType); + } + return output; + } +@@ -322,7 +321,7 @@ function transformSchemaObjectCore(schemaObject, options) { + } + } + if ("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length || "additionalProperties" in schemaObject && schemaObject.additionalProperties || "patternProperties" in schemaObject && schemaObject.patternProperties || "$defs" in schemaObject && schemaObject.$defs) { +- if (Object.keys(schemaObject.properties ?? {}).length) { ++ if ("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject?.properties).length) { + for (const [k, v] of utils.getEntries(schemaObject.properties ?? {}, options.ctx)) { + if (typeof v !== "object" && typeof v !== "boolean" || Array.isArray(v)) { + throw new Error( +@@ -383,7 +382,7 @@ function transformSchemaObjectCore(schemaObject, options) { + coreObjectType.push(property); + } + } +- if (schemaObject.$defs && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { ++ if ("$defs" in schemaObject && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { + const defKeys = []; + for (const [k, v] of Object.entries(schemaObject.$defs)) { + const defReadOnly = "readOnly" in v && !!v.readOnly; +@@ -433,7 +432,8 @@ function transformSchemaObjectCore(schemaObject, options) { + } + const hasExplicitAdditionalProperties = typeof schemaObject.additionalProperties === "object" && Object.keys(schemaObject.additionalProperties).length; + const hasImplicitAdditionalProperties = schemaObject.additionalProperties === true || typeof schemaObject.additionalProperties === "object" && Object.keys(schemaObject.additionalProperties).length === 0; +- const hasExplicitPatternProperties = typeof schemaObject.patternProperties === "object" && Object.keys(schemaObject.patternProperties).length; ++ const patternProperties = hasKey(schemaObject, "patternProperties") ? schemaObject.patternProperties : void 0; ++ const hasExplicitPatternProperties = typeof patternProperties === "object" && patternProperties !== null && Object.keys(patternProperties).length > 0; + const stringIndexTypes = []; + if (hasExplicitAdditionalProperties) { + stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties, options, true)); +@@ -441,8 +441,11 @@ function transformSchemaObjectCore(schemaObject, options) { + if (hasImplicitAdditionalProperties || !schemaObject.additionalProperties && options.ctx.additionalProperties) { + stringIndexTypes.push(ts.UNKNOWN); + } +- if (hasExplicitPatternProperties) { +- for (const [_, v] of utils.getEntries(schemaObject.patternProperties ?? {}, options.ctx)) { ++ if (hasExplicitPatternProperties && patternProperties && typeof patternProperties === "object") { ++ for (const [_, v] of utils.getEntries( ++ patternProperties, ++ options.ctx ++ )) { + stringIndexTypes.push(transformSchemaObject(v, options)); + } + } +@@ -484,6 +487,13 @@ function transformSchemaObjectCore(schemaObject, options) { + function hasKey(possibleObject, key) { + return typeof possibleObject === "object" && possibleObject !== null && key in possibleObject; + } ++function applyAdditionalPropertiesToEnum(hasAdditionalProperties, unionType, schemaObject) { ++ if (hasAdditionalProperties && schemaObject.type === "string") { ++ const stringAndEmptyObject = ts.tsIntersection([ts.STRING, ts__default.factory.createTypeLiteralNode([])]); ++ return ts.tsUnion([unionType, stringAndEmptyObject]); ++ } ++ return unionType; ++} + function wrapWithReadWriteMarker(type, readOnly, writeOnly, ctx) { + if (!ctx.readWriteMarkers || readOnly && writeOnly) { + return type; +diff --git a/dist/transform/schema-object.cjs.map b/dist/transform/schema-object.cjs.map +index 4039111f61f3fc47e1e7c6ed894a09e86490ba9c..27bf29dc83d8f29bad013bcf15a04c4458ed85cd 100644 +--- a/dist/transform/schema-object.cjs.map ++++ b/dist/transform/schema-object.cjs.map +@@ -1 +1 @@ +-{"version":3,"file":"schema-object.cjs","sources":["../../src/transform/schema-object.ts"],"sourcesContent":["import { parseRef } from \"@redocly/openapi-core/lib/ref-utils.js\";\nimport ts from \"typescript\";\nimport {\n addJSDocComment,\n BOOLEAN,\n NEVER,\n NULL,\n NUMBER,\n oapiRef,\n QUESTION_TOKEN,\n STRING,\n tsArrayLiteralExpression,\n tsEnum,\n tsIntersection,\n tsIsPrimitive,\n tsLiteral,\n tsModifiers,\n tsNullable,\n tsOmit,\n tsPropertyIndex,\n tsRecord,\n tsUnion,\n tsWithRequired,\n UNDEFINED,\n UNKNOWN,\n} from \"../lib/ts.js\";\nimport { createDiscriminatorProperty, createRef, getEntries } from \"../lib/utils.js\";\nimport type { ReferenceObject, SchemaObject, TransformNodeOptions } from \"../types.js\";\n\n/**\n * Transform SchemaObject nodes (4.8.24)\n * @see https://spec.openapis.org/oas/v3.1.0#schema-object\n */\nexport default function transformSchemaObject(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n const type = transformSchemaObjectWithComposition(schemaObject, options, fromAdditionalProperties);\n if (typeof options.ctx.postTransform === \"function\") {\n const postTransformResult = options.ctx.postTransform(type, options);\n if (postTransformResult) {\n return postTransformResult;\n }\n }\n return type;\n}\n\n/**\n * Transform SchemaObjects\n */\nexport function transformSchemaObjectWithComposition(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n /**\n * Unexpected types & edge cases\n */\n\n // missing/falsy type returns `never`\n if (!schemaObject) {\n return NEVER;\n }\n // `true` returns `unknown` (this exists, but is untyped)\n if ((schemaObject as unknown) === true) {\n return UNKNOWN;\n }\n // for any other unexpected type, throw error\n if (Array.isArray(schemaObject) || typeof schemaObject !== \"object\") {\n throw new Error(\n `Expected SchemaObject, received ${Array.isArray(schemaObject) ? \"Array\" : typeof schemaObject} at ${options.path}`,\n );\n }\n\n /**\n * ReferenceObject\n */\n if (\"$ref\" in schemaObject) {\n return oapiRef(schemaObject.$ref);\n }\n\n /**\n * const (valid for any type)\n */\n if (schemaObject.const !== null && schemaObject.const !== undefined) {\n return tsLiteral(schemaObject.const);\n }\n\n /**\n * enum (non-objects)\n * note: enum is valid for any type, but for objects, handle in oneOf below\n */\n if (\n Array.isArray(schemaObject.enum) &&\n (!(\"type\" in schemaObject) || schemaObject.type !== \"object\") &&\n !(\"properties\" in schemaObject) &&\n !(\"additionalProperties\" in schemaObject)\n ) {\n // hoist enum to top level if string/number enum and option is enabled\n if (shouldTransformToTsEnum(options, schemaObject)) {\n let enumName = parseRef(options.path ?? \"\").pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumName = enumName.replace(\"components/schemas\", \"\");\n const metadata = schemaObject.enum.map((_, i) => ({\n name: schemaObject[\"x-enum-varnames\"]?.[i] ?? schemaObject[\"x-enumNames\"]?.[i],\n description: schemaObject[\"x-enum-descriptions\"]?.[i] ?? schemaObject[\"x-enumDescriptions\"]?.[i],\n }));\n\n // enums can contain null values, but dont want to output them\n let hasNull = false;\n const validSchemaEnums = schemaObject.enum.filter((enumValue) => {\n if (enumValue === null) {\n hasNull = true;\n return false;\n }\n\n return true;\n });\n const enumType = tsEnum(enumName, validSchemaEnums as (string | number)[], metadata, {\n shouldCache: options.ctx.dedupeEnums,\n export: true,\n // readonly: TS enum do not support the readonly modifier\n });\n if (!options.ctx.injectFooter.includes(enumType)) {\n options.ctx.injectFooter.push(enumType);\n }\n const ref = ts.factory.createTypeReferenceNode(enumType.name);\n return hasNull ? tsUnion([ref, NULL]) : ref;\n }\n const enumType = schemaObject.enum.map(tsLiteral);\n if ((Array.isArray(schemaObject.type) && schemaObject.type.includes(\"null\")) || schemaObject.nullable) {\n enumType.push(NULL);\n }\n\n const unionType = tsUnion(enumType);\n\n // hoist array with valid enum values to top level if string/number enum and option is enabled\n if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === \"string\" || typeof v === \"number\")) {\n const parsed = parseRef(options.path ?? \"\");\n let enumValuesVariableName = parsed.pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumValuesVariableName = enumValuesVariableName.replace(\"components/schemas\", \"\");\n enumValuesVariableName = `${enumValuesVariableName}Values`;\n\n // build a ref path for the type that ignores union indices (anyOf/oneOf) so\n // type references remain stable even when names include union positions\n const cleanedPointer: string[] = [];\n // Track ALL properties after a oneOf/anyOf that need Extract<> narrowing.\n // We apply Extract<> before EVERY property access after a union index because:\n // - When the property exists on ALL variants, Extract<> is a no-op (returns same type)\n // - When the property only exists on SOME variants, it correctly narrows the union\n // - When both variants have same property name but different inner schemas,\n // we still narrow at each level to handle nested unions correctly\n // This robust approach handles both simple and complex union structures.\n const extractProperties: string[] = [];\n for (let i = 0; i < parsed.pointer.length; i++) {\n // Example: #/paths/analytics/data/get/responses/400/content/application/json/anyOf/0/message\n const segment = parsed.pointer[i];\n if ((segment === \"anyOf\" || segment === \"oneOf\") && i < parsed.pointer.length - 1) {\n const next = parsed.pointer[i + 1];\n if (/^\\d+$/.test(next)) {\n // If we encounter something like \"anyOf/0\", we want to skip that part of the path\n i++;\n // Collect ALL remaining segments after the union index.\n // Each one will be wrapped with Extract<> to safely narrow the type\n // at each level, handling both top-level and nested union variants.\n const remainingSegments = parsed.pointer.slice(i + 1);\n for (const seg of remainingSegments) {\n // Skip union keywords and indices, only add actual property names\n if (seg !== \"anyOf\" && seg !== \"oneOf\" && !/^\\d+$/.test(seg)) {\n extractProperties.push(seg);\n }\n }\n continue;\n }\n }\n cleanedPointer.push(segment);\n }\n const cleanedRefPath = createRef(cleanedPointer);\n\n const enumValuesArray = tsArrayLiteralExpression(\n enumValuesVariableName,\n // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type\n fromAdditionalProperties\n ? ts.factory.createIndexedAccessTypeNode(\n oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"string\")),\n )\n : oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n schemaObject.enum as (string | number)[],\n {\n export: true,\n readonly: true,\n injectFooter: options.ctx.injectFooter,\n },\n );\n\n options.ctx.injectFooter.push(enumValuesArray);\n }\n\n return unionType;\n }\n\n /**\n * Object + composition (anyOf/allOf/oneOf) types\n */\n\n /** Collect oneOf/anyOf */\n function collectUnionCompositions(items: (SchemaObject | ReferenceObject)[], unionKey: \"anyOf\" | \"oneOf\") {\n const output: ts.TypeNode[] = [];\n for (const [index, item] of items.entries()) {\n output.push(\n transformSchemaObject(item, {\n ...options,\n // include index in path so generated names from nested enums/enumValues are unique\n path: createRef([options.path, unionKey, String(index)]),\n }),\n );\n }\n\n return output;\n }\n\n /** Collect allOf with Omit<> for discriminators */\n function collectAllOfCompositions(items: (SchemaObject | ReferenceObject)[], required?: string[]): ts.TypeNode[] {\n const output: ts.TypeNode[] = [];\n for (const item of items) {\n let itemType: ts.TypeNode;\n // if this is a $ref, use WithRequired if parent specifies required properties\n // (but only for valid keys)\n if (\"$ref\" in item) {\n itemType = transformSchemaObject(item, options);\n\n const resolved = options.ctx.resolve(item.$ref);\n\n // make keys required, if necessary\n if (\n resolved &&\n typeof resolved === \"object\" &&\n \"properties\" in resolved &&\n // we have already handled this item (discriminator property was already added as required)\n !options.ctx.discriminators.refsHandled.includes(item.$ref)\n ) {\n // add WithRequired if necessary\n const validRequired = (required ?? []).filter((key) => !!resolved.properties?.[key]);\n if (validRequired.length) {\n itemType = tsWithRequired(itemType, validRequired, options.ctx.injectFooter);\n }\n }\n }\n // otherwise, if this is a schema object, combine parent `required[]` with its own, if any\n else {\n const itemRequired = [...(required ?? [])];\n if (typeof item === \"object\" && Array.isArray(item.required)) {\n itemRequired.push(...item.required);\n }\n itemType = transformSchemaObject({ ...item, required: itemRequired }, options);\n }\n\n const discriminator =\n (\"$ref\" in item && options.ctx.discriminators.objects[item.$ref]) || (item as any).discriminator;\n if (discriminator) {\n output.push(tsOmit(itemType, [discriminator.propertyName]));\n } else {\n output.push(itemType);\n }\n }\n return output;\n }\n\n // compile final type\n let finalType: ts.TypeNode | undefined;\n\n // core + allOf: intersect\n const coreObjectType = transformSchemaObjectCore(schemaObject, options);\n const allOfType = collectAllOfCompositions(schemaObject.allOf ?? [], schemaObject.required);\n if (coreObjectType || allOfType.length) {\n const allOf: ts.TypeNode | undefined = allOfType.length ? tsIntersection(allOfType) : undefined;\n finalType = tsIntersection([...(coreObjectType ? [coreObjectType] : []), ...(allOf ? [allOf] : [])]);\n }\n // anyOf: union\n // (note: this may seem counterintuitive, but as TypeScript’s unions are not true XORs, they mimic behavior closer to anyOf than oneOf)\n const anyOfType = collectUnionCompositions(schemaObject.anyOf ?? [], \"anyOf\");\n if (anyOfType.length) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...anyOfType]);\n }\n // oneOf: union (within intersection with other types, if any)\n const oneOfType = collectUnionCompositions(\n schemaObject.oneOf ||\n (\"type\" in schemaObject &&\n schemaObject.type === \"object\" &&\n (schemaObject.enum as (SchemaObject | ReferenceObject)[])) ||\n [],\n \"oneOf\",\n );\n if (oneOfType.length) {\n // note: oneOf is the only type that may include primitives\n if (oneOfType.every(tsIsPrimitive)) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...oneOfType]);\n } else {\n finalType = tsIntersection([...(finalType ? [finalType] : []), tsUnion(oneOfType)]);\n }\n }\n\n // When no final type can be generated, fall back to unknown type (or related variants)\n if (!finalType) {\n if (\"type\" in schemaObject) {\n finalType = tsRecord(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER);\n } else {\n finalType = UNKNOWN;\n }\n }\n\n if (finalType !== UNKNOWN && schemaObject.nullable) {\n finalType = tsNullable([finalType]);\n }\n\n return finalType;\n}\n\n/**\n * Check if the given OAPI enum should be transformed to a TypeScript enum\n */\nfunction shouldTransformToTsEnum(options: TransformNodeOptions, schemaObject: SchemaObject): boolean {\n // Enum conversion not enabled or no enum present\n if (!options.ctx.enum || !schemaObject.enum) {\n return false;\n }\n\n // Enum must have string, number or null values\n if (!schemaObject.enum.every((v) => [\"string\", \"number\", null].includes(typeof v))) {\n return false;\n }\n\n // If conditionalEnums is enabled, only convert if x-enum-* metadata is present\n if (options.ctx.conditionalEnums) {\n const hasEnumMetadata =\n Array.isArray(schemaObject[\"x-enum-varnames\"]) ||\n Array.isArray(schemaObject[\"x-enumNames\"]) ||\n Array.isArray(schemaObject[\"x-enum-descriptions\"]) ||\n Array.isArray(schemaObject[\"x-enumDescriptions\"]);\n if (!hasEnumMetadata) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Handle SchemaObject minus composition (anyOf/allOf/oneOf)\n */\nfunction transformSchemaObjectCore(schemaObject: SchemaObject, options: TransformNodeOptions): ts.TypeNode | undefined {\n if (\"type\" in schemaObject && schemaObject.type) {\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(schemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n if (result.questionToken) {\n return ts.factory.createUnionTypeNode([result.schema, UNDEFINED]);\n } else {\n return result.schema;\n }\n } else {\n return result;\n }\n }\n }\n\n // primitives\n // type: null\n if (schemaObject.type === \"null\") {\n return NULL;\n }\n // type: string\n if (schemaObject.type === \"string\") {\n return STRING;\n }\n // type: number / type: integer\n if (schemaObject.type === \"number\" || schemaObject.type === \"integer\") {\n return NUMBER;\n }\n // type: boolean\n if (schemaObject.type === \"boolean\") {\n return BOOLEAN;\n }\n\n // type: array (with support for tuples)\n if (schemaObject.type === \"array\") {\n // default to `unknown[]`\n let itemType: ts.TypeNode = UNKNOWN;\n // tuple type\n if (schemaObject.prefixItems || Array.isArray(schemaObject.items)) {\n const prefixItems = schemaObject.prefixItems ?? (schemaObject.items as (SchemaObject | ReferenceObject)[]);\n itemType = ts.factory.createTupleTypeNode(prefixItems.map((item) => transformSchemaObject(item, options)));\n }\n // standard array type\n else if (schemaObject.items) {\n if (hasKey(schemaObject.items, \"type\") && schemaObject.items.type === \"array\") {\n itemType = ts.factory.createArrayTypeNode(transformSchemaObject(schemaObject.items, options));\n } else {\n itemType = transformSchemaObject(schemaObject.items, options);\n }\n }\n\n const min: number =\n typeof schemaObject.minItems === \"number\" && schemaObject.minItems >= 0 ? schemaObject.minItems : 0;\n const max: number | undefined =\n typeof schemaObject.maxItems === \"number\" && schemaObject.maxItems >= 0 && min <= schemaObject.maxItems\n ? schemaObject.maxItems\n : undefined;\n const estimateCodeSize = typeof max !== \"number\" ? min : (max * (max + 1) - min * (min - 1)) / 2;\n if (\n options.ctx.arrayLength &&\n (min !== 0 || max !== undefined) &&\n estimateCodeSize < 30 // \"30\" is an arbitrary number but roughly around when TS starts to struggle with tuple inference in practice\n ) {\n if (min === max) {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n return tsUnion([ts.factory.createTupleTypeNode(elements)]);\n } else if ((schemaObject.maxItems as number) > 0) {\n // if maxItems is set, then return a union of all permutations of possible tuple types\n const members: ts.TypeNode[] = [];\n // populate 1 short of min …\n for (let i = 0; i <= (max ?? 0) - min; i++) {\n const elements: ts.TypeNode[] = [];\n for (let j = min; j < i + min; j++) {\n elements.push(itemType);\n }\n members.push(ts.factory.createTupleTypeNode(elements));\n }\n return tsUnion(members);\n }\n // if maxItems not set, then return a simple tuple type the length of `min`\n else {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n elements.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(itemType)));\n return ts.factory.createTupleTypeNode(elements);\n }\n }\n\n const finalType =\n ts.isTupleTypeNode(itemType) || ts.isArrayTypeNode(itemType)\n ? itemType\n : ts.factory.createArrayTypeNode(itemType); // wrap itemType in array type, but only if not a tuple or array already\n\n return options.ctx.immutable\n ? ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, finalType)\n : finalType;\n }\n\n // polymorphic, or 3.1 nullable\n if (Array.isArray(schemaObject.type) && !Array.isArray(schemaObject)) {\n // skip any primitive types that appear in oneOf as well\n const uniqueTypes: ts.TypeNode[] = [];\n if (Array.isArray(schemaObject.oneOf)) {\n for (const t of schemaObject.type) {\n if (\n (t === \"boolean\" || t === \"string\" || t === \"number\" || t === \"integer\" || t === \"null\") &&\n schemaObject.oneOf.find((o) => typeof o === \"object\" && \"type\" in o && o.type === t)\n ) {\n continue;\n }\n uniqueTypes.push(\n t === \"null\" || t === null\n ? NULL\n : transformSchemaObject(\n { ...schemaObject, type: t, oneOf: undefined } as SchemaObject, // don’t stack oneOf transforms\n options,\n ),\n );\n }\n } else {\n for (const t of schemaObject.type) {\n if (t === \"null\" || t === null) {\n uniqueTypes.push(NULL);\n } else {\n uniqueTypes.push(transformSchemaObject({ ...schemaObject, type: t } as SchemaObject, options));\n }\n }\n }\n return tsUnion(uniqueTypes);\n }\n }\n\n // type: object\n const coreObjectType: ts.TypeElement[] = [];\n\n // discriminators: explicit mapping on schema object\n for (const k of [\"allOf\", \"anyOf\"] as const) {\n if (!schemaObject[k]) {\n continue;\n }\n // for all magic inheritance, we will have already gathered it into\n // ctx.discriminators. But stop objects from referencing their own\n // discriminator meant for children (!schemaObject.discriminator)\n // and don't add discriminator properties if we already added/patched\n // them (options.ctx.discriminators.refsHandled.includes(options.path!).\n const discriminator =\n !schemaObject.discriminator &&\n !options.ctx.discriminators.refsHandled.includes(options.path ?? \"\") &&\n options.ctx.discriminators.objects[options.path ?? \"\"];\n if (discriminator) {\n coreObjectType.unshift(\n createDiscriminatorProperty(discriminator, {\n path: options.path ?? \"\",\n readonly: options.ctx.immutable,\n }),\n );\n break;\n }\n }\n\n if (\n (\"properties\" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length) ||\n (\"additionalProperties\" in schemaObject && schemaObject.additionalProperties) ||\n (\"patternProperties\" in schemaObject && schemaObject.patternProperties) ||\n (\"$defs\" in schemaObject && schemaObject.$defs)\n ) {\n // properties\n if (Object.keys(schemaObject.properties ?? {}).length) {\n for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) {\n if ((typeof v !== \"object\" && typeof v !== \"boolean\") || Array.isArray(v)) {\n throw new Error(\n `${options.path}: invalid property ${k}. Expected Schema Object or boolean, got ${\n Array.isArray(v) ? \"Array\" : typeof v\n }`,\n );\n }\n\n const { $ref, readOnly, writeOnly, hasDefault } =\n typeof v === \"object\"\n ? {\n $ref: \"$ref\" in v && v.$ref,\n readOnly: \"readOnly\" in v && v.readOnly,\n writeOnly: \"writeOnly\" in v && v.writeOnly,\n hasDefault: \"default\" in v && v.default !== undefined,\n }\n : {};\n\n // handle excludeDeprecated option\n if (options.ctx.excludeDeprecated) {\n const resolved = $ref ? options.ctx.resolve($ref) : v;\n if ((resolved as SchemaObject)?.deprecated) {\n continue;\n }\n }\n let optional =\n schemaObject.required?.includes(k) ||\n (schemaObject.required === undefined && options.ctx.propertiesRequiredByDefault) ||\n (hasDefault &&\n options.ctx.defaultNonNullable &&\n !options.path?.includes(\"parameters\") &&\n !options.path?.includes(\"requestBody\") &&\n !options.path?.includes(\"requestBodies\")) // can’t be required, even with defaults\n ? undefined\n : QUESTION_TOKEN;\n let type = $ref\n ? oapiRef($ref)\n : transformSchemaObject(v, {\n ...options,\n path: createRef([options.path, k]),\n });\n\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(v as SchemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n type = result.schema;\n optional = result.questionToken ? QUESTION_TOKEN : optional;\n } else {\n type = result;\n }\n }\n }\n\n type = wrapWithReadWriteMarker(type, !!readOnly, !!writeOnly, options.ctx);\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && readOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ optional,\n /* type */ type,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n coreObjectType.push(property);\n }\n }\n\n // $defs\n if (schemaObject.$defs && typeof schemaObject.$defs === \"object\" && Object.keys(schemaObject.$defs).length) {\n const defKeys: ts.TypeElement[] = [];\n for (const [k, v] of Object.entries(schemaObject.$defs)) {\n const defReadOnly = \"readOnly\" in v && !!v.readOnly;\n const defWriteOnly = \"writeOnly\" in v && !!v.writeOnly;\n const defType = wrapWithReadWriteMarker(\n transformSchemaObject(v, { ...options, path: createRef([options.path, \"$defs\", k]) }),\n defReadOnly,\n defWriteOnly,\n options.ctx,\n );\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && defReadOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ undefined,\n /* type */ defType,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, \"$defs\", k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n defKeys.push(property);\n }\n coreObjectType.push(\n ts.factory.createPropertySignature(\n /* modifiers */ undefined,\n /* name */ tsPropertyIndex(\"$defs\"),\n /* questionToken */ undefined,\n /* type */ ts.factory.createTypeLiteralNode(defKeys),\n ),\n );\n }\n\n // additionalProperties / patternProperties\n const hasExplicitAdditionalProperties =\n typeof schemaObject.additionalProperties === \"object\" && Object.keys(schemaObject.additionalProperties).length;\n const hasImplicitAdditionalProperties =\n schemaObject.additionalProperties === true ||\n (typeof schemaObject.additionalProperties === \"object\" &&\n Object.keys(schemaObject.additionalProperties).length === 0);\n const hasExplicitPatternProperties =\n typeof schemaObject.patternProperties === \"object\" && Object.keys(schemaObject.patternProperties).length;\n const stringIndexTypes = [];\n if (hasExplicitAdditionalProperties) {\n stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties as SchemaObject, options, true));\n }\n if (hasImplicitAdditionalProperties || (!schemaObject.additionalProperties && options.ctx.additionalProperties)) {\n stringIndexTypes.push(UNKNOWN);\n }\n if (hasExplicitPatternProperties) {\n for (const [_, v] of getEntries(schemaObject.patternProperties ?? {}, options.ctx)) {\n stringIndexTypes.push(transformSchemaObject(v, options));\n }\n }\n\n if (stringIndexTypes.length === 0) {\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n }\n\n const stringIndexType = tsUnion(stringIndexTypes);\n\n return tsIntersection([\n ...(coreObjectType.length ? [ts.factory.createTypeLiteralNode(coreObjectType)] : []),\n ts.factory.createTypeLiteralNode([\n ts.factory.createIndexSignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable,\n }),\n /* parameters */ [\n ts.factory.createParameterDeclaration(\n /* modifiers */ undefined,\n /* dotDotDotToken */ undefined,\n /* name */ ts.factory.createIdentifier(\"key\"),\n /* questionToken */ undefined,\n /* type */ STRING,\n ),\n ],\n /* type */ stringIndexType,\n ),\n ]),\n ]);\n }\n\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n}\n\n/**\n * Check if an object has a key\n * @param possibleObject - The object to check\n * @param key - The key to check for\n * @returns True if the object has the key, false otherwise\n */\nfunction hasKey(possibleObject: unknown, key: K): possibleObject is { [key in K]: unknown } {\n return typeof possibleObject === \"object\" && possibleObject !== null && key in possibleObject;\n}\n\n/** Wrap type with $Read or $Write marker when readWriteMarkers flag is enabled */\nfunction wrapWithReadWriteMarker(\n type: ts.TypeNode,\n readOnly: boolean,\n writeOnly: boolean,\n ctx: { readWriteMarkers: boolean },\n): ts.TypeNode {\n if (!ctx.readWriteMarkers || (readOnly && writeOnly)) {\n return type;\n }\n if (readOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Read\"), [type]);\n }\n if (writeOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Write\"), [type]);\n }\n return type;\n}\n"],"names":["NEVER","UNKNOWN","oapiRef","tsLiteral","parseRef","enumType","tsEnum","ts","tsUnion","NULL","createRef","tsArrayLiteralExpression","tsWithRequired","tsOmit","tsIntersection","tsIsPrimitive","tsRecord","STRING","tsNullable","UNDEFINED","NUMBER","BOOLEAN","createDiscriminatorProperty","getEntries","QUESTION_TOKEN","tsModifiers","tsPropertyIndex","addJSDocComment"],"mappings":";;;;;;;;;;;;;AAiCA,SAAwB,qBAAA,CACtB,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AACb,EAAA,MAAM,IAAA,GAAO,oCAAA,CAAqC,YAAA,EAAc,OAAA,EAAS,wBAAwB,CAAA;AACjG,EAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,aAAA,KAAkB,UAAA,EAAY;AACnD,IAAA,MAAM,mBAAA,GAAsB,OAAA,CAAQ,GAAA,CAAI,aAAA,CAAc,MAAM,OAAO,CAAA;AACnE,IAAA,IAAI,mBAAA,EAAqB;AACvB,MAAA,OAAO,mBAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAKO,SAAS,oCAAA,CACd,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AAMb,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAOA,QAAA;AAAA,EACT;AAEA,EAAA,IAAK,iBAA6B,IAAA,EAAM;AACtC,IAAA,OAAOC,UAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAM,OAAA,CAAQ,YAAY,CAAA,IAAK,OAAO,iBAAiB,QAAA,EAAU;AACnE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gCAAA,EAAmC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,GAAI,UAAU,OAAO,YAAY,CAAA,IAAA,EAAO,OAAA,CAAQ,IAAI,CAAA;AAAA,KACnH;AAAA,EACF;AAKA,EAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,IAAA,OAAOC,UAAA,CAAQ,aAAa,IAAI,CAAA;AAAA,EAClC;AAKA,EAAA,IAAI,YAAA,CAAa,KAAA,KAAU,IAAA,IAAQ,YAAA,CAAa,UAAU,MAAA,EAAW;AACnE,IAAA,OAAOC,YAAA,CAAU,aAAa,KAAK,CAAA;AAAA,EACrC;AAMA,EAAA,IACE,MAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,KAC9B,EAAE,MAAA,IAAU,YAAA,CAAA,IAAiB,YAAA,CAAa,IAAA,KAAS,aACpD,EAAE,YAAA,IAAgB,YAAA,CAAA,IAClB,EAAE,0BAA0B,YAAA,CAAA,EAC5B;AAEA,IAAA,IAAI,uBAAA,CAAwB,OAAA,EAAS,YAAY,CAAA,EAAG;AAClD,MAAA,IAAI,QAAA,GAAWC,qBAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA,CAAE,OAAA,CAAQ,KAAK,GAAG,CAAA;AAE5D,MAAA,QAAA,GAAW,QAAA,CAAS,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AACpD,MAAA,MAAM,WAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAI,CAAC,GAAG,CAAA,MAAO;AAAA,QAChD,IAAA,EAAM,aAAa,iBAAiB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,aAAa,CAAA,GAAI,CAAC,CAAA;AAAA,QAC7E,WAAA,EAAa,aAAa,qBAAqB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,oBAAoB,CAAA,GAAI,CAAC;AAAA,OACjG,CAAE,CAAA;AAGF,MAAA,IAAI,OAAA,GAAU,KAAA;AACd,MAAA,MAAM,gBAAA,GAAmB,YAAA,CAAa,IAAA,CAAK,MAAA,CAAO,CAAC,SAAA,KAAc;AAC/D,QAAA,IAAI,cAAc,IAAA,EAAM;AACtB,UAAA,OAAA,GAAU,IAAA;AACV,UAAA,OAAO,KAAA;AAAA,QACT;AAEA,QAAA,OAAO,IAAA;AAAA,MACT,CAAC,CAAA;AACD,MAAA,MAAMC,SAAAA,GAAWC,SAAA,CAAO,QAAA,EAAU,gBAAA,EAAyC,QAAA,EAAU;AAAA,QACnF,WAAA,EAAa,QAAQ,GAAA,CAAI,WAAA;AAAA,QACzB,MAAA,EAAQ;AAAA;AAAA,OAET,CAAA;AACD,MAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,QAAA,CAASD,SAAQ,CAAA,EAAG;AAChD,QAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAKA,SAAQ,CAAA;AAAA,MACxC;AACA,MAAA,MAAM,GAAA,GAAME,WAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBF,UAAS,IAAI,CAAA;AAC5D,MAAA,OAAO,UAAUG,UAAA,CAAQ,CAAC,GAAA,EAAKC,OAAI,CAAC,CAAA,GAAI,GAAA;AAAA,IAC1C;AACA,IAAA,MAAM,QAAA,GAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAIN,YAAS,CAAA;AAChD,IAAA,IAAK,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,IAAK,YAAA,CAAa,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,IAAM,YAAA,CAAa,QAAA,EAAU;AACrG,MAAA,QAAA,CAAS,KAAKM,OAAI,CAAA;AAAA,IACpB;AAEA,IAAA,MAAM,SAAA,GAAYD,WAAQ,QAAQ,CAAA;AAGlC,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,YAAA,CAAa,KAAK,KAAA,CAAM,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EAAG;AAC5G,MAAA,MAAM,MAAA,GAASJ,oBAAA,CAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA;AAC1C,MAAA,IAAI,sBAAA,GAAyB,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA;AAEpD,MAAA,sBAAA,GAAyB,sBAAA,CAAuB,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AAChF,MAAA,sBAAA,GAAyB,GAAG,sBAAsB,CAAA,MAAA,CAAA;AAIlD,MAAA,MAAM,iBAA2B,EAAC;AAQlC,MAAA,MAAM,oBAA8B,EAAC;AACrC,MAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AAE9C,QAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,CAAC,CAAA;AAChC,QAAA,IAAA,CAAK,OAAA,KAAY,WAAW,OAAA,KAAY,OAAA,KAAY,IAAI,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACjF,UAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,CAAA,GAAI,CAAC,CAAA;AACjC,UAAA,IAAI,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,EAAG;AAEtB,YAAA,CAAA,EAAA;AAIA,YAAA,MAAM,iBAAA,GAAoB,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAC,CAAA;AACpD,YAAA,KAAA,MAAW,OAAO,iBAAA,EAAmB;AAEnC,cAAA,IAAI,GAAA,KAAQ,WAAW,GAAA,KAAQ,OAAA,IAAW,CAAC,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,EAAG;AAC5D,gBAAA,iBAAA,CAAkB,KAAK,GAAG,CAAA;AAAA,cAC5B;AAAA,YACF;AACA,YAAA;AAAA,UACF;AAAA,QACF;AACA,QAAA,cAAA,CAAe,KAAK,OAAO,CAAA;AAAA,MAC7B;AACA,MAAA,MAAM,cAAA,GAAiBM,gBAAU,cAAc,CAAA;AAE/C,MAAA,MAAM,eAAA,GAAkBC,2BAAA;AAAA,QACtB,sBAAA;AAAA;AAAA,QAEA,wBAAA,GACIJ,YAAG,OAAA,CAAQ,2BAAA;AAAA,UACTL,WAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,UACpEK,YAAG,OAAA,CAAQ,uBAAA,CAAwBA,YAAG,OAAA,CAAQ,gBAAA,CAAiB,QAAQ,CAAC;AAAA,SAC1E,GACAL,WAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,QACxE,YAAA,CAAa,IAAA;AAAA,QACb;AAAA,UACE,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU,IAAA;AAAA,UACV,YAAA,EAAc,QAAQ,GAAA,CAAI;AAAA;AAC5B,OACF;AAEA,MAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAK,eAAe,CAAA;AAAA,IAC/C;AAEA,IAAA,OAAO,SAAA;AAAA,EACT;AAOA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAA6B;AACxG,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,CAAC,KAAA,EAAO,IAAI,CAAA,IAAK,KAAA,CAAM,SAAQ,EAAG;AAC3C,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,sBAAsB,IAAA,EAAM;AAAA,UAC1B,GAAG,OAAA;AAAA;AAAA,UAEH,IAAA,EAAMQ,gBAAU,CAAC,OAAA,CAAQ,MAAM,QAAA,EAAU,MAAA,CAAO,KAAK,CAAC,CAAC;AAAA,SACxD;AAAA,OACH;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAAoC;AAC/G,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,MAAA,IAAI,QAAA;AAGJ,MAAA,IAAI,UAAU,IAAA,EAAM;AAClB,QAAA,QAAA,GAAW,qBAAA,CAAsB,MAAM,OAAO,CAAA;AAE9C,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,KAAK,IAAI,CAAA;AAG5D,QAAA,IACE,QAAA,IACA,OAAO,QAAA,KAAa,QAAA,IACpB,YAAA,IAAgB,QAAA;AAAA,QAEhB,CAAC,QAAQ,GAAA,CAAI,cAAA,CAAe,YAAY,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAC1D;AAEA,UAAA,MAAM,aAAA,GAAA,CAAiB,QAAA,IAAY,EAAC,EAAG,MAAA,CAAO,CAAC,GAAA,KAAQ,CAAC,CAAC,QAAA,CAAS,UAAA,GAAa,GAAG,CAAC,CAAA;AACnF,UAAA,IAAI,cAAc,MAAA,EAAQ;AACxB,YAAA,QAAA,GAAWE,iBAAA,CAAe,QAAA,EAAU,aAAA,EAAe,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,UAC7E;AAAA,QACF;AAAA,MACF,CAAA,MAEK;AACH,QAAA,MAAM,YAAA,GAAe,CAAC,GAAI,QAAA,IAAY,EAAG,CAAA;AACzC,QAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,QAAQ,CAAA,EAAG;AAC5D,UAAA,YAAA,CAAa,IAAA,CAAK,GAAG,IAAA,CAAK,QAAQ,CAAA;AAAA,QACpC;AACA,QAAA,QAAA,GAAW,sBAAsB,EAAE,GAAG,MAAM,QAAA,EAAU,YAAA,IAAgB,OAAO,CAAA;AAAA,MAC/E;AAEA,MAAA,MAAM,aAAA,GACH,MAAA,IAAU,IAAA,IAAQ,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,IAAO,IAAA,CAAa,aAAA;AACrF,MAAA,IAAI,aAAA,EAAe;AACjB,QAAA,MAAA,CAAO,KAAKC,SAAA,CAAO,QAAA,EAAU,CAAC,aAAA,CAAc,YAAY,CAAC,CAAC,CAAA;AAAA,MAC5D,CAAA,MAAO;AACL,QAAA,MAAA,CAAO,KAAK,QAAQ,CAAA;AAAA,MACtB;AAAA,IACF;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,IAAI,SAAA;AAGJ,EAAA,MAAM,cAAA,GAAiB,yBAAA,CAA0B,YAAA,EAAc,OAAO,CAAA;AACtE,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,SAAS,EAAC,EAAG,aAAa,QAAQ,CAAA;AAC1F,EAAA,IAAI,cAAA,IAAkB,UAAU,MAAA,EAAQ;AACtC,IAAA,MAAM,KAAA,GAAiC,SAAA,CAAU,MAAA,GAASC,iBAAA,CAAe,SAAS,CAAA,GAAI,MAAA;AACtF,IAAA,SAAA,GAAYA,kBAAe,CAAC,GAAI,cAAA,GAAiB,CAAC,cAAc,CAAA,GAAI,EAAC,EAAI,GAAI,QAAQ,CAAC,KAAK,CAAA,GAAI,EAAG,CAAC,CAAA;AAAA,EACrG;AAGA,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,KAAA,IAAS,IAAI,OAAO,CAAA;AAC5E,EAAA,IAAI,UAAU,MAAA,EAAQ;AACpB,IAAA,SAAA,GAAYN,UAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,EACvE;AAEA,EAAA,MAAM,SAAA,GAAY,wBAAA;AAAA,IAChB,YAAA,CAAa,SACV,MAAA,IAAU,YAAA,IACT,aAAa,IAAA,KAAS,QAAA,IACrB,YAAA,CAAa,IAAA,IAChB,EAAC;AAAA,IACH;AAAA,GACF;AACA,EAAA,IAAI,UAAU,MAAA,EAAQ;AAEpB,IAAA,IAAI,SAAA,CAAU,KAAA,CAAMO,gBAAa,CAAA,EAAG;AAClC,MAAA,SAAA,GAAYP,UAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,IACvE,CAAA,MAAO;AACL,MAAA,SAAA,GAAYM,iBAAA,CAAe,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAIN,UAAA,CAAQ,SAAS,CAAC,CAAC,CAAA;AAAA,IACpF;AAAA,EACF;AAGA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,MAAA,SAAA,GAAYQ,YAASC,SAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,mBAAA,GAAsBhB,aAAUD,QAAK,CAAA;AAAA,IAChF,CAAA,MAAO;AACL,MAAA,SAAA,GAAYC,UAAA;AAAA,IACd;AAAA,EACF;AAEA,EAAA,IAAI,SAAA,KAAcA,UAAA,IAAW,YAAA,CAAa,QAAA,EAAU;AAClD,IAAA,SAAA,GAAYiB,aAAA,CAAW,CAAC,SAAS,CAAC,CAAA;AAAA,EACpC;AAEA,EAAA,OAAO,SAAA;AACT;AAKA,SAAS,uBAAA,CAAwB,SAA+B,YAAA,EAAqC;AAEnG,EAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,IAAA,IAAQ,CAAC,aAAa,IAAA,EAAM;AAC3C,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,KAAM,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,CAAA,CAAE,QAAA,CAAS,OAAO,CAAC,CAAC,CAAA,EAAG;AAClF,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,OAAA,CAAQ,IAAI,gBAAA,EAAkB;AAChC,IAAA,MAAM,eAAA,GACJ,MAAM,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAC,CAAA,IAC7C,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,aAAa,CAAC,CAAA,IACzC,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAC,KACjD,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,oBAAoB,CAAC,CAAA;AAClD,IAAA,IAAI,CAAC,eAAA,EAAiB;AACpB,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT;AAKA,SAAS,yBAAA,CAA0B,cAA4B,OAAA,EAAwD;AACrH,EAAA,IAAI,MAAA,IAAU,YAAA,IAAgB,YAAA,CAAa,IAAA,EAAM;AAC/C,IAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,cAAc,OAAO,CAAA;AAC1D,MAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,QAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,UAAA,IAAI,OAAO,aAAA,EAAe;AACxB,YAAA,OAAOX,YAAG,OAAA,CAAQ,mBAAA,CAAoB,CAAC,MAAA,CAAO,MAAA,EAAQY,YAAS,CAAC,CAAA;AAAA,UAClE,CAAA,MAAO;AACL,YAAA,OAAO,MAAA,CAAO,MAAA;AAAA,UAChB;AAAA,QACF,CAAA,MAAO;AACL,UAAA,OAAO,MAAA;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAIA,IAAA,IAAI,YAAA,CAAa,SAAS,MAAA,EAAQ;AAChC,MAAA,OAAOV,OAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,QAAA,EAAU;AAClC,MAAA,OAAOQ,SAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,IAAA,KAAS,QAAA,IAAY,YAAA,CAAa,SAAS,SAAA,EAAW;AACrE,MAAA,OAAOG,SAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,SAAA,EAAW;AACnC,MAAA,OAAOC,UAAA;AAAA,IACT;AAGA,IAAA,IAAI,YAAA,CAAa,SAAS,OAAA,EAAS;AAEjC,MAAA,IAAI,QAAA,GAAwBpB,UAAA;AAE5B,MAAA,IAAI,aAAa,WAAA,IAAe,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACjE,QAAA,MAAM,WAAA,GAAc,YAAA,CAAa,WAAA,IAAgB,YAAA,CAAa,KAAA;AAC9D,QAAA,QAAA,GAAWM,WAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,WAAA,CAAY,GAAA,CAAI,CAAC,IAAA,KAAS,qBAAA,CAAsB,IAAA,EAAM,OAAO,CAAC,CAAC,CAAA;AAAA,MAC3G,CAAA,MAAA,IAES,aAAa,KAAA,EAAO;AAC3B,QAAA,IAAI,MAAA,CAAO,aAAa,KAAA,EAAO,MAAM,KAAK,YAAA,CAAa,KAAA,CAAM,SAAS,OAAA,EAAS;AAC7E,UAAA,QAAA,GAAWA,YAAG,OAAA,CAAQ,mBAAA,CAAoB,sBAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,QAC9F,CAAA,MAAO;AACL,UAAA,QAAA,GAAW,qBAAA,CAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAA;AAAA,QAC9D;AAAA,MACF;AAEA,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,YAAY,YAAA,CAAa,QAAA,IAAY,CAAA,GAAI,YAAA,CAAa,QAAA,GAAW,CAAA;AACpG,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,QAAA,IAAY,YAAA,CAAa,QAAA,IAAY,CAAA,IAAK,GAAA,IAAO,YAAA,CAAa,QAAA,GAC3F,YAAA,CAAa,QAAA,GACb,MAAA;AACN,MAAA,MAAM,gBAAA,GAAmB,OAAO,GAAA,KAAQ,QAAA,GAAW,GAAA,GAAA,CAAO,OAAO,GAAA,GAAM,CAAA,CAAA,GAAK,GAAA,IAAO,GAAA,GAAM,CAAA,CAAA,IAAM,CAAA;AAC/F,MAAA,IACE,OAAA,CAAQ,IAAI,WAAA,KACX,GAAA,KAAQ,KAAK,GAAA,KAAQ,MAAA,CAAA,IACtB,mBAAmB,EAAA,EACnB;AACA,QAAA,IAAI,QAAQ,GAAA,EAAK;AACf,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,OAAOC,WAAQ,CAACD,WAAA,CAAG,QAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AAAA,QAC3D,CAAA,MAAA,IAAY,YAAA,CAAa,QAAA,GAAsB,CAAA,EAAG;AAEhD,UAAA,MAAM,UAAyB,EAAC;AAEhC,UAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,IAAA,CAAM,GAAA,IAAO,CAAA,IAAK,KAAK,CAAA,EAAA,EAAK;AAC1C,YAAA,MAAM,WAA0B,EAAC;AACjC,YAAA,KAAA,IAAS,CAAA,GAAI,GAAA,EAAK,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,EAAA,EAAK;AAClC,cAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,YACxB;AACA,YAAA,OAAA,CAAQ,IAAA,CAAKA,WAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAA;AAAA,UACvD;AACA,UAAA,OAAOC,WAAQ,OAAO,CAAA;AAAA,QACxB,CAAA,MAEK;AACH,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,QAAA,CAAS,IAAA,CAAKD,YAAG,OAAA,CAAQ,kBAAA,CAAmBA,YAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AACrF,UAAA,OAAOA,WAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAA;AAAA,QAChD;AAAA,MACF;AAEA,MAAA,MAAM,SAAA,GACJA,WAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,IAAKA,WAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,GACvD,QAAA,GACAA,WAAA,CAAG,OAAA,CAAQ,oBAAoB,QAAQ,CAAA;AAE7C,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,GACfA,WAAA,CAAG,OAAA,CAAQ,uBAAuBA,WAAA,CAAG,UAAA,CAAW,eAAA,EAAiB,SAAS,CAAA,GAC1E,SAAA;AAAA,IACN;AAGA,IAAA,IAAI,KAAA,CAAM,QAAQ,YAAA,CAAa,IAAI,KAAK,CAAC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,EAAG;AAEpE,MAAA,MAAM,cAA6B,EAAC;AACpC,MAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACrC,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAA,CACG,CAAA,KAAM,aAAa,CAAA,KAAM,QAAA,IAAY,MAAM,QAAA,IAAY,CAAA,KAAM,SAAA,IAAa,CAAA,KAAM,MAAA,KACjF,YAAA,CAAa,MAAM,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,UAAU,CAAA,IAAK,CAAA,CAAE,IAAA,KAAS,CAAC,CAAA,EACnF;AACA,YAAA;AAAA,UACF;AACA,UAAA,WAAA,CAAY,IAAA;AAAA,YACV,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,GAClBE,OAAA,GACA,qBAAA;AAAA,cACE,EAAE,GAAG,YAAA,EAAc,IAAA,EAAM,CAAA,EAAG,OAAO,MAAA,EAAU;AAAA;AAAA,cAC7C;AAAA;AACF,WACN;AAAA,QACF;AAAA,MACF,CAAA,MAAO;AACL,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAI,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,EAAM;AAC9B,YAAA,WAAA,CAAY,KAAKA,OAAI,CAAA;AAAA,UACvB,CAAA,MAAO;AACL,YAAA,WAAA,CAAY,IAAA,CAAK,sBAAsB,EAAE,GAAG,cAAc,IAAA,EAAM,CAAA,EAAE,EAAmB,OAAO,CAAC,CAAA;AAAA,UAC/F;AAAA,QACF;AAAA,MACF;AACA,MAAA,OAAOD,WAAQ,WAAW,CAAA;AAAA,IAC5B;AAAA,EACF;AAGA,EAAA,MAAM,iBAAmC,EAAC;AAG1C,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,OAAA,EAAS,OAAO,CAAA,EAAY;AAC3C,IAAA,IAAI,CAAC,YAAA,CAAa,CAAC,CAAA,EAAG;AACpB,MAAA;AAAA,IACF;AAMA,IAAA,MAAM,aAAA,GACJ,CAAC,YAAA,CAAa,aAAA,IACd,CAAC,OAAA,CAAQ,GAAA,CAAI,eAAe,WAAA,CAAY,QAAA,CAAS,QAAQ,IAAA,IAAQ,EAAE,KACnE,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACvD,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,cAAA,CAAe,OAAA;AAAA,QACbc,kCAA4B,aAAA,EAAe;AAAA,UACzC,IAAA,EAAM,QAAQ,IAAA,IAAQ,EAAA;AAAA,UACtB,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,SACvB;AAAA,OACH;AACA,MAAA;AAAA,IACF;AAAA,EACF;AAEA,EAAA,IACG,YAAA,IAAgB,gBAAgB,YAAA,CAAa,UAAA,IAAc,OAAO,IAAA,CAAK,YAAA,CAAa,UAAU,CAAA,CAAE,MAAA,IAChG,0BAA0B,YAAA,IAAgB,YAAA,CAAa,wBACvD,mBAAA,IAAuB,YAAA,IAAgB,aAAa,iBAAA,IACpD,OAAA,IAAW,YAAA,IAAgB,YAAA,CAAa,KAAA,EACzC;AAEA,IAAA,IAAI,OAAO,IAAA,CAAK,YAAA,CAAa,cAAc,EAAE,EAAE,MAAA,EAAQ;AACrD,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAKC,gBAAA,CAAW,YAAA,CAAa,UAAA,IAAc,EAAC,EAAG,OAAA,CAAQ,GAAG,CAAA,EAAG;AAC3E,QAAA,IAAK,OAAO,MAAM,QAAA,IAAY,OAAO,MAAM,SAAA,IAAc,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,EAAG;AACzE,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,EAAG,OAAA,CAAQ,IAAI,CAAA,mBAAA,EAAsB,CAAC,CAAA,yCAAA,EACpC,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAAI,OAAA,GAAU,OAAO,CACtC,CAAA;AAAA,WACF;AAAA,QACF;AAEA,QAAA,MAAM,EAAE,MAAM,QAAA,EAAU,SAAA,EAAW,YAAW,GAC5C,OAAO,MAAM,QAAA,GACT;AAAA,UACE,IAAA,EAAM,MAAA,IAAU,CAAA,IAAK,CAAA,CAAE,IAAA;AAAA,UACvB,QAAA,EAAU,UAAA,IAAc,CAAA,IAAK,CAAA,CAAE,QAAA;AAAA,UAC/B,SAAA,EAAW,WAAA,IAAe,CAAA,IAAK,CAAA,CAAE,SAAA;AAAA,UACjC,UAAA,EAAY,SAAA,IAAa,CAAA,IAAK,CAAA,CAAE,OAAA,KAAY;AAAA,YAE9C,EAAC;AAGP,QAAA,IAAI,OAAA,CAAQ,IAAI,iBAAA,EAAmB;AACjC,UAAA,MAAM,WAAW,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,IAAI,CAAA,GAAI,CAAA;AAClE,UAAA,IAAK,UAA2B,UAAA,EAAY;AAC1C,YAAA;AAAA,UACF;AAAA,QACF;AACA,QAAA,IAAI,QAAA,GACF,YAAA,CAAa,QAAA,EAAU,QAAA,CAAS,CAAC,CAAA,IAChC,YAAA,CAAa,QAAA,KAAa,MAAA,IAAa,QAAQ,GAAA,CAAI,2BAAA,IACnD,UAAA,IACC,OAAA,CAAQ,IAAI,kBAAA,IACZ,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,YAAY,CAAA,IACpC,CAAC,QAAQ,IAAA,EAAM,QAAA,CAAS,aAAa,CAAA,IACrC,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,eAAe,IACrC,MAAA,GACAC,iBAAA;AACN,QAAA,IAAI,OAAO,IAAA,GACPtB,UAAA,CAAQ,IAAI,CAAA,GACZ,sBAAsB,CAAA,EAAG;AAAA,UACvB,GAAG,OAAA;AAAA,UACH,MAAMQ,eAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,SAClC,CAAA;AAEL,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,GAAmB,OAAO,CAAA;AAC/D,UAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,YAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,cAAA,IAAA,GAAO,MAAA,CAAO,MAAA;AACd,cAAA,QAAA,GAAW,MAAA,CAAO,gBAAgBc,iBAAA,GAAiB,QAAA;AAAA,YACrD,CAAA,MAAO;AACL,cAAA,IAAA,GAAO,MAAA;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAEA,QAAA,IAAA,GAAO,uBAAA,CAAwB,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC,SAAA,EAAW,OAAA,CAAQ,GAAG,CAAA;AAEzE,QAAA,IAAI,QAAA,GAAWjB,YAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACJkB,cAAA,CAAY;AAAA,YAC9B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmBC,mBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,QAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAMhB,eAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,WAClC,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAAiB,kBAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,cAAA,CAAe,KAAK,QAAQ,CAAA;AAAA,MAC9B;AAAA,IACF;AAGA,IAAA,IAAI,YAAA,CAAa,KAAA,IAAS,OAAO,YAAA,CAAa,KAAA,KAAU,QAAA,IAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,KAAK,CAAA,CAAE,MAAA,EAAQ;AAC1G,MAAA,MAAM,UAA4B,EAAC;AACnC,MAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACvD,QAAA,MAAM,WAAA,GAAc,UAAA,IAAc,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,QAAA;AAC3C,QAAA,MAAM,YAAA,GAAe,WAAA,IAAe,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,SAAA;AAC7C,QAAA,MAAM,OAAA,GAAU,uBAAA;AAAA,UACd,qBAAA,CAAsB,CAAA,EAAG,EAAE,GAAG,SAAS,IAAA,EAAMjB,eAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC,GAAG,CAAA;AAAA,UACpF,WAAA;AAAA,UACA,YAAA;AAAA,UACA,OAAA,CAAQ;AAAA,SACV;AAEA,QAAA,IAAI,QAAA,GAAWH,YAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACLkB,cAAA,CAAY;AAAA,YAC7B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmBC,mBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,MAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAMhB,eAAA,CAAU,CAAC,QAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC;AAAA,WAC3C,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAAiB,kBAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,OAAA,CAAQ,KAAK,QAAQ,CAAA;AAAA,MACvB;AACA,MAAA,cAAA,CAAe,IAAA;AAAA,QACbpB,YAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACW,MAAA;AAAA;AAAA,UACAmB,mBAAgB,OAAO,CAAA;AAAA;AAAA,UACvB,MAAA;AAAA;AAAA,UACAnB,WAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,OAAO;AAAA;AAC9D,OACF;AAAA,IACF;AAGA,IAAA,MAAM,+BAAA,GACJ,OAAO,YAAA,CAAa,oBAAA,KAAyB,YAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,CAAA,CAAE,MAAA;AAC1G,IAAA,MAAM,+BAAA,GACJ,YAAA,CAAa,oBAAA,KAAyB,IAAA,IACrC,OAAO,YAAA,CAAa,oBAAA,KAAyB,QAAA,IAC5C,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,EAAE,MAAA,KAAW,CAAA;AAC9D,IAAA,MAAM,4BAAA,GACJ,OAAO,YAAA,CAAa,iBAAA,KAAsB,YAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,iBAAiB,CAAA,CAAE,MAAA;AACpG,IAAA,MAAM,mBAAmB,EAAC;AAC1B,IAAA,IAAI,+BAAA,EAAiC;AACnC,MAAA,gBAAA,CAAiB,KAAK,qBAAA,CAAsB,YAAA,CAAa,oBAAA,EAAsC,OAAA,EAAS,IAAI,CAAC,CAAA;AAAA,IAC/G;AACA,IAAA,IAAI,mCAAoC,CAAC,YAAA,CAAa,oBAAA,IAAwB,OAAA,CAAQ,IAAI,oBAAA,EAAuB;AAC/G,MAAA,gBAAA,CAAiB,KAAKN,UAAO,CAAA;AAAA,IAC/B;AACA,IAAA,IAAI,4BAAA,EAA8B;AAChC,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAKsB,gBAAA,CAAW,YAAA,CAAa,iBAAA,IAAqB,EAAC,EAAG,OAAA,CAAQ,GAAG,CAAA,EAAG;AAClF,QAAA,gBAAA,CAAiB,IAAA,CAAK,qBAAA,CAAsB,CAAA,EAAG,OAAO,CAAC,CAAA;AAAA,MACzD;AAAA,IACF;AAEA,IAAA,IAAI,gBAAA,CAAiB,WAAW,CAAA,EAAG;AACjC,MAAA,OAAO,eAAe,MAAA,GAAShB,WAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AAAA,IACpF;AAEA,IAAA,MAAM,eAAA,GAAkBC,WAAQ,gBAAgB,CAAA;AAEhD,IAAA,OAAOM,iBAAA,CAAe;AAAA,MACpB,GAAI,cAAA,CAAe,MAAA,GAAS,CAACP,WAAA,CAAG,QAAQ,qBAAA,CAAsB,cAAc,CAAC,CAAA,GAAI,EAAC;AAAA,MAClFA,WAAA,CAAG,QAAQ,qBAAA,CAAsB;AAAA,QAC/BA,YAAG,OAAA,CAAQ,oBAAA;AAAA;AAAA,UACQkB,cAAA,CAAY;AAAA,YAC3B,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,WACvB,CAAA;AAAA;AAAA,UACgB;AAAA,YACflB,YAAG,OAAA,CAAQ,0BAAA;AAAA;AAAA,cACY,MAAA;AAAA;AAAA,cACA,MAAA;AAAA;AAAA,cACAA,WAAA,CAAG,OAAA,CAAQ,gBAAA,CAAiB,KAAK,CAAA;AAAA;AAAA,cACjC,MAAA;AAAA;AAAA,cACAU;AAAA;AACvB,WACF;AAAA;AAAA,UACiB;AAAA;AACnB,OACD;AAAA,KACF,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,eAAe,MAAA,GAASV,WAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AACpF;AAQA,SAAS,MAAA,CAAyB,gBAAyB,GAAA,EAAmD;AAC5G,EAAA,OAAO,OAAO,cAAA,KAAmB,QAAA,IAAY,cAAA,KAAmB,QAAQ,GAAA,IAAO,cAAA;AACjF;AAGA,SAAS,uBAAA,CACP,IAAA,EACA,QAAA,EACA,SAAA,EACA,GAAA,EACa;AACb,EAAA,IAAI,CAAC,GAAA,CAAI,gBAAA,IAAqB,QAAA,IAAY,SAAA,EAAY;AACpD,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAOA,WAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBA,WAAA,CAAG,OAAA,CAAQ,iBAAiB,OAAO,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,OAAOA,WAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBA,WAAA,CAAG,OAAA,CAAQ,iBAAiB,QAAQ,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACzF;AACA,EAAA,OAAO,IAAA;AACT;;;;;"} +\ No newline at end of file ++{"version":3,"file":"schema-object.cjs","sources":["../../src/transform/schema-object.ts"],"sourcesContent":["import { parseRef } from \"@redocly/openapi-core/lib/ref-utils.js\";\nimport ts from \"typescript\";\nimport {\n addJSDocComment,\n BOOLEAN,\n NEVER,\n NULL,\n NUMBER,\n oapiRef,\n QUESTION_TOKEN,\n STRING,\n tsArrayLiteralExpression,\n tsEnum,\n tsIntersection,\n tsIsPrimitive,\n tsLiteral,\n tsModifiers,\n tsNullable,\n tsPropertyIndex,\n tsRecord,\n tsUnion,\n tsWithRequired,\n UNDEFINED,\n UNKNOWN,\n} from \"../lib/ts.js\";\nimport { createDiscriminatorProperty, createRef, getEntries } from \"../lib/utils.js\";\nimport type { ReferenceObject, SchemaObject, TransformNodeOptions } from \"../types.js\";\n\n/**\n * Transform SchemaObject nodes (4.8.24)\n * @see https://spec.openapis.org/oas/v3.1.0#schema-object\n */\nexport default function transformSchemaObject(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n const type = transformSchemaObjectWithComposition(schemaObject, options, fromAdditionalProperties);\n if (typeof options.ctx.postTransform === \"function\") {\n const postTransformResult = options.ctx.postTransform(type, options);\n if (postTransformResult) {\n return postTransformResult;\n }\n }\n return type;\n}\n\n/**\n * Transform SchemaObjects\n */\nexport function transformSchemaObjectWithComposition(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n /**\n * Unexpected types & edge cases\n */\n\n // missing/falsy type returns `never`\n if (!schemaObject) {\n return NEVER;\n }\n // `true` returns `unknown` (this exists, but is untyped)\n if ((schemaObject as unknown) === true) {\n return UNKNOWN;\n }\n // for any other unexpected type, throw error\n if (Array.isArray(schemaObject) || typeof schemaObject !== \"object\") {\n throw new Error(\n `Expected SchemaObject, received ${Array.isArray(schemaObject) ? \"Array\" : typeof schemaObject} at ${options.path}`,\n );\n }\n\n /**\n * ReferenceObject\n */\n if (\"$ref\" in schemaObject) {\n return oapiRef(schemaObject.$ref);\n }\n\n /**\n * const (valid for any type)\n */\n if (schemaObject.const !== null && schemaObject.const !== undefined) {\n return tsLiteral(schemaObject.const);\n }\n\n /**\n * enum (non-objects)\n * note: enum is valid for any type, but for objects, handle in oneOf below\n */\n if (\n Array.isArray(schemaObject.enum) &&\n (!(\"type\" in schemaObject) || schemaObject.type !== \"object\") &&\n !(\"properties\" in schemaObject)\n ) {\n const hasAdditionalProperties = \"additionalProperties\" in schemaObject && !!schemaObject.additionalProperties;\n\n if (!hasAdditionalProperties || (schemaObject.type === \"string\" && hasAdditionalProperties)) {\n // hoist enum to top level if string/number enum and option is enabled\n if (shouldTransformToTsEnum(options, schemaObject)) {\n let enumName = parseRef(options.path ?? \"\").pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumName = enumName.replace(\"components/schemas\", \"\");\n const metadata = schemaObject.enum.map((_, i) => ({\n name: schemaObject[\"x-enum-varnames\"]?.[i] ?? schemaObject[\"x-enumNames\"]?.[i],\n description: schemaObject[\"x-enum-descriptions\"]?.[i] ?? schemaObject[\"x-enumDescriptions\"]?.[i],\n }));\n\n // enums can contain null values, but dont want to output them\n let hasNull = false;\n const validSchemaEnums = schemaObject.enum.filter((enumValue) => {\n if (enumValue === null) {\n hasNull = true;\n return false;\n }\n\n return true;\n });\n const enumType = tsEnum(enumName, validSchemaEnums as (string | number)[], metadata, {\n shouldCache: options.ctx.dedupeEnums,\n export: true,\n // readonly: TS enum do not support the readonly modifier\n });\n if (!options.ctx.injectFooter.includes(enumType)) {\n options.ctx.injectFooter.push(enumType);\n }\n const ref = ts.factory.createTypeReferenceNode(enumType.name);\n\n const finalType: ts.TypeNode = hasNull ? tsUnion([ref, NULL]) : ref;\n\n return applyAdditionalPropertiesToEnum(hasAdditionalProperties, finalType, schemaObject);\n }\n\n const enumType = schemaObject.enum.map(tsLiteral);\n if ((Array.isArray(schemaObject.type) && schemaObject.type.includes(\"null\")) || schemaObject.nullable) {\n enumType.push(NULL);\n }\n\n const unionType = applyAdditionalPropertiesToEnum(hasAdditionalProperties, tsUnion(enumType), schemaObject);\n\n // hoist array with valid enum values to top level if string/number enum and option is enabled\n if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === \"string\" || typeof v === \"number\")) {\n const parsed = parseRef(options.path ?? \"\");\n let enumValuesVariableName = parsed.pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumValuesVariableName = enumValuesVariableName.replace(\"components/schemas\", \"\");\n enumValuesVariableName = `${enumValuesVariableName}Values`;\n\n // build a ref path for the type that ignores union indices (anyOf/oneOf) so\n // type references remain stable even when names include union positions\n const cleanedPointer: string[] = [];\n // Track ALL properties after a oneOf/anyOf that need Extract<> narrowing.\n // We apply Extract<> before EVERY property access after a union index because:\n // - When the property exists on ALL variants, Extract<> is a no-op (returns same type)\n // - When the property only exists on SOME variants, it correctly narrows the union\n // - When both variants have same property name but different inner schemas,\n // we still narrow at each level to handle nested unions correctly\n // This robust approach handles both simple and complex union structures.\n const extractProperties: string[] = [];\n for (let i = 0; i < parsed.pointer.length; i++) {\n // Example: #/paths/analytics/data/get/responses/400/content/application/json/anyOf/0/message\n const segment = parsed.pointer[i];\n if ((segment === \"anyOf\" || segment === \"oneOf\") && i < parsed.pointer.length - 1) {\n const next = parsed.pointer[i + 1];\n if (/^\\d+$/.test(next)) {\n // If we encounter something like \"anyOf/0\", we want to skip that part of the path\n i++;\n // Collect ALL remaining segments after the union index.\n // Each one will be wrapped with Extract<> to safely narrow the type\n // at each level, handling both top-level and nested union variants.\n const remainingSegments = parsed.pointer.slice(i + 1);\n for (const seg of remainingSegments) {\n // Skip union keywords and indices, only add actual property names\n if (seg !== \"anyOf\" && seg !== \"oneOf\" && !/^\\d+$/.test(seg)) {\n extractProperties.push(seg);\n }\n }\n continue;\n }\n }\n cleanedPointer.push(segment);\n }\n const cleanedRefPath = createRef(cleanedPointer);\n\n const enumValuesArray = tsArrayLiteralExpression(\n enumValuesVariableName,\n // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type\n fromAdditionalProperties\n ? ts.factory.createIndexedAccessTypeNode(\n oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"string\")),\n )\n : oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n schemaObject.enum as (string | number)[],\n {\n export: true,\n readonly: true,\n injectFooter: options.ctx.injectFooter,\n },\n );\n\n options.ctx.injectFooter.push(enumValuesArray);\n }\n\n return unionType;\n }\n }\n\n /**\n * Object + composition (anyOf/allOf/oneOf) types\n */\n\n /** Collect oneOf/anyOf */\n function collectUnionCompositions(items: (SchemaObject | ReferenceObject)[], unionKey: \"anyOf\" | \"oneOf\") {\n const output: ts.TypeNode[] = [];\n for (const [index, item] of items.entries()) {\n output.push(\n transformSchemaObject(item, {\n ...options,\n // include index in path so generated names from nested enums/enumValues are unique\n path: createRef([options.path, unionKey, String(index)]),\n }),\n );\n }\n\n return output;\n }\n\n /** Collect allOf with Omit<> for discriminators */\n function collectAllOfCompositions(items: (SchemaObject | ReferenceObject)[], required?: string[]): ts.TypeNode[] {\n const output: ts.TypeNode[] = [];\n for (const item of items) {\n let itemType: ts.TypeNode;\n // if this is a $ref, use WithRequired if parent specifies required properties\n // (but only for valid keys)\n if (\"$ref\" in item) {\n itemType = transformSchemaObject(item, options);\n\n const resolved = options.ctx.resolve(item.$ref);\n\n // make keys required, if necessary\n if (\n resolved &&\n typeof resolved === \"object\" &&\n \"properties\" in resolved &&\n // we have already handled this item (discriminator property was already added as required)\n !options.ctx.discriminators.refsHandled.includes(item.$ref)\n ) {\n // add WithRequired if necessary\n const validRequired = (required ?? []).filter((key) => !!resolved.properties?.[key]);\n if (validRequired.length) {\n itemType = tsWithRequired(itemType, validRequired, options.ctx.injectFooter);\n }\n }\n }\n // otherwise, if this is a schema object, combine parent `required[]` with its own, if any\n else {\n const itemRequired = [...(required ?? [])];\n if (typeof item === \"object\" && Array.isArray(item.required)) {\n itemRequired.push(...item.required);\n }\n itemType = transformSchemaObject({ ...item, required: itemRequired }, options);\n }\n\n output.push(itemType);\n }\n return output;\n }\n\n // compile final type\n let finalType: ts.TypeNode | undefined;\n\n // core + allOf: intersect\n const coreObjectType = transformSchemaObjectCore(schemaObject, options);\n const allOfType = collectAllOfCompositions(schemaObject.allOf ?? [], schemaObject.required);\n if (coreObjectType || allOfType.length) {\n const allOf: ts.TypeNode | undefined = allOfType.length ? tsIntersection(allOfType) : undefined;\n finalType = tsIntersection([...(coreObjectType ? [coreObjectType] : []), ...(allOf ? [allOf] : [])]);\n }\n // anyOf: union\n // (note: this may seem counterintuitive, but as TypeScript’s unions are not true XORs, they mimic behavior closer to anyOf than oneOf)\n const anyOfType = collectUnionCompositions(schemaObject.anyOf ?? [], \"anyOf\");\n if (anyOfType.length) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...anyOfType]);\n }\n // oneOf: union (within intersection with other types, if any)\n const oneOfType = collectUnionCompositions(\n schemaObject.oneOf ||\n (\"type\" in schemaObject &&\n schemaObject.type === \"object\" &&\n (schemaObject.enum as (SchemaObject | ReferenceObject)[])) ||\n [],\n \"oneOf\",\n );\n if (oneOfType.length) {\n // note: oneOf is the only type that may include primitives\n if (oneOfType.every(tsIsPrimitive)) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...oneOfType]);\n } else {\n finalType = tsIntersection([...(finalType ? [finalType] : []), tsUnion(oneOfType)]);\n }\n }\n\n // When no final type can be generated, fall back to unknown type (or related variants)\n if (!finalType) {\n if (\"type\" in schemaObject) {\n finalType = tsRecord(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER);\n } else {\n finalType = UNKNOWN;\n }\n }\n\n if (finalType !== UNKNOWN && schemaObject.nullable) {\n finalType = tsNullable([finalType]);\n }\n\n return finalType;\n}\n\n/**\n * Check if the given OAPI enum should be transformed to a TypeScript enum\n */\nfunction shouldTransformToTsEnum(options: TransformNodeOptions, schemaObject: SchemaObject): boolean {\n // Enum conversion not enabled or no enum present\n if (!options.ctx.enum || !schemaObject.enum) {\n return false;\n }\n\n // Enum must have string, number or null values\n if (!schemaObject.enum.every((v) => [\"string\", \"number\", null].includes(typeof v))) {\n return false;\n }\n\n // If conditionalEnums is enabled, only convert if x-enum-* metadata is present\n if (options.ctx.conditionalEnums) {\n const hasEnumMetadata =\n Array.isArray(schemaObject[\"x-enum-varnames\"]) ||\n Array.isArray(schemaObject[\"x-enumNames\"]) ||\n Array.isArray(schemaObject[\"x-enum-descriptions\"]) ||\n Array.isArray(schemaObject[\"x-enumDescriptions\"]);\n if (!hasEnumMetadata) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Handle SchemaObject minus composition (anyOf/allOf/oneOf)\n */\nfunction transformSchemaObjectCore(schemaObject: SchemaObject, options: TransformNodeOptions): ts.TypeNode | undefined {\n if (\"type\" in schemaObject && schemaObject.type) {\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(schemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n if (result.questionToken) {\n return ts.factory.createUnionTypeNode([result.schema, UNDEFINED]);\n } else {\n return result.schema;\n }\n } else {\n return result;\n }\n }\n }\n\n // primitives\n // type: null\n if (schemaObject.type === \"null\") {\n return NULL;\n }\n // type: string\n if (schemaObject.type === \"string\") {\n return STRING;\n }\n // type: number / type: integer\n if (schemaObject.type === \"number\" || schemaObject.type === \"integer\") {\n return NUMBER;\n }\n // type: boolean\n if (schemaObject.type === \"boolean\") {\n return BOOLEAN;\n }\n\n // type: array (with support for tuples)\n if (schemaObject.type === \"array\") {\n // default to `unknown[]`\n let itemType: ts.TypeNode = UNKNOWN;\n // tuple type\n if (schemaObject.prefixItems || Array.isArray(schemaObject.items)) {\n const prefixItems = schemaObject.prefixItems ?? (schemaObject.items as (SchemaObject | ReferenceObject)[]);\n itemType = ts.factory.createTupleTypeNode(prefixItems.map((item) => transformSchemaObject(item, options)));\n }\n // standard array type\n else if (schemaObject.items) {\n if (hasKey(schemaObject.items, \"type\") && schemaObject.items.type === \"array\") {\n itemType = ts.factory.createArrayTypeNode(transformSchemaObject(schemaObject.items, options));\n } else {\n itemType = transformSchemaObject(schemaObject.items, options);\n }\n }\n\n const min: number =\n typeof schemaObject.minItems === \"number\" && schemaObject.minItems >= 0 ? schemaObject.minItems : 0;\n const max: number | undefined =\n typeof schemaObject.maxItems === \"number\" && schemaObject.maxItems >= 0 && min <= schemaObject.maxItems\n ? schemaObject.maxItems\n : undefined;\n const estimateCodeSize = typeof max !== \"number\" ? min : (max * (max + 1) - min * (min - 1)) / 2;\n if (\n options.ctx.arrayLength &&\n (min !== 0 || max !== undefined) &&\n estimateCodeSize < 30 // \"30\" is an arbitrary number but roughly around when TS starts to struggle with tuple inference in practice\n ) {\n if (min === max) {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n return tsUnion([ts.factory.createTupleTypeNode(elements)]);\n } else if ((schemaObject.maxItems as number) > 0) {\n // if maxItems is set, then return a union of all permutations of possible tuple types\n const members: ts.TypeNode[] = [];\n // populate 1 short of min …\n for (let i = 0; i <= (max ?? 0) - min; i++) {\n const elements: ts.TypeNode[] = [];\n for (let j = min; j < i + min; j++) {\n elements.push(itemType);\n }\n members.push(ts.factory.createTupleTypeNode(elements));\n }\n return tsUnion(members);\n }\n // if maxItems not set, then return a simple tuple type the length of `min`\n else {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n elements.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(itemType)));\n return ts.factory.createTupleTypeNode(elements);\n }\n }\n\n const finalType =\n ts.isTupleTypeNode(itemType) || ts.isArrayTypeNode(itemType)\n ? itemType\n : ts.factory.createArrayTypeNode(itemType); // wrap itemType in array type, but only if not a tuple or array already\n\n return options.ctx.immutable\n ? ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, finalType)\n : finalType;\n }\n\n // polymorphic, or 3.1 nullable\n if (Array.isArray(schemaObject.type) && !Array.isArray(schemaObject)) {\n // skip any primitive types that appear in oneOf as well\n const uniqueTypes: ts.TypeNode[] = [];\n if (Array.isArray(schemaObject.oneOf)) {\n for (const t of schemaObject.type) {\n if (\n (t === \"boolean\" || t === \"string\" || t === \"number\" || t === \"integer\" || t === \"null\") &&\n schemaObject.oneOf.find((o) => typeof o === \"object\" && \"type\" in o && o.type === t)\n ) {\n continue;\n }\n uniqueTypes.push(\n t === \"null\" || t === null\n ? NULL\n : transformSchemaObject(\n { ...schemaObject, type: t, oneOf: undefined } as SchemaObject, // don’t stack oneOf transforms\n options,\n ),\n );\n }\n } else {\n for (const t of schemaObject.type) {\n if (t === \"null\" || t === null) {\n uniqueTypes.push(NULL);\n } else {\n uniqueTypes.push(transformSchemaObject({ ...schemaObject, type: t } as SchemaObject, options));\n }\n }\n }\n return tsUnion(uniqueTypes);\n }\n }\n\n // type: object\n const coreObjectType: ts.TypeElement[] = [];\n\n // discriminators: explicit mapping on schema object\n for (const k of [\"allOf\", \"anyOf\"] as const) {\n if (!schemaObject[k]) {\n continue;\n }\n // for all magic inheritance, we will have already gathered it into\n // ctx.discriminators. But stop objects from referencing their own\n // discriminator meant for children (!schemaObject.discriminator)\n // and don't add discriminator properties if we already added/patched\n // them (options.ctx.discriminators.refsHandled.includes(options.path!).\n const discriminator =\n !schemaObject.discriminator &&\n !options.ctx.discriminators.refsHandled.includes(options.path ?? \"\") &&\n options.ctx.discriminators.objects[options.path ?? \"\"];\n if (discriminator) {\n coreObjectType.unshift(\n createDiscriminatorProperty(discriminator, {\n path: options.path ?? \"\",\n readonly: options.ctx.immutable,\n }),\n );\n break;\n }\n }\n\n if (\n (\"properties\" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length) ||\n (\"additionalProperties\" in schemaObject && schemaObject.additionalProperties) ||\n (\"patternProperties\" in schemaObject && schemaObject.patternProperties) ||\n (\"$defs\" in schemaObject && schemaObject.$defs)\n ) {\n // properties\n if (\"properties\" in schemaObject && schemaObject.properties && Object.keys(schemaObject?.properties).length) {\n for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) {\n if ((typeof v !== \"object\" && typeof v !== \"boolean\") || Array.isArray(v)) {\n throw new Error(\n `${options.path}: invalid property ${k}. Expected Schema Object or boolean, got ${\n Array.isArray(v) ? \"Array\" : typeof v\n }`,\n );\n }\n\n const { $ref, readOnly, writeOnly, hasDefault } =\n typeof v === \"object\"\n ? {\n $ref: \"$ref\" in v && v.$ref,\n readOnly: \"readOnly\" in v && v.readOnly,\n writeOnly: \"writeOnly\" in v && v.writeOnly,\n hasDefault: \"default\" in v && v.default !== undefined,\n }\n : {};\n\n // handle excludeDeprecated option\n if (options.ctx.excludeDeprecated) {\n const resolved = $ref ? options.ctx.resolve($ref) : v;\n if ((resolved as SchemaObject)?.deprecated) {\n continue;\n }\n }\n let optional =\n schemaObject.required?.includes(k) ||\n (schemaObject.required === undefined && options.ctx.propertiesRequiredByDefault) ||\n (hasDefault &&\n options.ctx.defaultNonNullable &&\n !options.path?.includes(\"parameters\") &&\n !options.path?.includes(\"requestBody\") &&\n !options.path?.includes(\"requestBodies\")) // can’t be required, even with defaults\n ? undefined\n : QUESTION_TOKEN;\n let type = $ref\n ? oapiRef($ref)\n : transformSchemaObject(v, {\n ...options,\n path: createRef([options.path, k]),\n });\n\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(v as SchemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n type = result.schema;\n optional = result.questionToken ? QUESTION_TOKEN : optional;\n } else {\n type = result;\n }\n }\n }\n\n type = wrapWithReadWriteMarker(type, !!readOnly, !!writeOnly, options.ctx);\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && readOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ optional,\n /* type */ type,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n coreObjectType.push(property);\n }\n }\n\n // $defs\n if (\"$defs\" in schemaObject && typeof schemaObject.$defs === \"object\" && Object.keys(schemaObject.$defs).length) {\n const defKeys: ts.TypeElement[] = [];\n for (const [k, v] of Object.entries(schemaObject.$defs)) {\n const defReadOnly = \"readOnly\" in v && !!v.readOnly;\n const defWriteOnly = \"writeOnly\" in v && !!v.writeOnly;\n const defType = wrapWithReadWriteMarker(\n transformSchemaObject(v, { ...options, path: createRef([options.path, \"$defs\", k]) }),\n defReadOnly,\n defWriteOnly,\n options.ctx,\n );\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && defReadOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ undefined,\n /* type */ defType,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, \"$defs\", k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n defKeys.push(property);\n }\n coreObjectType.push(\n ts.factory.createPropertySignature(\n /* modifiers */ undefined,\n /* name */ tsPropertyIndex(\"$defs\"),\n /* questionToken */ undefined,\n /* type */ ts.factory.createTypeLiteralNode(defKeys),\n ),\n );\n }\n\n // additionalProperties / patternProperties\n const hasExplicitAdditionalProperties =\n typeof schemaObject.additionalProperties === \"object\" && Object.keys(schemaObject.additionalProperties).length;\n const hasImplicitAdditionalProperties =\n schemaObject.additionalProperties === true ||\n (typeof schemaObject.additionalProperties === \"object\" &&\n Object.keys(schemaObject.additionalProperties).length === 0);\n const patternProperties = hasKey(schemaObject, \"patternProperties\") ? schemaObject.patternProperties : undefined;\n const hasExplicitPatternProperties =\n typeof patternProperties === \"object\" && patternProperties !== null && Object.keys(patternProperties).length > 0;\n const stringIndexTypes = [];\n if (hasExplicitAdditionalProperties) {\n stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties as SchemaObject, options, true));\n }\n if (hasImplicitAdditionalProperties || (!schemaObject.additionalProperties && options.ctx.additionalProperties)) {\n stringIndexTypes.push(UNKNOWN);\n }\n if (hasExplicitPatternProperties && patternProperties && typeof patternProperties === \"object\") {\n for (const [_, v] of getEntries(\n patternProperties as Record,\n options.ctx,\n )) {\n stringIndexTypes.push(transformSchemaObject(v, options));\n }\n }\n\n if (stringIndexTypes.length === 0) {\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n }\n\n const stringIndexType = tsUnion(stringIndexTypes);\n\n return tsIntersection([\n ...(coreObjectType.length ? [ts.factory.createTypeLiteralNode(coreObjectType)] : []),\n ts.factory.createTypeLiteralNode([\n ts.factory.createIndexSignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable,\n }),\n /* parameters */ [\n ts.factory.createParameterDeclaration(\n /* modifiers */ undefined,\n /* dotDotDotToken */ undefined,\n /* name */ ts.factory.createIdentifier(\"key\"),\n /* questionToken */ undefined,\n /* type */ STRING,\n ),\n ],\n /* type */ stringIndexType,\n ),\n ]),\n ]);\n }\n\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n}\n\n/**\n * Check if an object has a key\n * @param possibleObject - The object to check\n * @param key - The key to check for\n * @returns True if the object has the key, false otherwise\n */\nfunction hasKey(possibleObject: unknown, key: K): possibleObject is { [key in K]: unknown } {\n return typeof possibleObject === \"object\" && possibleObject !== null && key in possibleObject;\n}\n\nfunction applyAdditionalPropertiesToEnum(\n hasAdditionalProperties: boolean,\n unionType: ts.TypeNode,\n schemaObject: SchemaObject,\n) {\n // If additionalProperties is true, add (string & {}) to the union\n if (hasAdditionalProperties && schemaObject.type === \"string\") {\n const stringAndEmptyObject = tsIntersection([STRING, ts.factory.createTypeLiteralNode([])]);\n return tsUnion([unionType, stringAndEmptyObject]);\n }\n return unionType;\n}\n\n/** Wrap type with $Read or $Write marker when readWriteMarkers flag is enabled */\nfunction wrapWithReadWriteMarker(\n type: ts.TypeNode,\n readOnly: boolean,\n writeOnly: boolean,\n ctx: { readWriteMarkers: boolean },\n): ts.TypeNode {\n if (!ctx.readWriteMarkers || (readOnly && writeOnly)) {\n return type;\n }\n if (readOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Read\"), [type]);\n }\n if (writeOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Write\"), [type]);\n }\n return type;\n}\n"],"names":["NEVER","UNKNOWN","oapiRef","tsLiteral","parseRef","enumType","tsEnum","ts","finalType","tsUnion","NULL","createRef","tsArrayLiteralExpression","tsWithRequired","tsIntersection","tsIsPrimitive","tsRecord","STRING","tsNullable","UNDEFINED","NUMBER","BOOLEAN","createDiscriminatorProperty","getEntries","QUESTION_TOKEN","tsModifiers","tsPropertyIndex","addJSDocComment"],"mappings":";;;;;;;;;;;;;AAgCA,SAAwB,qBAAA,CACtB,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AACb,EAAA,MAAM,IAAA,GAAO,oCAAA,CAAqC,YAAA,EAAc,OAAA,EAAS,wBAAwB,CAAA;AACjG,EAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,aAAA,KAAkB,UAAA,EAAY;AACnD,IAAA,MAAM,mBAAA,GAAsB,OAAA,CAAQ,GAAA,CAAI,aAAA,CAAc,MAAM,OAAO,CAAA;AACnE,IAAA,IAAI,mBAAA,EAAqB;AACvB,MAAA,OAAO,mBAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAKO,SAAS,oCAAA,CACd,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AAMb,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAOA,QAAA;AAAA,EACT;AAEA,EAAA,IAAK,iBAA6B,IAAA,EAAM;AACtC,IAAA,OAAOC,UAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAM,OAAA,CAAQ,YAAY,CAAA,IAAK,OAAO,iBAAiB,QAAA,EAAU;AACnE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gCAAA,EAAmC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,GAAI,UAAU,OAAO,YAAY,CAAA,IAAA,EAAO,OAAA,CAAQ,IAAI,CAAA;AAAA,KACnH;AAAA,EACF;AAKA,EAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,IAAA,OAAOC,UAAA,CAAQ,aAAa,IAAI,CAAA;AAAA,EAClC;AAKA,EAAA,IAAI,YAAA,CAAa,KAAA,KAAU,IAAA,IAAQ,YAAA,CAAa,UAAU,MAAA,EAAW;AACnE,IAAA,OAAOC,YAAA,CAAU,aAAa,KAAK,CAAA;AAAA,EACrC;AAMA,EAAA,IACE,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,KAC9B,EAAE,MAAA,IAAU,YAAA,CAAA,IAAiB,YAAA,CAAa,IAAA,KAAS,QAAA,CAAA,IACpD,EAAE,gBAAgB,YAAA,CAAA,EAClB;AACA,IAAA,MAAM,uBAAA,GAA0B,sBAAA,IAA0B,YAAA,IAAgB,CAAC,CAAC,YAAA,CAAa,oBAAA;AAEzF,IAAA,IAAI,CAAC,uBAAA,IAA4B,YAAA,CAAa,IAAA,KAAS,YAAY,uBAAA,EAA0B;AAE3F,MAAA,IAAI,uBAAA,CAAwB,OAAA,EAAS,YAAY,CAAA,EAAG;AAClD,QAAA,IAAI,QAAA,GAAWC,qBAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA,CAAE,OAAA,CAAQ,KAAK,GAAG,CAAA;AAE5D,QAAA,QAAA,GAAW,QAAA,CAAS,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AACpD,QAAA,MAAM,WAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAI,CAAC,GAAG,CAAA,MAAO;AAAA,UAChD,IAAA,EAAM,aAAa,iBAAiB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,aAAa,CAAA,GAAI,CAAC,CAAA;AAAA,UAC7E,WAAA,EAAa,aAAa,qBAAqB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,oBAAoB,CAAA,GAAI,CAAC;AAAA,SACjG,CAAE,CAAA;AAGF,QAAA,IAAI,OAAA,GAAU,KAAA;AACd,QAAA,MAAM,gBAAA,GAAmB,YAAA,CAAa,IAAA,CAAK,MAAA,CAAO,CAAC,SAAA,KAAc;AAC/D,UAAA,IAAI,cAAc,IAAA,EAAM;AACtB,YAAA,OAAA,GAAU,IAAA;AACV,YAAA,OAAO,KAAA;AAAA,UACT;AAEA,UAAA,OAAO,IAAA;AAAA,QACT,CAAC,CAAA;AACD,QAAA,MAAMC,SAAAA,GAAWC,SAAA,CAAO,QAAA,EAAU,gBAAA,EAAyC,QAAA,EAAU;AAAA,UACnF,WAAA,EAAa,QAAQ,GAAA,CAAI,WAAA;AAAA,UACzB,MAAA,EAAQ;AAAA;AAAA,SAET,CAAA;AACD,QAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,QAAA,CAASD,SAAQ,CAAA,EAAG;AAChD,UAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAKA,SAAQ,CAAA;AAAA,QACxC;AACA,QAAA,MAAM,GAAA,GAAME,WAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBF,UAAS,IAAI,CAAA;AAE5D,QAAA,MAAMG,aAAyB,OAAA,GAAUC,UAAA,CAAQ,CAAC,GAAA,EAAKC,OAAI,CAAC,CAAA,GAAI,GAAA;AAEhE,QAAA,OAAO,+BAAA,CAAgC,uBAAA,EAAyBF,UAAAA,EAAW,YAAY,CAAA;AAAA,MACzF;AAEA,MAAA,MAAM,QAAA,GAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAIL,YAAS,CAAA;AAChD,MAAA,IAAK,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,IAAK,YAAA,CAAa,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,IAAM,YAAA,CAAa,QAAA,EAAU;AACrG,QAAA,QAAA,CAAS,KAAKO,OAAI,CAAA;AAAA,MACpB;AAEA,MAAA,MAAM,YAAY,+BAAA,CAAgC,uBAAA,EAAyBD,UAAA,CAAQ,QAAQ,GAAG,YAAY,CAAA;AAG1G,MAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,YAAA,CAAa,KAAK,KAAA,CAAM,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EAAG;AAC5G,QAAA,MAAM,MAAA,GAASL,oBAAA,CAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA;AAC1C,QAAA,IAAI,sBAAA,GAAyB,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA;AAEpD,QAAA,sBAAA,GAAyB,sBAAA,CAAuB,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AAChF,QAAA,sBAAA,GAAyB,GAAG,sBAAsB,CAAA,MAAA,CAAA;AAIlD,QAAA,MAAM,iBAA2B,EAAC;AAQlC,QAAA,MAAM,oBAA8B,EAAC;AACrC,QAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AAE9C,UAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,CAAC,CAAA;AAChC,UAAA,IAAA,CAAK,OAAA,KAAY,WAAW,OAAA,KAAY,OAAA,KAAY,IAAI,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACjF,YAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,CAAA,GAAI,CAAC,CAAA;AACjC,YAAA,IAAI,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,EAAG;AAEtB,cAAA,CAAA,EAAA;AAIA,cAAA,MAAM,iBAAA,GAAoB,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAC,CAAA;AACpD,cAAA,KAAA,MAAW,OAAO,iBAAA,EAAmB;AAEnC,gBAAA,IAAI,GAAA,KAAQ,WAAW,GAAA,KAAQ,OAAA,IAAW,CAAC,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,EAAG;AAC5D,kBAAA,iBAAA,CAAkB,KAAK,GAAG,CAAA;AAAA,gBAC5B;AAAA,cACF;AACA,cAAA;AAAA,YACF;AAAA,UACF;AACA,UAAA,cAAA,CAAe,KAAK,OAAO,CAAA;AAAA,QAC7B;AACA,QAAA,MAAM,cAAA,GAAiBO,gBAAU,cAAc,CAAA;AAE/C,QAAA,MAAM,eAAA,GAAkBC,2BAAA;AAAA,UACtB,sBAAA;AAAA;AAAA,UAEA,wBAAA,GACIL,YAAG,OAAA,CAAQ,2BAAA;AAAA,YACTL,WAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,YACpEK,YAAG,OAAA,CAAQ,uBAAA,CAAwBA,YAAG,OAAA,CAAQ,gBAAA,CAAiB,QAAQ,CAAC;AAAA,WAC1E,GACAL,WAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,UACxE,YAAA,CAAa,IAAA;AAAA,UACb;AAAA,YACE,MAAA,EAAQ,IAAA;AAAA,YACR,QAAA,EAAU,IAAA;AAAA,YACV,YAAA,EAAc,QAAQ,GAAA,CAAI;AAAA;AAC5B,SACF;AAEA,QAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAK,eAAe,CAAA;AAAA,MAC/C;AAEA,MAAA,OAAO,SAAA;AAAA,IACT;AAAA,EACF;AAOA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAA6B;AACxG,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,CAAC,KAAA,EAAO,IAAI,CAAA,IAAK,KAAA,CAAM,SAAQ,EAAG;AAC3C,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,sBAAsB,IAAA,EAAM;AAAA,UAC1B,GAAG,OAAA;AAAA;AAAA,UAEH,IAAA,EAAMS,gBAAU,CAAC,OAAA,CAAQ,MAAM,QAAA,EAAU,MAAA,CAAO,KAAK,CAAC,CAAC;AAAA,SACxD;AAAA,OACH;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAAoC;AAC/G,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,MAAA,IAAI,QAAA;AAGJ,MAAA,IAAI,UAAU,IAAA,EAAM;AAClB,QAAA,QAAA,GAAW,qBAAA,CAAsB,MAAM,OAAO,CAAA;AAE9C,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,KAAK,IAAI,CAAA;AAG5D,QAAA,IACE,QAAA,IACA,OAAO,QAAA,KAAa,QAAA,IACpB,YAAA,IAAgB,QAAA;AAAA,QAEhB,CAAC,QAAQ,GAAA,CAAI,cAAA,CAAe,YAAY,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAC1D;AAEA,UAAA,MAAM,aAAA,GAAA,CAAiB,QAAA,IAAY,EAAC,EAAG,MAAA,CAAO,CAAC,GAAA,KAAQ,CAAC,CAAC,QAAA,CAAS,UAAA,GAAa,GAAG,CAAC,CAAA;AACnF,UAAA,IAAI,cAAc,MAAA,EAAQ;AACxB,YAAA,QAAA,GAAWE,iBAAA,CAAe,QAAA,EAAU,aAAA,EAAe,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,UAC7E;AAAA,QACF;AAAA,MACF,CAAA,MAEK;AACH,QAAA,MAAM,YAAA,GAAe,CAAC,GAAI,QAAA,IAAY,EAAG,CAAA;AACzC,QAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,QAAQ,CAAA,EAAG;AAC5D,UAAA,YAAA,CAAa,IAAA,CAAK,GAAG,IAAA,CAAK,QAAQ,CAAA;AAAA,QACpC;AACA,QAAA,QAAA,GAAW,sBAAsB,EAAE,GAAG,MAAM,QAAA,EAAU,YAAA,IAAgB,OAAO,CAAA;AAAA,MAC/E;AAEA,MAAA,MAAA,CAAO,KAAK,QAAQ,CAAA;AAAA,IACtB;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,IAAI,SAAA;AAGJ,EAAA,MAAM,cAAA,GAAiB,yBAAA,CAA0B,YAAA,EAAc,OAAO,CAAA;AACtE,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,SAAS,EAAC,EAAG,aAAa,QAAQ,CAAA;AAC1F,EAAA,IAAI,cAAA,IAAkB,UAAU,MAAA,EAAQ;AACtC,IAAA,MAAM,KAAA,GAAiC,SAAA,CAAU,MAAA,GAASC,iBAAA,CAAe,SAAS,CAAA,GAAI,MAAA;AACtF,IAAA,SAAA,GAAYA,kBAAe,CAAC,GAAI,cAAA,GAAiB,CAAC,cAAc,CAAA,GAAI,EAAC,EAAI,GAAI,QAAQ,CAAC,KAAK,CAAA,GAAI,EAAG,CAAC,CAAA;AAAA,EACrG;AAGA,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,KAAA,IAAS,IAAI,OAAO,CAAA;AAC5E,EAAA,IAAI,UAAU,MAAA,EAAQ;AACpB,IAAA,SAAA,GAAYL,UAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,EACvE;AAEA,EAAA,MAAM,SAAA,GAAY,wBAAA;AAAA,IAChB,YAAA,CAAa,SACV,MAAA,IAAU,YAAA,IACT,aAAa,IAAA,KAAS,QAAA,IACrB,YAAA,CAAa,IAAA,IAChB,EAAC;AAAA,IACH;AAAA,GACF;AACA,EAAA,IAAI,UAAU,MAAA,EAAQ;AAEpB,IAAA,IAAI,SAAA,CAAU,KAAA,CAAMM,gBAAa,CAAA,EAAG;AAClC,MAAA,SAAA,GAAYN,UAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,IACvE,CAAA,MAAO;AACL,MAAA,SAAA,GAAYK,iBAAA,CAAe,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAIL,UAAA,CAAQ,SAAS,CAAC,CAAC,CAAA;AAAA,IACpF;AAAA,EACF;AAGA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,MAAA,SAAA,GAAYO,YAASC,SAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,mBAAA,GAAsBhB,aAAUD,QAAK,CAAA;AAAA,IAChF,CAAA,MAAO;AACL,MAAA,SAAA,GAAYC,UAAA;AAAA,IACd;AAAA,EACF;AAEA,EAAA,IAAI,SAAA,KAAcA,UAAA,IAAW,YAAA,CAAa,QAAA,EAAU;AAClD,IAAA,SAAA,GAAYiB,aAAA,CAAW,CAAC,SAAS,CAAC,CAAA;AAAA,EACpC;AAEA,EAAA,OAAO,SAAA;AACT;AAKA,SAAS,uBAAA,CAAwB,SAA+B,YAAA,EAAqC;AAEnG,EAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,IAAA,IAAQ,CAAC,aAAa,IAAA,EAAM;AAC3C,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,KAAM,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,CAAA,CAAE,QAAA,CAAS,OAAO,CAAC,CAAC,CAAA,EAAG;AAClF,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,OAAA,CAAQ,IAAI,gBAAA,EAAkB;AAChC,IAAA,MAAM,eAAA,GACJ,MAAM,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAC,CAAA,IAC7C,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,aAAa,CAAC,CAAA,IACzC,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAC,KACjD,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,oBAAoB,CAAC,CAAA;AAClD,IAAA,IAAI,CAAC,eAAA,EAAiB;AACpB,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT;AAKA,SAAS,yBAAA,CAA0B,cAA4B,OAAA,EAAwD;AACrH,EAAA,IAAI,MAAA,IAAU,YAAA,IAAgB,YAAA,CAAa,IAAA,EAAM;AAC/C,IAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,cAAc,OAAO,CAAA;AAC1D,MAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,QAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,UAAA,IAAI,OAAO,aAAA,EAAe;AACxB,YAAA,OAAOX,YAAG,OAAA,CAAQ,mBAAA,CAAoB,CAAC,MAAA,CAAO,MAAA,EAAQY,YAAS,CAAC,CAAA;AAAA,UAClE,CAAA,MAAO;AACL,YAAA,OAAO,MAAA,CAAO,MAAA;AAAA,UAChB;AAAA,QACF,CAAA,MAAO;AACL,UAAA,OAAO,MAAA;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAIA,IAAA,IAAI,YAAA,CAAa,SAAS,MAAA,EAAQ;AAChC,MAAA,OAAOT,OAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,QAAA,EAAU;AAClC,MAAA,OAAOO,SAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,IAAA,KAAS,QAAA,IAAY,YAAA,CAAa,SAAS,SAAA,EAAW;AACrE,MAAA,OAAOG,SAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,SAAA,EAAW;AACnC,MAAA,OAAOC,UAAA;AAAA,IACT;AAGA,IAAA,IAAI,YAAA,CAAa,SAAS,OAAA,EAAS;AAEjC,MAAA,IAAI,QAAA,GAAwBpB,UAAA;AAE5B,MAAA,IAAI,aAAa,WAAA,IAAe,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACjE,QAAA,MAAM,WAAA,GAAc,YAAA,CAAa,WAAA,IAAgB,YAAA,CAAa,KAAA;AAC9D,QAAA,QAAA,GAAWM,WAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,WAAA,CAAY,GAAA,CAAI,CAAC,IAAA,KAAS,qBAAA,CAAsB,IAAA,EAAM,OAAO,CAAC,CAAC,CAAA;AAAA,MAC3G,CAAA,MAAA,IAES,aAAa,KAAA,EAAO;AAC3B,QAAA,IAAI,MAAA,CAAO,aAAa,KAAA,EAAO,MAAM,KAAK,YAAA,CAAa,KAAA,CAAM,SAAS,OAAA,EAAS;AAC7E,UAAA,QAAA,GAAWA,YAAG,OAAA,CAAQ,mBAAA,CAAoB,sBAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,QAC9F,CAAA,MAAO;AACL,UAAA,QAAA,GAAW,qBAAA,CAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAA;AAAA,QAC9D;AAAA,MACF;AAEA,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,YAAY,YAAA,CAAa,QAAA,IAAY,CAAA,GAAI,YAAA,CAAa,QAAA,GAAW,CAAA;AACpG,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,QAAA,IAAY,YAAA,CAAa,QAAA,IAAY,CAAA,IAAK,GAAA,IAAO,YAAA,CAAa,QAAA,GAC3F,YAAA,CAAa,QAAA,GACb,MAAA;AACN,MAAA,MAAM,gBAAA,GAAmB,OAAO,GAAA,KAAQ,QAAA,GAAW,GAAA,GAAA,CAAO,OAAO,GAAA,GAAM,CAAA,CAAA,GAAK,GAAA,IAAO,GAAA,GAAM,CAAA,CAAA,IAAM,CAAA;AAC/F,MAAA,IACE,OAAA,CAAQ,IAAI,WAAA,KACX,GAAA,KAAQ,KAAK,GAAA,KAAQ,MAAA,CAAA,IACtB,mBAAmB,EAAA,EACnB;AACA,QAAA,IAAI,QAAQ,GAAA,EAAK;AACf,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,OAAOE,WAAQ,CAACF,WAAA,CAAG,QAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AAAA,QAC3D,CAAA,MAAA,IAAY,YAAA,CAAa,QAAA,GAAsB,CAAA,EAAG;AAEhD,UAAA,MAAM,UAAyB,EAAC;AAEhC,UAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,IAAA,CAAM,GAAA,IAAO,CAAA,IAAK,KAAK,CAAA,EAAA,EAAK;AAC1C,YAAA,MAAM,WAA0B,EAAC;AACjC,YAAA,KAAA,IAAS,CAAA,GAAI,GAAA,EAAK,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,EAAA,EAAK;AAClC,cAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,YACxB;AACA,YAAA,OAAA,CAAQ,IAAA,CAAKA,WAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAA;AAAA,UACvD;AACA,UAAA,OAAOE,WAAQ,OAAO,CAAA;AAAA,QACxB,CAAA,MAEK;AACH,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,QAAA,CAAS,IAAA,CAAKF,YAAG,OAAA,CAAQ,kBAAA,CAAmBA,YAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AACrF,UAAA,OAAOA,WAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAA;AAAA,QAChD;AAAA,MACF;AAEA,MAAA,MAAM,SAAA,GACJA,WAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,IAAKA,WAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,GACvD,QAAA,GACAA,WAAA,CAAG,OAAA,CAAQ,oBAAoB,QAAQ,CAAA;AAE7C,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,GACfA,WAAA,CAAG,OAAA,CAAQ,uBAAuBA,WAAA,CAAG,UAAA,CAAW,eAAA,EAAiB,SAAS,CAAA,GAC1E,SAAA;AAAA,IACN;AAGA,IAAA,IAAI,KAAA,CAAM,QAAQ,YAAA,CAAa,IAAI,KAAK,CAAC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,EAAG;AAEpE,MAAA,MAAM,cAA6B,EAAC;AACpC,MAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACrC,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAA,CACG,CAAA,KAAM,aAAa,CAAA,KAAM,QAAA,IAAY,MAAM,QAAA,IAAY,CAAA,KAAM,SAAA,IAAa,CAAA,KAAM,MAAA,KACjF,YAAA,CAAa,MAAM,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,UAAU,CAAA,IAAK,CAAA,CAAE,IAAA,KAAS,CAAC,CAAA,EACnF;AACA,YAAA;AAAA,UACF;AACA,UAAA,WAAA,CAAY,IAAA;AAAA,YACV,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,GAClBG,OAAA,GACA,qBAAA;AAAA,cACE,EAAE,GAAG,YAAA,EAAc,IAAA,EAAM,CAAA,EAAG,OAAO,MAAA,EAAU;AAAA;AAAA,cAC7C;AAAA;AACF,WACN;AAAA,QACF;AAAA,MACF,CAAA,MAAO;AACL,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAI,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,EAAM;AAC9B,YAAA,WAAA,CAAY,KAAKA,OAAI,CAAA;AAAA,UACvB,CAAA,MAAO;AACL,YAAA,WAAA,CAAY,IAAA,CAAK,sBAAsB,EAAE,GAAG,cAAc,IAAA,EAAM,CAAA,EAAE,EAAmB,OAAO,CAAC,CAAA;AAAA,UAC/F;AAAA,QACF;AAAA,MACF;AACA,MAAA,OAAOD,WAAQ,WAAW,CAAA;AAAA,IAC5B;AAAA,EACF;AAGA,EAAA,MAAM,iBAAmC,EAAC;AAG1C,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,OAAA,EAAS,OAAO,CAAA,EAAY;AAC3C,IAAA,IAAI,CAAC,YAAA,CAAa,CAAC,CAAA,EAAG;AACpB,MAAA;AAAA,IACF;AAMA,IAAA,MAAM,aAAA,GACJ,CAAC,YAAA,CAAa,aAAA,IACd,CAAC,OAAA,CAAQ,GAAA,CAAI,eAAe,WAAA,CAAY,QAAA,CAAS,QAAQ,IAAA,IAAQ,EAAE,KACnE,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACvD,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,cAAA,CAAe,OAAA;AAAA,QACba,kCAA4B,aAAA,EAAe;AAAA,UACzC,IAAA,EAAM,QAAQ,IAAA,IAAQ,EAAA;AAAA,UACtB,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,SACvB;AAAA,OACH;AACA,MAAA;AAAA,IACF;AAAA,EACF;AAEA,EAAA,IACG,YAAA,IAAgB,gBAAgB,YAAA,CAAa,UAAA,IAAc,OAAO,IAAA,CAAK,YAAA,CAAa,UAAU,CAAA,CAAE,MAAA,IAChG,0BAA0B,YAAA,IAAgB,YAAA,CAAa,wBACvD,mBAAA,IAAuB,YAAA,IAAgB,aAAa,iBAAA,IACpD,OAAA,IAAW,YAAA,IAAgB,YAAA,CAAa,KAAA,EACzC;AAEA,IAAA,IAAI,YAAA,IAAgB,gBAAgB,YAAA,CAAa,UAAA,IAAc,OAAO,IAAA,CAAK,YAAA,EAAc,UAAU,CAAA,CAAE,MAAA,EAAQ;AAC3G,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAKC,gBAAA,CAAW,YAAA,CAAa,UAAA,IAAc,EAAC,EAAG,OAAA,CAAQ,GAAG,CAAA,EAAG;AAC3E,QAAA,IAAK,OAAO,MAAM,QAAA,IAAY,OAAO,MAAM,SAAA,IAAc,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,EAAG;AACzE,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,EAAG,OAAA,CAAQ,IAAI,CAAA,mBAAA,EAAsB,CAAC,CAAA,yCAAA,EACpC,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAAI,OAAA,GAAU,OAAO,CACtC,CAAA;AAAA,WACF;AAAA,QACF;AAEA,QAAA,MAAM,EAAE,MAAM,QAAA,EAAU,SAAA,EAAW,YAAW,GAC5C,OAAO,MAAM,QAAA,GACT;AAAA,UACE,IAAA,EAAM,MAAA,IAAU,CAAA,IAAK,CAAA,CAAE,IAAA;AAAA,UACvB,QAAA,EAAU,UAAA,IAAc,CAAA,IAAK,CAAA,CAAE,QAAA;AAAA,UAC/B,SAAA,EAAW,WAAA,IAAe,CAAA,IAAK,CAAA,CAAE,SAAA;AAAA,UACjC,UAAA,EAAY,SAAA,IAAa,CAAA,IAAK,CAAA,CAAE,OAAA,KAAY;AAAA,YAE9C,EAAC;AAGP,QAAA,IAAI,OAAA,CAAQ,IAAI,iBAAA,EAAmB;AACjC,UAAA,MAAM,WAAW,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,IAAI,CAAA,GAAI,CAAA;AAClE,UAAA,IAAK,UAA2B,UAAA,EAAY;AAC1C,YAAA;AAAA,UACF;AAAA,QACF;AACA,QAAA,IAAI,QAAA,GACF,YAAA,CAAa,QAAA,EAAU,QAAA,CAAS,CAAC,CAAA,IAChC,YAAA,CAAa,QAAA,KAAa,MAAA,IAAa,QAAQ,GAAA,CAAI,2BAAA,IACnD,UAAA,IACC,OAAA,CAAQ,IAAI,kBAAA,IACZ,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,YAAY,CAAA,IACpC,CAAC,QAAQ,IAAA,EAAM,QAAA,CAAS,aAAa,CAAA,IACrC,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,eAAe,IACrC,MAAA,GACAC,iBAAA;AACN,QAAA,IAAI,OAAO,IAAA,GACPtB,UAAA,CAAQ,IAAI,CAAA,GACZ,sBAAsB,CAAA,EAAG;AAAA,UACvB,GAAG,OAAA;AAAA,UACH,MAAMS,eAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,SAClC,CAAA;AAEL,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,GAAmB,OAAO,CAAA;AAC/D,UAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,YAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,cAAA,IAAA,GAAO,MAAA,CAAO,MAAA;AACd,cAAA,QAAA,GAAW,MAAA,CAAO,gBAAgBa,iBAAA,GAAiB,QAAA;AAAA,YACrD,CAAA,MAAO;AACL,cAAA,IAAA,GAAO,MAAA;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAEA,QAAA,IAAA,GAAO,uBAAA,CAAwB,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC,SAAA,EAAW,OAAA,CAAQ,GAAG,CAAA;AAEzE,QAAA,IAAI,QAAA,GAAWjB,YAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACJkB,cAAA,CAAY;AAAA,YAC9B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmBC,mBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,QAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAMf,eAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,WAClC,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAAgB,kBAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,cAAA,CAAe,KAAK,QAAQ,CAAA;AAAA,MAC9B;AAAA,IACF;AAGA,IAAA,IAAI,OAAA,IAAW,YAAA,IAAgB,OAAO,YAAA,CAAa,KAAA,KAAU,QAAA,IAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,KAAK,CAAA,CAAE,MAAA,EAAQ;AAC/G,MAAA,MAAM,UAA4B,EAAC;AACnC,MAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACvD,QAAA,MAAM,WAAA,GAAc,UAAA,IAAc,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,QAAA;AAC3C,QAAA,MAAM,YAAA,GAAe,WAAA,IAAe,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,SAAA;AAC7C,QAAA,MAAM,OAAA,GAAU,uBAAA;AAAA,UACd,qBAAA,CAAsB,CAAA,EAAG,EAAE,GAAG,SAAS,IAAA,EAAMhB,eAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC,GAAG,CAAA;AAAA,UACpF,WAAA;AAAA,UACA,YAAA;AAAA,UACA,OAAA,CAAQ;AAAA,SACV;AAEA,QAAA,IAAI,QAAA,GAAWJ,YAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACLkB,cAAA,CAAY;AAAA,YAC7B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmBC,mBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,MAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAMf,eAAA,CAAU,CAAC,QAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC;AAAA,WAC3C,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAAgB,kBAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,OAAA,CAAQ,KAAK,QAAQ,CAAA;AAAA,MACvB;AACA,MAAA,cAAA,CAAe,IAAA;AAAA,QACbpB,YAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACW,MAAA;AAAA;AAAA,UACAmB,mBAAgB,OAAO,CAAA;AAAA;AAAA,UACvB,MAAA;AAAA;AAAA,UACAnB,WAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,OAAO;AAAA;AAC9D,OACF;AAAA,IACF;AAGA,IAAA,MAAM,+BAAA,GACJ,OAAO,YAAA,CAAa,oBAAA,KAAyB,YAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,CAAA,CAAE,MAAA;AAC1G,IAAA,MAAM,+BAAA,GACJ,YAAA,CAAa,oBAAA,KAAyB,IAAA,IACrC,OAAO,YAAA,CAAa,oBAAA,KAAyB,QAAA,IAC5C,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,EAAE,MAAA,KAAW,CAAA;AAC9D,IAAA,MAAM,oBAAoB,MAAA,CAAO,YAAA,EAAc,mBAAmB,CAAA,GAAI,aAAa,iBAAA,GAAoB,MAAA;AACvG,IAAA,MAAM,4BAAA,GACJ,OAAO,iBAAA,KAAsB,QAAA,IAAY,iBAAA,KAAsB,QAAQ,MAAA,CAAO,IAAA,CAAK,iBAAiB,CAAA,CAAE,MAAA,GAAS,CAAA;AACjH,IAAA,MAAM,mBAAmB,EAAC;AAC1B,IAAA,IAAI,+BAAA,EAAiC;AACnC,MAAA,gBAAA,CAAiB,KAAK,qBAAA,CAAsB,YAAA,CAAa,oBAAA,EAAsC,OAAA,EAAS,IAAI,CAAC,CAAA;AAAA,IAC/G;AACA,IAAA,IAAI,mCAAoC,CAAC,YAAA,CAAa,oBAAA,IAAwB,OAAA,CAAQ,IAAI,oBAAA,EAAuB;AAC/G,MAAA,gBAAA,CAAiB,KAAKN,UAAO,CAAA;AAAA,IAC/B;AACA,IAAA,IAAI,4BAAA,IAAgC,iBAAA,IAAqB,OAAO,iBAAA,KAAsB,QAAA,EAAU;AAC9F,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAKsB,gBAAA;AAAA,QACnB,iBAAA;AAAA,QACA,OAAA,CAAQ;AAAA,OACV,EAAG;AACD,QAAA,gBAAA,CAAiB,IAAA,CAAK,qBAAA,CAAsB,CAAA,EAAG,OAAO,CAAC,CAAA;AAAA,MACzD;AAAA,IACF;AAEA,IAAA,IAAI,gBAAA,CAAiB,WAAW,CAAA,EAAG;AACjC,MAAA,OAAO,eAAe,MAAA,GAAShB,WAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AAAA,IACpF;AAEA,IAAA,MAAM,eAAA,GAAkBE,WAAQ,gBAAgB,CAAA;AAEhD,IAAA,OAAOK,iBAAA,CAAe;AAAA,MACpB,GAAI,cAAA,CAAe,MAAA,GAAS,CAACP,WAAA,CAAG,QAAQ,qBAAA,CAAsB,cAAc,CAAC,CAAA,GAAI,EAAC;AAAA,MAClFA,WAAA,CAAG,QAAQ,qBAAA,CAAsB;AAAA,QAC/BA,YAAG,OAAA,CAAQ,oBAAA;AAAA;AAAA,UACQkB,cAAA,CAAY;AAAA,YAC3B,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,WACvB,CAAA;AAAA;AAAA,UACgB;AAAA,YACflB,YAAG,OAAA,CAAQ,0BAAA;AAAA;AAAA,cACY,MAAA;AAAA;AAAA,cACA,MAAA;AAAA;AAAA,cACAA,WAAA,CAAG,OAAA,CAAQ,gBAAA,CAAiB,KAAK,CAAA;AAAA;AAAA,cACjC,MAAA;AAAA;AAAA,cACAU;AAAA;AACvB,WACF;AAAA;AAAA,UACiB;AAAA;AACnB,OACD;AAAA,KACF,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,eAAe,MAAA,GAASV,WAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AACpF;AAQA,SAAS,MAAA,CAAyB,gBAAyB,GAAA,EAAmD;AAC5G,EAAA,OAAO,OAAO,cAAA,KAAmB,QAAA,IAAY,cAAA,KAAmB,QAAQ,GAAA,IAAO,cAAA;AACjF;AAEA,SAAS,+BAAA,CACP,uBAAA,EACA,SAAA,EACA,YAAA,EACA;AAEA,EAAA,IAAI,uBAAA,IAA2B,YAAA,CAAa,IAAA,KAAS,QAAA,EAAU;AAC7D,IAAA,MAAM,oBAAA,GAAuBO,iBAAA,CAAe,CAACG,SAAA,EAAQV,WAAA,CAAG,QAAQ,qBAAA,CAAsB,EAAE,CAAC,CAAC,CAAA;AAC1F,IAAA,OAAOE,UAAA,CAAQ,CAAC,SAAA,EAAW,oBAAoB,CAAC,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,SAAA;AACT;AAGA,SAAS,uBAAA,CACP,IAAA,EACA,QAAA,EACA,SAAA,EACA,GAAA,EACa;AACb,EAAA,IAAI,CAAC,GAAA,CAAI,gBAAA,IAAqB,QAAA,IAAY,SAAA,EAAY;AACpD,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAOF,WAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBA,WAAA,CAAG,OAAA,CAAQ,iBAAiB,OAAO,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,OAAOA,WAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBA,WAAA,CAAG,OAAA,CAAQ,iBAAiB,QAAQ,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACzF;AACA,EAAA,OAAO,IAAA;AACT;;;;;"} +\ No newline at end of file +diff --git a/dist/transform/schema-object.mjs b/dist/transform/schema-object.mjs +index dc20a5c14b1320364a71a254b79415bd214f4416..989814efa12f6293e4a274eb980a80f808cc503b 100644 +--- a/dist/transform/schema-object.mjs ++++ b/dist/transform/schema-object.mjs +@@ -1,6 +1,6 @@ + import { parseRef } from '@redocly/openapi-core/lib/ref-utils.js'; + import ts from 'typescript'; +-import { NEVER, UNKNOWN, oapiRef, tsLiteral, tsEnum, tsUnion, NULL, tsArrayLiteralExpression, tsIntersection, tsIsPrimitive, tsRecord, STRING, tsNullable, UNDEFINED, NUMBER, BOOLEAN, QUESTION_TOKEN, tsModifiers, tsPropertyIndex, addJSDocComment, tsWithRequired, tsOmit } from '../lib/ts.mjs'; ++import { NEVER, UNKNOWN, oapiRef, tsLiteral, tsEnum, tsUnion, NULL, tsArrayLiteralExpression, tsIntersection, tsIsPrimitive, tsRecord, STRING, tsNullable, UNDEFINED, NUMBER, BOOLEAN, QUESTION_TOKEN, tsModifiers, tsPropertyIndex, addJSDocComment, tsWithRequired } from '../lib/ts.mjs'; + import { createRef, createDiscriminatorProperty, getEntries } from '../lib/utils.mjs'; + + function transformSchemaObject(schemaObject, options, fromAdditionalProperties = false) { +@@ -31,80 +31,84 @@ function transformSchemaObjectWithComposition(schemaObject, options, fromAdditio + if (schemaObject.const !== null && schemaObject.const !== void 0) { + return tsLiteral(schemaObject.const); + } +- if (Array.isArray(schemaObject.enum) && (!("type" in schemaObject) || schemaObject.type !== "object") && !("properties" in schemaObject) && !("additionalProperties" in schemaObject)) { +- if (shouldTransformToTsEnum(options, schemaObject)) { +- let enumName = parseRef(options.path ?? "").pointer.join("/"); +- enumName = enumName.replace("components/schemas", ""); +- const metadata = schemaObject.enum.map((_, i) => ({ +- name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], +- description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i] +- })); +- let hasNull = false; +- const validSchemaEnums = schemaObject.enum.filter((enumValue) => { +- if (enumValue === null) { +- hasNull = true; +- return false; ++ if (Array.isArray(schemaObject.enum) && (!("type" in schemaObject) || schemaObject.type !== "object") && !("properties" in schemaObject)) { ++ const hasAdditionalProperties = "additionalProperties" in schemaObject && !!schemaObject.additionalProperties; ++ if (!hasAdditionalProperties || schemaObject.type === "string" && hasAdditionalProperties) { ++ if (shouldTransformToTsEnum(options, schemaObject)) { ++ let enumName = parseRef(options.path ?? "").pointer.join("/"); ++ enumName = enumName.replace("components/schemas", ""); ++ const metadata = schemaObject.enum.map((_, i) => ({ ++ name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], ++ description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i] ++ })); ++ let hasNull = false; ++ const validSchemaEnums = schemaObject.enum.filter((enumValue) => { ++ if (enumValue === null) { ++ hasNull = true; ++ return false; ++ } ++ return true; ++ }); ++ const enumType2 = tsEnum(enumName, validSchemaEnums, metadata, { ++ shouldCache: options.ctx.dedupeEnums, ++ export: true ++ // readonly: TS enum do not support the readonly modifier ++ }); ++ if (!options.ctx.injectFooter.includes(enumType2)) { ++ options.ctx.injectFooter.push(enumType2); + } +- return true; +- }); +- const enumType2 = tsEnum(enumName, validSchemaEnums, metadata, { +- shouldCache: options.ctx.dedupeEnums, +- export: true +- // readonly: TS enum do not support the readonly modifier +- }); +- if (!options.ctx.injectFooter.includes(enumType2)) { +- options.ctx.injectFooter.push(enumType2); ++ const ref = ts.factory.createTypeReferenceNode(enumType2.name); ++ const finalType2 = hasNull ? tsUnion([ref, NULL]) : ref; ++ return applyAdditionalPropertiesToEnum(hasAdditionalProperties, finalType2, schemaObject); + } +- const ref = ts.factory.createTypeReferenceNode(enumType2.name); +- return hasNull ? tsUnion([ref, NULL]) : ref; +- } +- const enumType = schemaObject.enum.map(tsLiteral); +- if (Array.isArray(schemaObject.type) && schemaObject.type.includes("null") || schemaObject.nullable) { +- enumType.push(NULL); +- } +- const unionType = tsUnion(enumType); +- if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { +- const parsed = parseRef(options.path ?? ""); +- let enumValuesVariableName = parsed.pointer.join("/"); +- enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); +- enumValuesVariableName = `${enumValuesVariableName}Values`; +- const cleanedPointer = []; +- const extractProperties = []; +- for (let i = 0; i < parsed.pointer.length; i++) { +- const segment = parsed.pointer[i]; +- if ((segment === "anyOf" || segment === "oneOf") && i < parsed.pointer.length - 1) { +- const next = parsed.pointer[i + 1]; +- if (/^\d+$/.test(next)) { +- i++; +- const remainingSegments = parsed.pointer.slice(i + 1); +- for (const seg of remainingSegments) { +- if (seg !== "anyOf" && seg !== "oneOf" && !/^\d+$/.test(seg)) { +- extractProperties.push(seg); ++ const enumType = schemaObject.enum.map(tsLiteral); ++ if (Array.isArray(schemaObject.type) && schemaObject.type.includes("null") || schemaObject.nullable) { ++ enumType.push(NULL); ++ } ++ const unionType = applyAdditionalPropertiesToEnum(hasAdditionalProperties, tsUnion(enumType), schemaObject); ++ if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { ++ const parsed = parseRef(options.path ?? ""); ++ let enumValuesVariableName = parsed.pointer.join("/"); ++ enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); ++ enumValuesVariableName = `${enumValuesVariableName}Values`; ++ const cleanedPointer = []; ++ const extractProperties = []; ++ for (let i = 0; i < parsed.pointer.length; i++) { ++ const segment = parsed.pointer[i]; ++ if ((segment === "anyOf" || segment === "oneOf") && i < parsed.pointer.length - 1) { ++ const next = parsed.pointer[i + 1]; ++ if (/^\d+$/.test(next)) { ++ i++; ++ const remainingSegments = parsed.pointer.slice(i + 1); ++ for (const seg of remainingSegments) { ++ if (seg !== "anyOf" && seg !== "oneOf" && !/^\d+$/.test(seg)) { ++ extractProperties.push(seg); ++ } + } ++ continue; + } +- continue; + } ++ cleanedPointer.push(segment); + } +- cleanedPointer.push(segment); ++ const cleanedRefPath = createRef(cleanedPointer); ++ const enumValuesArray = tsArrayLiteralExpression( ++ enumValuesVariableName, ++ // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type ++ fromAdditionalProperties ? ts.factory.createIndexedAccessTypeNode( ++ oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), ++ ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("string")) ++ ) : oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), ++ schemaObject.enum, ++ { ++ export: true, ++ readonly: true, ++ injectFooter: options.ctx.injectFooter ++ } ++ ); ++ options.ctx.injectFooter.push(enumValuesArray); + } +- const cleanedRefPath = createRef(cleanedPointer); +- const enumValuesArray = tsArrayLiteralExpression( +- enumValuesVariableName, +- // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type +- fromAdditionalProperties ? ts.factory.createIndexedAccessTypeNode( +- oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), +- ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("string")) +- ) : oapiRef(cleanedRefPath, void 0, { deep: true, extractProperties }), +- schemaObject.enum, +- { +- export: true, +- readonly: true, +- injectFooter: options.ctx.injectFooter +- } +- ); +- options.ctx.injectFooter.push(enumValuesArray); ++ return unionType; + } +- return unionType; + } + function collectUnionCompositions(items, unionKey) { + const output = []; +@@ -140,12 +144,7 @@ function transformSchemaObjectWithComposition(schemaObject, options, fromAdditio + } + itemType = transformSchemaObject({ ...item, required: itemRequired }, options); + } +- const discriminator = "$ref" in item && options.ctx.discriminators.objects[item.$ref] || item.discriminator; +- if (discriminator) { +- output.push(tsOmit(itemType, [discriminator.propertyName])); +- } else { +- output.push(itemType); +- } ++ output.push(itemType); + } + return output; + } +@@ -314,7 +313,7 @@ function transformSchemaObjectCore(schemaObject, options) { + } + } + if ("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length || "additionalProperties" in schemaObject && schemaObject.additionalProperties || "patternProperties" in schemaObject && schemaObject.patternProperties || "$defs" in schemaObject && schemaObject.$defs) { +- if (Object.keys(schemaObject.properties ?? {}).length) { ++ if ("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject?.properties).length) { + for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) { + if (typeof v !== "object" && typeof v !== "boolean" || Array.isArray(v)) { + throw new Error( +@@ -375,7 +374,7 @@ function transformSchemaObjectCore(schemaObject, options) { + coreObjectType.push(property); + } + } +- if (schemaObject.$defs && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { ++ if ("$defs" in schemaObject && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { + const defKeys = []; + for (const [k, v] of Object.entries(schemaObject.$defs)) { + const defReadOnly = "readOnly" in v && !!v.readOnly; +@@ -425,7 +424,8 @@ function transformSchemaObjectCore(schemaObject, options) { + } + const hasExplicitAdditionalProperties = typeof schemaObject.additionalProperties === "object" && Object.keys(schemaObject.additionalProperties).length; + const hasImplicitAdditionalProperties = schemaObject.additionalProperties === true || typeof schemaObject.additionalProperties === "object" && Object.keys(schemaObject.additionalProperties).length === 0; +- const hasExplicitPatternProperties = typeof schemaObject.patternProperties === "object" && Object.keys(schemaObject.patternProperties).length; ++ const patternProperties = hasKey(schemaObject, "patternProperties") ? schemaObject.patternProperties : void 0; ++ const hasExplicitPatternProperties = typeof patternProperties === "object" && patternProperties !== null && Object.keys(patternProperties).length > 0; + const stringIndexTypes = []; + if (hasExplicitAdditionalProperties) { + stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties, options, true)); +@@ -433,8 +433,11 @@ function transformSchemaObjectCore(schemaObject, options) { + if (hasImplicitAdditionalProperties || !schemaObject.additionalProperties && options.ctx.additionalProperties) { + stringIndexTypes.push(UNKNOWN); + } +- if (hasExplicitPatternProperties) { +- for (const [_, v] of getEntries(schemaObject.patternProperties ?? {}, options.ctx)) { ++ if (hasExplicitPatternProperties && patternProperties && typeof patternProperties === "object") { ++ for (const [_, v] of getEntries( ++ patternProperties, ++ options.ctx ++ )) { + stringIndexTypes.push(transformSchemaObject(v, options)); + } + } +@@ -476,6 +479,13 @@ function transformSchemaObjectCore(schemaObject, options) { + function hasKey(possibleObject, key) { + return typeof possibleObject === "object" && possibleObject !== null && key in possibleObject; + } ++function applyAdditionalPropertiesToEnum(hasAdditionalProperties, unionType, schemaObject) { ++ if (hasAdditionalProperties && schemaObject.type === "string") { ++ const stringAndEmptyObject = tsIntersection([STRING, ts.factory.createTypeLiteralNode([])]); ++ return tsUnion([unionType, stringAndEmptyObject]); ++ } ++ return unionType; ++} + function wrapWithReadWriteMarker(type, readOnly, writeOnly, ctx) { + if (!ctx.readWriteMarkers || readOnly && writeOnly) { + return type; +diff --git a/dist/transform/schema-object.mjs.map b/dist/transform/schema-object.mjs.map +index 452cebcb435ee9d7123da76c7ff2b10c6e53a494..b0d6edffb8fda895ed37f45a99f673143803960c 100644 +--- a/dist/transform/schema-object.mjs.map ++++ b/dist/transform/schema-object.mjs.map +@@ -1 +1 @@ +-{"version":3,"file":"schema-object.mjs","sources":["../../src/transform/schema-object.ts"],"sourcesContent":["import { parseRef } from \"@redocly/openapi-core/lib/ref-utils.js\";\nimport ts from \"typescript\";\nimport {\n addJSDocComment,\n BOOLEAN,\n NEVER,\n NULL,\n NUMBER,\n oapiRef,\n QUESTION_TOKEN,\n STRING,\n tsArrayLiteralExpression,\n tsEnum,\n tsIntersection,\n tsIsPrimitive,\n tsLiteral,\n tsModifiers,\n tsNullable,\n tsOmit,\n tsPropertyIndex,\n tsRecord,\n tsUnion,\n tsWithRequired,\n UNDEFINED,\n UNKNOWN,\n} from \"../lib/ts.js\";\nimport { createDiscriminatorProperty, createRef, getEntries } from \"../lib/utils.js\";\nimport type { ReferenceObject, SchemaObject, TransformNodeOptions } from \"../types.js\";\n\n/**\n * Transform SchemaObject nodes (4.8.24)\n * @see https://spec.openapis.org/oas/v3.1.0#schema-object\n */\nexport default function transformSchemaObject(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n const type = transformSchemaObjectWithComposition(schemaObject, options, fromAdditionalProperties);\n if (typeof options.ctx.postTransform === \"function\") {\n const postTransformResult = options.ctx.postTransform(type, options);\n if (postTransformResult) {\n return postTransformResult;\n }\n }\n return type;\n}\n\n/**\n * Transform SchemaObjects\n */\nexport function transformSchemaObjectWithComposition(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n /**\n * Unexpected types & edge cases\n */\n\n // missing/falsy type returns `never`\n if (!schemaObject) {\n return NEVER;\n }\n // `true` returns `unknown` (this exists, but is untyped)\n if ((schemaObject as unknown) === true) {\n return UNKNOWN;\n }\n // for any other unexpected type, throw error\n if (Array.isArray(schemaObject) || typeof schemaObject !== \"object\") {\n throw new Error(\n `Expected SchemaObject, received ${Array.isArray(schemaObject) ? \"Array\" : typeof schemaObject} at ${options.path}`,\n );\n }\n\n /**\n * ReferenceObject\n */\n if (\"$ref\" in schemaObject) {\n return oapiRef(schemaObject.$ref);\n }\n\n /**\n * const (valid for any type)\n */\n if (schemaObject.const !== null && schemaObject.const !== undefined) {\n return tsLiteral(schemaObject.const);\n }\n\n /**\n * enum (non-objects)\n * note: enum is valid for any type, but for objects, handle in oneOf below\n */\n if (\n Array.isArray(schemaObject.enum) &&\n (!(\"type\" in schemaObject) || schemaObject.type !== \"object\") &&\n !(\"properties\" in schemaObject) &&\n !(\"additionalProperties\" in schemaObject)\n ) {\n // hoist enum to top level if string/number enum and option is enabled\n if (shouldTransformToTsEnum(options, schemaObject)) {\n let enumName = parseRef(options.path ?? \"\").pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumName = enumName.replace(\"components/schemas\", \"\");\n const metadata = schemaObject.enum.map((_, i) => ({\n name: schemaObject[\"x-enum-varnames\"]?.[i] ?? schemaObject[\"x-enumNames\"]?.[i],\n description: schemaObject[\"x-enum-descriptions\"]?.[i] ?? schemaObject[\"x-enumDescriptions\"]?.[i],\n }));\n\n // enums can contain null values, but dont want to output them\n let hasNull = false;\n const validSchemaEnums = schemaObject.enum.filter((enumValue) => {\n if (enumValue === null) {\n hasNull = true;\n return false;\n }\n\n return true;\n });\n const enumType = tsEnum(enumName, validSchemaEnums as (string | number)[], metadata, {\n shouldCache: options.ctx.dedupeEnums,\n export: true,\n // readonly: TS enum do not support the readonly modifier\n });\n if (!options.ctx.injectFooter.includes(enumType)) {\n options.ctx.injectFooter.push(enumType);\n }\n const ref = ts.factory.createTypeReferenceNode(enumType.name);\n return hasNull ? tsUnion([ref, NULL]) : ref;\n }\n const enumType = schemaObject.enum.map(tsLiteral);\n if ((Array.isArray(schemaObject.type) && schemaObject.type.includes(\"null\")) || schemaObject.nullable) {\n enumType.push(NULL);\n }\n\n const unionType = tsUnion(enumType);\n\n // hoist array with valid enum values to top level if string/number enum and option is enabled\n if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === \"string\" || typeof v === \"number\")) {\n const parsed = parseRef(options.path ?? \"\");\n let enumValuesVariableName = parsed.pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumValuesVariableName = enumValuesVariableName.replace(\"components/schemas\", \"\");\n enumValuesVariableName = `${enumValuesVariableName}Values`;\n\n // build a ref path for the type that ignores union indices (anyOf/oneOf) so\n // type references remain stable even when names include union positions\n const cleanedPointer: string[] = [];\n // Track ALL properties after a oneOf/anyOf that need Extract<> narrowing.\n // We apply Extract<> before EVERY property access after a union index because:\n // - When the property exists on ALL variants, Extract<> is a no-op (returns same type)\n // - When the property only exists on SOME variants, it correctly narrows the union\n // - When both variants have same property name but different inner schemas,\n // we still narrow at each level to handle nested unions correctly\n // This robust approach handles both simple and complex union structures.\n const extractProperties: string[] = [];\n for (let i = 0; i < parsed.pointer.length; i++) {\n // Example: #/paths/analytics/data/get/responses/400/content/application/json/anyOf/0/message\n const segment = parsed.pointer[i];\n if ((segment === \"anyOf\" || segment === \"oneOf\") && i < parsed.pointer.length - 1) {\n const next = parsed.pointer[i + 1];\n if (/^\\d+$/.test(next)) {\n // If we encounter something like \"anyOf/0\", we want to skip that part of the path\n i++;\n // Collect ALL remaining segments after the union index.\n // Each one will be wrapped with Extract<> to safely narrow the type\n // at each level, handling both top-level and nested union variants.\n const remainingSegments = parsed.pointer.slice(i + 1);\n for (const seg of remainingSegments) {\n // Skip union keywords and indices, only add actual property names\n if (seg !== \"anyOf\" && seg !== \"oneOf\" && !/^\\d+$/.test(seg)) {\n extractProperties.push(seg);\n }\n }\n continue;\n }\n }\n cleanedPointer.push(segment);\n }\n const cleanedRefPath = createRef(cleanedPointer);\n\n const enumValuesArray = tsArrayLiteralExpression(\n enumValuesVariableName,\n // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type\n fromAdditionalProperties\n ? ts.factory.createIndexedAccessTypeNode(\n oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"string\")),\n )\n : oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n schemaObject.enum as (string | number)[],\n {\n export: true,\n readonly: true,\n injectFooter: options.ctx.injectFooter,\n },\n );\n\n options.ctx.injectFooter.push(enumValuesArray);\n }\n\n return unionType;\n }\n\n /**\n * Object + composition (anyOf/allOf/oneOf) types\n */\n\n /** Collect oneOf/anyOf */\n function collectUnionCompositions(items: (SchemaObject | ReferenceObject)[], unionKey: \"anyOf\" | \"oneOf\") {\n const output: ts.TypeNode[] = [];\n for (const [index, item] of items.entries()) {\n output.push(\n transformSchemaObject(item, {\n ...options,\n // include index in path so generated names from nested enums/enumValues are unique\n path: createRef([options.path, unionKey, String(index)]),\n }),\n );\n }\n\n return output;\n }\n\n /** Collect allOf with Omit<> for discriminators */\n function collectAllOfCompositions(items: (SchemaObject | ReferenceObject)[], required?: string[]): ts.TypeNode[] {\n const output: ts.TypeNode[] = [];\n for (const item of items) {\n let itemType: ts.TypeNode;\n // if this is a $ref, use WithRequired if parent specifies required properties\n // (but only for valid keys)\n if (\"$ref\" in item) {\n itemType = transformSchemaObject(item, options);\n\n const resolved = options.ctx.resolve(item.$ref);\n\n // make keys required, if necessary\n if (\n resolved &&\n typeof resolved === \"object\" &&\n \"properties\" in resolved &&\n // we have already handled this item (discriminator property was already added as required)\n !options.ctx.discriminators.refsHandled.includes(item.$ref)\n ) {\n // add WithRequired if necessary\n const validRequired = (required ?? []).filter((key) => !!resolved.properties?.[key]);\n if (validRequired.length) {\n itemType = tsWithRequired(itemType, validRequired, options.ctx.injectFooter);\n }\n }\n }\n // otherwise, if this is a schema object, combine parent `required[]` with its own, if any\n else {\n const itemRequired = [...(required ?? [])];\n if (typeof item === \"object\" && Array.isArray(item.required)) {\n itemRequired.push(...item.required);\n }\n itemType = transformSchemaObject({ ...item, required: itemRequired }, options);\n }\n\n const discriminator =\n (\"$ref\" in item && options.ctx.discriminators.objects[item.$ref]) || (item as any).discriminator;\n if (discriminator) {\n output.push(tsOmit(itemType, [discriminator.propertyName]));\n } else {\n output.push(itemType);\n }\n }\n return output;\n }\n\n // compile final type\n let finalType: ts.TypeNode | undefined;\n\n // core + allOf: intersect\n const coreObjectType = transformSchemaObjectCore(schemaObject, options);\n const allOfType = collectAllOfCompositions(schemaObject.allOf ?? [], schemaObject.required);\n if (coreObjectType || allOfType.length) {\n const allOf: ts.TypeNode | undefined = allOfType.length ? tsIntersection(allOfType) : undefined;\n finalType = tsIntersection([...(coreObjectType ? [coreObjectType] : []), ...(allOf ? [allOf] : [])]);\n }\n // anyOf: union\n // (note: this may seem counterintuitive, but as TypeScript’s unions are not true XORs, they mimic behavior closer to anyOf than oneOf)\n const anyOfType = collectUnionCompositions(schemaObject.anyOf ?? [], \"anyOf\");\n if (anyOfType.length) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...anyOfType]);\n }\n // oneOf: union (within intersection with other types, if any)\n const oneOfType = collectUnionCompositions(\n schemaObject.oneOf ||\n (\"type\" in schemaObject &&\n schemaObject.type === \"object\" &&\n (schemaObject.enum as (SchemaObject | ReferenceObject)[])) ||\n [],\n \"oneOf\",\n );\n if (oneOfType.length) {\n // note: oneOf is the only type that may include primitives\n if (oneOfType.every(tsIsPrimitive)) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...oneOfType]);\n } else {\n finalType = tsIntersection([...(finalType ? [finalType] : []), tsUnion(oneOfType)]);\n }\n }\n\n // When no final type can be generated, fall back to unknown type (or related variants)\n if (!finalType) {\n if (\"type\" in schemaObject) {\n finalType = tsRecord(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER);\n } else {\n finalType = UNKNOWN;\n }\n }\n\n if (finalType !== UNKNOWN && schemaObject.nullable) {\n finalType = tsNullable([finalType]);\n }\n\n return finalType;\n}\n\n/**\n * Check if the given OAPI enum should be transformed to a TypeScript enum\n */\nfunction shouldTransformToTsEnum(options: TransformNodeOptions, schemaObject: SchemaObject): boolean {\n // Enum conversion not enabled or no enum present\n if (!options.ctx.enum || !schemaObject.enum) {\n return false;\n }\n\n // Enum must have string, number or null values\n if (!schemaObject.enum.every((v) => [\"string\", \"number\", null].includes(typeof v))) {\n return false;\n }\n\n // If conditionalEnums is enabled, only convert if x-enum-* metadata is present\n if (options.ctx.conditionalEnums) {\n const hasEnumMetadata =\n Array.isArray(schemaObject[\"x-enum-varnames\"]) ||\n Array.isArray(schemaObject[\"x-enumNames\"]) ||\n Array.isArray(schemaObject[\"x-enum-descriptions\"]) ||\n Array.isArray(schemaObject[\"x-enumDescriptions\"]);\n if (!hasEnumMetadata) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Handle SchemaObject minus composition (anyOf/allOf/oneOf)\n */\nfunction transformSchemaObjectCore(schemaObject: SchemaObject, options: TransformNodeOptions): ts.TypeNode | undefined {\n if (\"type\" in schemaObject && schemaObject.type) {\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(schemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n if (result.questionToken) {\n return ts.factory.createUnionTypeNode([result.schema, UNDEFINED]);\n } else {\n return result.schema;\n }\n } else {\n return result;\n }\n }\n }\n\n // primitives\n // type: null\n if (schemaObject.type === \"null\") {\n return NULL;\n }\n // type: string\n if (schemaObject.type === \"string\") {\n return STRING;\n }\n // type: number / type: integer\n if (schemaObject.type === \"number\" || schemaObject.type === \"integer\") {\n return NUMBER;\n }\n // type: boolean\n if (schemaObject.type === \"boolean\") {\n return BOOLEAN;\n }\n\n // type: array (with support for tuples)\n if (schemaObject.type === \"array\") {\n // default to `unknown[]`\n let itemType: ts.TypeNode = UNKNOWN;\n // tuple type\n if (schemaObject.prefixItems || Array.isArray(schemaObject.items)) {\n const prefixItems = schemaObject.prefixItems ?? (schemaObject.items as (SchemaObject | ReferenceObject)[]);\n itemType = ts.factory.createTupleTypeNode(prefixItems.map((item) => transformSchemaObject(item, options)));\n }\n // standard array type\n else if (schemaObject.items) {\n if (hasKey(schemaObject.items, \"type\") && schemaObject.items.type === \"array\") {\n itemType = ts.factory.createArrayTypeNode(transformSchemaObject(schemaObject.items, options));\n } else {\n itemType = transformSchemaObject(schemaObject.items, options);\n }\n }\n\n const min: number =\n typeof schemaObject.minItems === \"number\" && schemaObject.minItems >= 0 ? schemaObject.minItems : 0;\n const max: number | undefined =\n typeof schemaObject.maxItems === \"number\" && schemaObject.maxItems >= 0 && min <= schemaObject.maxItems\n ? schemaObject.maxItems\n : undefined;\n const estimateCodeSize = typeof max !== \"number\" ? min : (max * (max + 1) - min * (min - 1)) / 2;\n if (\n options.ctx.arrayLength &&\n (min !== 0 || max !== undefined) &&\n estimateCodeSize < 30 // \"30\" is an arbitrary number but roughly around when TS starts to struggle with tuple inference in practice\n ) {\n if (min === max) {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n return tsUnion([ts.factory.createTupleTypeNode(elements)]);\n } else if ((schemaObject.maxItems as number) > 0) {\n // if maxItems is set, then return a union of all permutations of possible tuple types\n const members: ts.TypeNode[] = [];\n // populate 1 short of min …\n for (let i = 0; i <= (max ?? 0) - min; i++) {\n const elements: ts.TypeNode[] = [];\n for (let j = min; j < i + min; j++) {\n elements.push(itemType);\n }\n members.push(ts.factory.createTupleTypeNode(elements));\n }\n return tsUnion(members);\n }\n // if maxItems not set, then return a simple tuple type the length of `min`\n else {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n elements.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(itemType)));\n return ts.factory.createTupleTypeNode(elements);\n }\n }\n\n const finalType =\n ts.isTupleTypeNode(itemType) || ts.isArrayTypeNode(itemType)\n ? itemType\n : ts.factory.createArrayTypeNode(itemType); // wrap itemType in array type, but only if not a tuple or array already\n\n return options.ctx.immutable\n ? ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, finalType)\n : finalType;\n }\n\n // polymorphic, or 3.1 nullable\n if (Array.isArray(schemaObject.type) && !Array.isArray(schemaObject)) {\n // skip any primitive types that appear in oneOf as well\n const uniqueTypes: ts.TypeNode[] = [];\n if (Array.isArray(schemaObject.oneOf)) {\n for (const t of schemaObject.type) {\n if (\n (t === \"boolean\" || t === \"string\" || t === \"number\" || t === \"integer\" || t === \"null\") &&\n schemaObject.oneOf.find((o) => typeof o === \"object\" && \"type\" in o && o.type === t)\n ) {\n continue;\n }\n uniqueTypes.push(\n t === \"null\" || t === null\n ? NULL\n : transformSchemaObject(\n { ...schemaObject, type: t, oneOf: undefined } as SchemaObject, // don’t stack oneOf transforms\n options,\n ),\n );\n }\n } else {\n for (const t of schemaObject.type) {\n if (t === \"null\" || t === null) {\n uniqueTypes.push(NULL);\n } else {\n uniqueTypes.push(transformSchemaObject({ ...schemaObject, type: t } as SchemaObject, options));\n }\n }\n }\n return tsUnion(uniqueTypes);\n }\n }\n\n // type: object\n const coreObjectType: ts.TypeElement[] = [];\n\n // discriminators: explicit mapping on schema object\n for (const k of [\"allOf\", \"anyOf\"] as const) {\n if (!schemaObject[k]) {\n continue;\n }\n // for all magic inheritance, we will have already gathered it into\n // ctx.discriminators. But stop objects from referencing their own\n // discriminator meant for children (!schemaObject.discriminator)\n // and don't add discriminator properties if we already added/patched\n // them (options.ctx.discriminators.refsHandled.includes(options.path!).\n const discriminator =\n !schemaObject.discriminator &&\n !options.ctx.discriminators.refsHandled.includes(options.path ?? \"\") &&\n options.ctx.discriminators.objects[options.path ?? \"\"];\n if (discriminator) {\n coreObjectType.unshift(\n createDiscriminatorProperty(discriminator, {\n path: options.path ?? \"\",\n readonly: options.ctx.immutable,\n }),\n );\n break;\n }\n }\n\n if (\n (\"properties\" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length) ||\n (\"additionalProperties\" in schemaObject && schemaObject.additionalProperties) ||\n (\"patternProperties\" in schemaObject && schemaObject.patternProperties) ||\n (\"$defs\" in schemaObject && schemaObject.$defs)\n ) {\n // properties\n if (Object.keys(schemaObject.properties ?? {}).length) {\n for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) {\n if ((typeof v !== \"object\" && typeof v !== \"boolean\") || Array.isArray(v)) {\n throw new Error(\n `${options.path}: invalid property ${k}. Expected Schema Object or boolean, got ${\n Array.isArray(v) ? \"Array\" : typeof v\n }`,\n );\n }\n\n const { $ref, readOnly, writeOnly, hasDefault } =\n typeof v === \"object\"\n ? {\n $ref: \"$ref\" in v && v.$ref,\n readOnly: \"readOnly\" in v && v.readOnly,\n writeOnly: \"writeOnly\" in v && v.writeOnly,\n hasDefault: \"default\" in v && v.default !== undefined,\n }\n : {};\n\n // handle excludeDeprecated option\n if (options.ctx.excludeDeprecated) {\n const resolved = $ref ? options.ctx.resolve($ref) : v;\n if ((resolved as SchemaObject)?.deprecated) {\n continue;\n }\n }\n let optional =\n schemaObject.required?.includes(k) ||\n (schemaObject.required === undefined && options.ctx.propertiesRequiredByDefault) ||\n (hasDefault &&\n options.ctx.defaultNonNullable &&\n !options.path?.includes(\"parameters\") &&\n !options.path?.includes(\"requestBody\") &&\n !options.path?.includes(\"requestBodies\")) // can’t be required, even with defaults\n ? undefined\n : QUESTION_TOKEN;\n let type = $ref\n ? oapiRef($ref)\n : transformSchemaObject(v, {\n ...options,\n path: createRef([options.path, k]),\n });\n\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(v as SchemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n type = result.schema;\n optional = result.questionToken ? QUESTION_TOKEN : optional;\n } else {\n type = result;\n }\n }\n }\n\n type = wrapWithReadWriteMarker(type, !!readOnly, !!writeOnly, options.ctx);\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && readOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ optional,\n /* type */ type,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n coreObjectType.push(property);\n }\n }\n\n // $defs\n if (schemaObject.$defs && typeof schemaObject.$defs === \"object\" && Object.keys(schemaObject.$defs).length) {\n const defKeys: ts.TypeElement[] = [];\n for (const [k, v] of Object.entries(schemaObject.$defs)) {\n const defReadOnly = \"readOnly\" in v && !!v.readOnly;\n const defWriteOnly = \"writeOnly\" in v && !!v.writeOnly;\n const defType = wrapWithReadWriteMarker(\n transformSchemaObject(v, { ...options, path: createRef([options.path, \"$defs\", k]) }),\n defReadOnly,\n defWriteOnly,\n options.ctx,\n );\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && defReadOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ undefined,\n /* type */ defType,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, \"$defs\", k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n defKeys.push(property);\n }\n coreObjectType.push(\n ts.factory.createPropertySignature(\n /* modifiers */ undefined,\n /* name */ tsPropertyIndex(\"$defs\"),\n /* questionToken */ undefined,\n /* type */ ts.factory.createTypeLiteralNode(defKeys),\n ),\n );\n }\n\n // additionalProperties / patternProperties\n const hasExplicitAdditionalProperties =\n typeof schemaObject.additionalProperties === \"object\" && Object.keys(schemaObject.additionalProperties).length;\n const hasImplicitAdditionalProperties =\n schemaObject.additionalProperties === true ||\n (typeof schemaObject.additionalProperties === \"object\" &&\n Object.keys(schemaObject.additionalProperties).length === 0);\n const hasExplicitPatternProperties =\n typeof schemaObject.patternProperties === \"object\" && Object.keys(schemaObject.patternProperties).length;\n const stringIndexTypes = [];\n if (hasExplicitAdditionalProperties) {\n stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties as SchemaObject, options, true));\n }\n if (hasImplicitAdditionalProperties || (!schemaObject.additionalProperties && options.ctx.additionalProperties)) {\n stringIndexTypes.push(UNKNOWN);\n }\n if (hasExplicitPatternProperties) {\n for (const [_, v] of getEntries(schemaObject.patternProperties ?? {}, options.ctx)) {\n stringIndexTypes.push(transformSchemaObject(v, options));\n }\n }\n\n if (stringIndexTypes.length === 0) {\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n }\n\n const stringIndexType = tsUnion(stringIndexTypes);\n\n return tsIntersection([\n ...(coreObjectType.length ? [ts.factory.createTypeLiteralNode(coreObjectType)] : []),\n ts.factory.createTypeLiteralNode([\n ts.factory.createIndexSignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable,\n }),\n /* parameters */ [\n ts.factory.createParameterDeclaration(\n /* modifiers */ undefined,\n /* dotDotDotToken */ undefined,\n /* name */ ts.factory.createIdentifier(\"key\"),\n /* questionToken */ undefined,\n /* type */ STRING,\n ),\n ],\n /* type */ stringIndexType,\n ),\n ]),\n ]);\n }\n\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n}\n\n/**\n * Check if an object has a key\n * @param possibleObject - The object to check\n * @param key - The key to check for\n * @returns True if the object has the key, false otherwise\n */\nfunction hasKey(possibleObject: unknown, key: K): possibleObject is { [key in K]: unknown } {\n return typeof possibleObject === \"object\" && possibleObject !== null && key in possibleObject;\n}\n\n/** Wrap type with $Read or $Write marker when readWriteMarkers flag is enabled */\nfunction wrapWithReadWriteMarker(\n type: ts.TypeNode,\n readOnly: boolean,\n writeOnly: boolean,\n ctx: { readWriteMarkers: boolean },\n): ts.TypeNode {\n if (!ctx.readWriteMarkers || (readOnly && writeOnly)) {\n return type;\n }\n if (readOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Read\"), [type]);\n }\n if (writeOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Write\"), [type]);\n }\n return type;\n}\n"],"names":["enumType"],"mappings":";;;;;AAiCA,SAAwB,qBAAA,CACtB,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AACb,EAAA,MAAM,IAAA,GAAO,oCAAA,CAAqC,YAAA,EAAc,OAAA,EAAS,wBAAwB,CAAA;AACjG,EAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,aAAA,KAAkB,UAAA,EAAY;AACnD,IAAA,MAAM,mBAAA,GAAsB,OAAA,CAAQ,GAAA,CAAI,aAAA,CAAc,MAAM,OAAO,CAAA;AACnE,IAAA,IAAI,mBAAA,EAAqB;AACvB,MAAA,OAAO,mBAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAKO,SAAS,oCAAA,CACd,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AAMb,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,IAAK,iBAA6B,IAAA,EAAM;AACtC,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAM,OAAA,CAAQ,YAAY,CAAA,IAAK,OAAO,iBAAiB,QAAA,EAAU;AACnE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gCAAA,EAAmC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,GAAI,UAAU,OAAO,YAAY,CAAA,IAAA,EAAO,OAAA,CAAQ,IAAI,CAAA;AAAA,KACnH;AAAA,EACF;AAKA,EAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,IAAA,OAAO,OAAA,CAAQ,aAAa,IAAI,CAAA;AAAA,EAClC;AAKA,EAAA,IAAI,YAAA,CAAa,KAAA,KAAU,IAAA,IAAQ,YAAA,CAAa,UAAU,MAAA,EAAW;AACnE,IAAA,OAAO,SAAA,CAAU,aAAa,KAAK,CAAA;AAAA,EACrC;AAMA,EAAA,IACE,MAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,KAC9B,EAAE,MAAA,IAAU,YAAA,CAAA,IAAiB,YAAA,CAAa,IAAA,KAAS,aACpD,EAAE,YAAA,IAAgB,YAAA,CAAA,IAClB,EAAE,0BAA0B,YAAA,CAAA,EAC5B;AAEA,IAAA,IAAI,uBAAA,CAAwB,OAAA,EAAS,YAAY,CAAA,EAAG;AAClD,MAAA,IAAI,QAAA,GAAW,SAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA,CAAE,OAAA,CAAQ,KAAK,GAAG,CAAA;AAE5D,MAAA,QAAA,GAAW,QAAA,CAAS,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AACpD,MAAA,MAAM,WAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAI,CAAC,GAAG,CAAA,MAAO;AAAA,QAChD,IAAA,EAAM,aAAa,iBAAiB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,aAAa,CAAA,GAAI,CAAC,CAAA;AAAA,QAC7E,WAAA,EAAa,aAAa,qBAAqB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,oBAAoB,CAAA,GAAI,CAAC;AAAA,OACjG,CAAE,CAAA;AAGF,MAAA,IAAI,OAAA,GAAU,KAAA;AACd,MAAA,MAAM,gBAAA,GAAmB,YAAA,CAAa,IAAA,CAAK,MAAA,CAAO,CAAC,SAAA,KAAc;AAC/D,QAAA,IAAI,cAAc,IAAA,EAAM;AACtB,UAAA,OAAA,GAAU,IAAA;AACV,UAAA,OAAO,KAAA;AAAA,QACT;AAEA,QAAA,OAAO,IAAA;AAAA,MACT,CAAC,CAAA;AACD,MAAA,MAAMA,SAAAA,GAAW,MAAA,CAAO,QAAA,EAAU,gBAAA,EAAyC,QAAA,EAAU;AAAA,QACnF,WAAA,EAAa,QAAQ,GAAA,CAAI,WAAA;AAAA,QACzB,MAAA,EAAQ;AAAA;AAAA,OAET,CAAA;AACD,MAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,QAAA,CAASA,SAAQ,CAAA,EAAG;AAChD,QAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAKA,SAAQ,CAAA;AAAA,MACxC;AACA,MAAA,MAAM,GAAA,GAAM,EAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBA,UAAS,IAAI,CAAA;AAC5D,MAAA,OAAO,UAAU,OAAA,CAAQ,CAAC,GAAA,EAAK,IAAI,CAAC,CAAA,GAAI,GAAA;AAAA,IAC1C;AACA,IAAA,MAAM,QAAA,GAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAI,SAAS,CAAA;AAChD,IAAA,IAAK,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,IAAK,YAAA,CAAa,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,IAAM,YAAA,CAAa,QAAA,EAAU;AACrG,MAAA,QAAA,CAAS,KAAK,IAAI,CAAA;AAAA,IACpB;AAEA,IAAA,MAAM,SAAA,GAAY,QAAQ,QAAQ,CAAA;AAGlC,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,YAAA,CAAa,KAAK,KAAA,CAAM,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EAAG;AAC5G,MAAA,MAAM,MAAA,GAAS,QAAA,CAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA;AAC1C,MAAA,IAAI,sBAAA,GAAyB,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA;AAEpD,MAAA,sBAAA,GAAyB,sBAAA,CAAuB,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AAChF,MAAA,sBAAA,GAAyB,GAAG,sBAAsB,CAAA,MAAA,CAAA;AAIlD,MAAA,MAAM,iBAA2B,EAAC;AAQlC,MAAA,MAAM,oBAA8B,EAAC;AACrC,MAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AAE9C,QAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,CAAC,CAAA;AAChC,QAAA,IAAA,CAAK,OAAA,KAAY,WAAW,OAAA,KAAY,OAAA,KAAY,IAAI,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACjF,UAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,CAAA,GAAI,CAAC,CAAA;AACjC,UAAA,IAAI,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,EAAG;AAEtB,YAAA,CAAA,EAAA;AAIA,YAAA,MAAM,iBAAA,GAAoB,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAC,CAAA;AACpD,YAAA,KAAA,MAAW,OAAO,iBAAA,EAAmB;AAEnC,cAAA,IAAI,GAAA,KAAQ,WAAW,GAAA,KAAQ,OAAA,IAAW,CAAC,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,EAAG;AAC5D,gBAAA,iBAAA,CAAkB,KAAK,GAAG,CAAA;AAAA,cAC5B;AAAA,YACF;AACA,YAAA;AAAA,UACF;AAAA,QACF;AACA,QAAA,cAAA,CAAe,KAAK,OAAO,CAAA;AAAA,MAC7B;AACA,MAAA,MAAM,cAAA,GAAiB,UAAU,cAAc,CAAA;AAE/C,MAAA,MAAM,eAAA,GAAkB,wBAAA;AAAA,QACtB,sBAAA;AAAA;AAAA,QAEA,wBAAA,GACI,GAAG,OAAA,CAAQ,2BAAA;AAAA,UACT,QAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,UACpE,GAAG,OAAA,CAAQ,uBAAA,CAAwB,GAAG,OAAA,CAAQ,gBAAA,CAAiB,QAAQ,CAAC;AAAA,SAC1E,GACA,QAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,QACxE,YAAA,CAAa,IAAA;AAAA,QACb;AAAA,UACE,MAAA,EAAQ,IAAA;AAAA,UACR,QAAA,EAAU,IAAA;AAAA,UACV,YAAA,EAAc,QAAQ,GAAA,CAAI;AAAA;AAC5B,OACF;AAEA,MAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAK,eAAe,CAAA;AAAA,IAC/C;AAEA,IAAA,OAAO,SAAA;AAAA,EACT;AAOA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAA6B;AACxG,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,CAAC,KAAA,EAAO,IAAI,CAAA,IAAK,KAAA,CAAM,SAAQ,EAAG;AAC3C,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,sBAAsB,IAAA,EAAM;AAAA,UAC1B,GAAG,OAAA;AAAA;AAAA,UAEH,IAAA,EAAM,UAAU,CAAC,OAAA,CAAQ,MAAM,QAAA,EAAU,MAAA,CAAO,KAAK,CAAC,CAAC;AAAA,SACxD;AAAA,OACH;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAAoC;AAC/G,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,MAAA,IAAI,QAAA;AAGJ,MAAA,IAAI,UAAU,IAAA,EAAM;AAClB,QAAA,QAAA,GAAW,qBAAA,CAAsB,MAAM,OAAO,CAAA;AAE9C,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,KAAK,IAAI,CAAA;AAG5D,QAAA,IACE,QAAA,IACA,OAAO,QAAA,KAAa,QAAA,IACpB,YAAA,IAAgB,QAAA;AAAA,QAEhB,CAAC,QAAQ,GAAA,CAAI,cAAA,CAAe,YAAY,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAC1D;AAEA,UAAA,MAAM,aAAA,GAAA,CAAiB,QAAA,IAAY,EAAC,EAAG,MAAA,CAAO,CAAC,GAAA,KAAQ,CAAC,CAAC,QAAA,CAAS,UAAA,GAAa,GAAG,CAAC,CAAA;AACnF,UAAA,IAAI,cAAc,MAAA,EAAQ;AACxB,YAAA,QAAA,GAAW,cAAA,CAAe,QAAA,EAAU,aAAA,EAAe,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,UAC7E;AAAA,QACF;AAAA,MACF,CAAA,MAEK;AACH,QAAA,MAAM,YAAA,GAAe,CAAC,GAAI,QAAA,IAAY,EAAG,CAAA;AACzC,QAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,QAAQ,CAAA,EAAG;AAC5D,UAAA,YAAA,CAAa,IAAA,CAAK,GAAG,IAAA,CAAK,QAAQ,CAAA;AAAA,QACpC;AACA,QAAA,QAAA,GAAW,sBAAsB,EAAE,GAAG,MAAM,QAAA,EAAU,YAAA,IAAgB,OAAO,CAAA;AAAA,MAC/E;AAEA,MAAA,MAAM,aAAA,GACH,MAAA,IAAU,IAAA,IAAQ,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,IAAO,IAAA,CAAa,aAAA;AACrF,MAAA,IAAI,aAAA,EAAe;AACjB,QAAA,MAAA,CAAO,KAAK,MAAA,CAAO,QAAA,EAAU,CAAC,aAAA,CAAc,YAAY,CAAC,CAAC,CAAA;AAAA,MAC5D,CAAA,MAAO;AACL,QAAA,MAAA,CAAO,KAAK,QAAQ,CAAA;AAAA,MACtB;AAAA,IACF;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,IAAI,SAAA;AAGJ,EAAA,MAAM,cAAA,GAAiB,yBAAA,CAA0B,YAAA,EAAc,OAAO,CAAA;AACtE,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,SAAS,EAAC,EAAG,aAAa,QAAQ,CAAA;AAC1F,EAAA,IAAI,cAAA,IAAkB,UAAU,MAAA,EAAQ;AACtC,IAAA,MAAM,KAAA,GAAiC,SAAA,CAAU,MAAA,GAAS,cAAA,CAAe,SAAS,CAAA,GAAI,MAAA;AACtF,IAAA,SAAA,GAAY,eAAe,CAAC,GAAI,cAAA,GAAiB,CAAC,cAAc,CAAA,GAAI,EAAC,EAAI,GAAI,QAAQ,CAAC,KAAK,CAAA,GAAI,EAAG,CAAC,CAAA;AAAA,EACrG;AAGA,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,KAAA,IAAS,IAAI,OAAO,CAAA;AAC5E,EAAA,IAAI,UAAU,MAAA,EAAQ;AACpB,IAAA,SAAA,GAAY,OAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,EACvE;AAEA,EAAA,MAAM,SAAA,GAAY,wBAAA;AAAA,IAChB,YAAA,CAAa,SACV,MAAA,IAAU,YAAA,IACT,aAAa,IAAA,KAAS,QAAA,IACrB,YAAA,CAAa,IAAA,IAChB,EAAC;AAAA,IACH;AAAA,GACF;AACA,EAAA,IAAI,UAAU,MAAA,EAAQ;AAEpB,IAAA,IAAI,SAAA,CAAU,KAAA,CAAM,aAAa,CAAA,EAAG;AAClC,MAAA,SAAA,GAAY,OAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,IACvE,CAAA,MAAO;AACL,MAAA,SAAA,GAAY,cAAA,CAAe,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,OAAA,CAAQ,SAAS,CAAC,CAAC,CAAA;AAAA,IACpF;AAAA,EACF;AAGA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,MAAA,SAAA,GAAY,SAAS,MAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,mBAAA,GAAsB,UAAU,KAAK,CAAA;AAAA,IAChF,CAAA,MAAO;AACL,MAAA,SAAA,GAAY,OAAA;AAAA,IACd;AAAA,EACF;AAEA,EAAA,IAAI,SAAA,KAAc,OAAA,IAAW,YAAA,CAAa,QAAA,EAAU;AAClD,IAAA,SAAA,GAAY,UAAA,CAAW,CAAC,SAAS,CAAC,CAAA;AAAA,EACpC;AAEA,EAAA,OAAO,SAAA;AACT;AAKA,SAAS,uBAAA,CAAwB,SAA+B,YAAA,EAAqC;AAEnG,EAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,IAAA,IAAQ,CAAC,aAAa,IAAA,EAAM;AAC3C,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,KAAM,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,CAAA,CAAE,QAAA,CAAS,OAAO,CAAC,CAAC,CAAA,EAAG;AAClF,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,OAAA,CAAQ,IAAI,gBAAA,EAAkB;AAChC,IAAA,MAAM,eAAA,GACJ,MAAM,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAC,CAAA,IAC7C,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,aAAa,CAAC,CAAA,IACzC,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAC,KACjD,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,oBAAoB,CAAC,CAAA;AAClD,IAAA,IAAI,CAAC,eAAA,EAAiB;AACpB,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT;AAKA,SAAS,yBAAA,CAA0B,cAA4B,OAAA,EAAwD;AACrH,EAAA,IAAI,MAAA,IAAU,YAAA,IAAgB,YAAA,CAAa,IAAA,EAAM;AAC/C,IAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,cAAc,OAAO,CAAA;AAC1D,MAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,QAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,UAAA,IAAI,OAAO,aAAA,EAAe;AACxB,YAAA,OAAO,GAAG,OAAA,CAAQ,mBAAA,CAAoB,CAAC,MAAA,CAAO,MAAA,EAAQ,SAAS,CAAC,CAAA;AAAA,UAClE,CAAA,MAAO;AACL,YAAA,OAAO,MAAA,CAAO,MAAA;AAAA,UAChB;AAAA,QACF,CAAA,MAAO;AACL,UAAA,OAAO,MAAA;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAIA,IAAA,IAAI,YAAA,CAAa,SAAS,MAAA,EAAQ;AAChC,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,QAAA,EAAU;AAClC,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,IAAA,KAAS,QAAA,IAAY,YAAA,CAAa,SAAS,SAAA,EAAW;AACrE,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,SAAA,EAAW;AACnC,MAAA,OAAO,OAAA;AAAA,IACT;AAGA,IAAA,IAAI,YAAA,CAAa,SAAS,OAAA,EAAS;AAEjC,MAAA,IAAI,QAAA,GAAwB,OAAA;AAE5B,MAAA,IAAI,aAAa,WAAA,IAAe,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACjE,QAAA,MAAM,WAAA,GAAc,YAAA,CAAa,WAAA,IAAgB,YAAA,CAAa,KAAA;AAC9D,QAAA,QAAA,GAAW,EAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,WAAA,CAAY,GAAA,CAAI,CAAC,IAAA,KAAS,qBAAA,CAAsB,IAAA,EAAM,OAAO,CAAC,CAAC,CAAA;AAAA,MAC3G,CAAA,MAAA,IAES,aAAa,KAAA,EAAO;AAC3B,QAAA,IAAI,MAAA,CAAO,aAAa,KAAA,EAAO,MAAM,KAAK,YAAA,CAAa,KAAA,CAAM,SAAS,OAAA,EAAS;AAC7E,UAAA,QAAA,GAAW,GAAG,OAAA,CAAQ,mBAAA,CAAoB,sBAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,QAC9F,CAAA,MAAO;AACL,UAAA,QAAA,GAAW,qBAAA,CAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAA;AAAA,QAC9D;AAAA,MACF;AAEA,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,YAAY,YAAA,CAAa,QAAA,IAAY,CAAA,GAAI,YAAA,CAAa,QAAA,GAAW,CAAA;AACpG,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,QAAA,IAAY,YAAA,CAAa,QAAA,IAAY,CAAA,IAAK,GAAA,IAAO,YAAA,CAAa,QAAA,GAC3F,YAAA,CAAa,QAAA,GACb,MAAA;AACN,MAAA,MAAM,gBAAA,GAAmB,OAAO,GAAA,KAAQ,QAAA,GAAW,GAAA,GAAA,CAAO,OAAO,GAAA,GAAM,CAAA,CAAA,GAAK,GAAA,IAAO,GAAA,GAAM,CAAA,CAAA,IAAM,CAAA;AAC/F,MAAA,IACE,OAAA,CAAQ,IAAI,WAAA,KACX,GAAA,KAAQ,KAAK,GAAA,KAAQ,MAAA,CAAA,IACtB,mBAAmB,EAAA,EACnB;AACA,QAAA,IAAI,QAAQ,GAAA,EAAK;AACf,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,OAAO,QAAQ,CAAC,EAAA,CAAG,QAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AAAA,QAC3D,CAAA,MAAA,IAAY,YAAA,CAAa,QAAA,GAAsB,CAAA,EAAG;AAEhD,UAAA,MAAM,UAAyB,EAAC;AAEhC,UAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,IAAA,CAAM,GAAA,IAAO,CAAA,IAAK,KAAK,CAAA,EAAA,EAAK;AAC1C,YAAA,MAAM,WAA0B,EAAC;AACjC,YAAA,KAAA,IAAS,CAAA,GAAI,GAAA,EAAK,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,EAAA,EAAK;AAClC,cAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,YACxB;AACA,YAAA,OAAA,CAAQ,IAAA,CAAK,EAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAA;AAAA,UACvD;AACA,UAAA,OAAO,QAAQ,OAAO,CAAA;AAAA,QACxB,CAAA,MAEK;AACH,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,QAAA,CAAS,IAAA,CAAK,GAAG,OAAA,CAAQ,kBAAA,CAAmB,GAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AACrF,UAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAA;AAAA,QAChD;AAAA,MACF;AAEA,MAAA,MAAM,SAAA,GACJ,EAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,IAAK,EAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,GACvD,QAAA,GACA,EAAA,CAAG,OAAA,CAAQ,oBAAoB,QAAQ,CAAA;AAE7C,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,GACf,EAAA,CAAG,OAAA,CAAQ,uBAAuB,EAAA,CAAG,UAAA,CAAW,eAAA,EAAiB,SAAS,CAAA,GAC1E,SAAA;AAAA,IACN;AAGA,IAAA,IAAI,KAAA,CAAM,QAAQ,YAAA,CAAa,IAAI,KAAK,CAAC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,EAAG;AAEpE,MAAA,MAAM,cAA6B,EAAC;AACpC,MAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACrC,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAA,CACG,CAAA,KAAM,aAAa,CAAA,KAAM,QAAA,IAAY,MAAM,QAAA,IAAY,CAAA,KAAM,SAAA,IAAa,CAAA,KAAM,MAAA,KACjF,YAAA,CAAa,MAAM,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,UAAU,CAAA,IAAK,CAAA,CAAE,IAAA,KAAS,CAAC,CAAA,EACnF;AACA,YAAA;AAAA,UACF;AACA,UAAA,WAAA,CAAY,IAAA;AAAA,YACV,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,GAClB,IAAA,GACA,qBAAA;AAAA,cACE,EAAE,GAAG,YAAA,EAAc,IAAA,EAAM,CAAA,EAAG,OAAO,MAAA,EAAU;AAAA;AAAA,cAC7C;AAAA;AACF,WACN;AAAA,QACF;AAAA,MACF,CAAA,MAAO;AACL,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAI,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,EAAM;AAC9B,YAAA,WAAA,CAAY,KAAK,IAAI,CAAA;AAAA,UACvB,CAAA,MAAO;AACL,YAAA,WAAA,CAAY,IAAA,CAAK,sBAAsB,EAAE,GAAG,cAAc,IAAA,EAAM,CAAA,EAAE,EAAmB,OAAO,CAAC,CAAA;AAAA,UAC/F;AAAA,QACF;AAAA,MACF;AACA,MAAA,OAAO,QAAQ,WAAW,CAAA;AAAA,IAC5B;AAAA,EACF;AAGA,EAAA,MAAM,iBAAmC,EAAC;AAG1C,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,OAAA,EAAS,OAAO,CAAA,EAAY;AAC3C,IAAA,IAAI,CAAC,YAAA,CAAa,CAAC,CAAA,EAAG;AACpB,MAAA;AAAA,IACF;AAMA,IAAA,MAAM,aAAA,GACJ,CAAC,YAAA,CAAa,aAAA,IACd,CAAC,OAAA,CAAQ,GAAA,CAAI,eAAe,WAAA,CAAY,QAAA,CAAS,QAAQ,IAAA,IAAQ,EAAE,KACnE,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACvD,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,cAAA,CAAe,OAAA;AAAA,QACb,4BAA4B,aAAA,EAAe;AAAA,UACzC,IAAA,EAAM,QAAQ,IAAA,IAAQ,EAAA;AAAA,UACtB,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,SACvB;AAAA,OACH;AACA,MAAA;AAAA,IACF;AAAA,EACF;AAEA,EAAA,IACG,YAAA,IAAgB,gBAAgB,YAAA,CAAa,UAAA,IAAc,OAAO,IAAA,CAAK,YAAA,CAAa,UAAU,CAAA,CAAE,MAAA,IAChG,0BAA0B,YAAA,IAAgB,YAAA,CAAa,wBACvD,mBAAA,IAAuB,YAAA,IAAgB,aAAa,iBAAA,IACpD,OAAA,IAAW,YAAA,IAAgB,YAAA,CAAa,KAAA,EACzC;AAEA,IAAA,IAAI,OAAO,IAAA,CAAK,YAAA,CAAa,cAAc,EAAE,EAAE,MAAA,EAAQ;AACrD,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,UAAA,CAAW,YAAA,CAAa,UAAA,IAAc,EAAC,EAAG,OAAA,CAAQ,GAAG,CAAA,EAAG;AAC3E,QAAA,IAAK,OAAO,MAAM,QAAA,IAAY,OAAO,MAAM,SAAA,IAAc,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,EAAG;AACzE,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,EAAG,OAAA,CAAQ,IAAI,CAAA,mBAAA,EAAsB,CAAC,CAAA,yCAAA,EACpC,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAAI,OAAA,GAAU,OAAO,CACtC,CAAA;AAAA,WACF;AAAA,QACF;AAEA,QAAA,MAAM,EAAE,MAAM,QAAA,EAAU,SAAA,EAAW,YAAW,GAC5C,OAAO,MAAM,QAAA,GACT;AAAA,UACE,IAAA,EAAM,MAAA,IAAU,CAAA,IAAK,CAAA,CAAE,IAAA;AAAA,UACvB,QAAA,EAAU,UAAA,IAAc,CAAA,IAAK,CAAA,CAAE,QAAA;AAAA,UAC/B,SAAA,EAAW,WAAA,IAAe,CAAA,IAAK,CAAA,CAAE,SAAA;AAAA,UACjC,UAAA,EAAY,SAAA,IAAa,CAAA,IAAK,CAAA,CAAE,OAAA,KAAY;AAAA,YAE9C,EAAC;AAGP,QAAA,IAAI,OAAA,CAAQ,IAAI,iBAAA,EAAmB;AACjC,UAAA,MAAM,WAAW,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,IAAI,CAAA,GAAI,CAAA;AAClE,UAAA,IAAK,UAA2B,UAAA,EAAY;AAC1C,YAAA;AAAA,UACF;AAAA,QACF;AACA,QAAA,IAAI,QAAA,GACF,YAAA,CAAa,QAAA,EAAU,QAAA,CAAS,CAAC,CAAA,IAChC,YAAA,CAAa,QAAA,KAAa,MAAA,IAAa,QAAQ,GAAA,CAAI,2BAAA,IACnD,UAAA,IACC,OAAA,CAAQ,IAAI,kBAAA,IACZ,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,YAAY,CAAA,IACpC,CAAC,QAAQ,IAAA,EAAM,QAAA,CAAS,aAAa,CAAA,IACrC,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,eAAe,IACrC,MAAA,GACA,cAAA;AACN,QAAA,IAAI,OAAO,IAAA,GACP,OAAA,CAAQ,IAAI,CAAA,GACZ,sBAAsB,CAAA,EAAG;AAAA,UACvB,GAAG,OAAA;AAAA,UACH,MAAM,SAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,SAClC,CAAA;AAEL,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,GAAmB,OAAO,CAAA;AAC/D,UAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,YAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,cAAA,IAAA,GAAO,MAAA,CAAO,MAAA;AACd,cAAA,QAAA,GAAW,MAAA,CAAO,gBAAgB,cAAA,GAAiB,QAAA;AAAA,YACrD,CAAA,MAAO;AACL,cAAA,IAAA,GAAO,MAAA;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAEA,QAAA,IAAA,GAAO,uBAAA,CAAwB,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC,SAAA,EAAW,OAAA,CAAQ,GAAG,CAAA;AAEzE,QAAA,IAAI,QAAA,GAAW,GAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACJ,WAAA,CAAY;AAAA,YAC9B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmB,gBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,QAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAM,SAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,WAClC,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAA,eAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,cAAA,CAAe,KAAK,QAAQ,CAAA;AAAA,MAC9B;AAAA,IACF;AAGA,IAAA,IAAI,YAAA,CAAa,KAAA,IAAS,OAAO,YAAA,CAAa,KAAA,KAAU,QAAA,IAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,KAAK,CAAA,CAAE,MAAA,EAAQ;AAC1G,MAAA,MAAM,UAA4B,EAAC;AACnC,MAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACvD,QAAA,MAAM,WAAA,GAAc,UAAA,IAAc,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,QAAA;AAC3C,QAAA,MAAM,YAAA,GAAe,WAAA,IAAe,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,SAAA;AAC7C,QAAA,MAAM,OAAA,GAAU,uBAAA;AAAA,UACd,qBAAA,CAAsB,CAAA,EAAG,EAAE,GAAG,SAAS,IAAA,EAAM,SAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC,GAAG,CAAA;AAAA,UACpF,WAAA;AAAA,UACA,YAAA;AAAA,UACA,OAAA,CAAQ;AAAA,SACV;AAEA,QAAA,IAAI,QAAA,GAAW,GAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACL,WAAA,CAAY;AAAA,YAC7B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmB,gBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,MAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAM,SAAA,CAAU,CAAC,QAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC;AAAA,WAC3C,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAA,eAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,OAAA,CAAQ,KAAK,QAAQ,CAAA;AAAA,MACvB;AACA,MAAA,cAAA,CAAe,IAAA;AAAA,QACb,GAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACW,MAAA;AAAA;AAAA,UACA,gBAAgB,OAAO,CAAA;AAAA;AAAA,UACvB,MAAA;AAAA;AAAA,UACA,EAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,OAAO;AAAA;AAC9D,OACF;AAAA,IACF;AAGA,IAAA,MAAM,+BAAA,GACJ,OAAO,YAAA,CAAa,oBAAA,KAAyB,YAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,CAAA,CAAE,MAAA;AAC1G,IAAA,MAAM,+BAAA,GACJ,YAAA,CAAa,oBAAA,KAAyB,IAAA,IACrC,OAAO,YAAA,CAAa,oBAAA,KAAyB,QAAA,IAC5C,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,EAAE,MAAA,KAAW,CAAA;AAC9D,IAAA,MAAM,4BAAA,GACJ,OAAO,YAAA,CAAa,iBAAA,KAAsB,YAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,iBAAiB,CAAA,CAAE,MAAA;AACpG,IAAA,MAAM,mBAAmB,EAAC;AAC1B,IAAA,IAAI,+BAAA,EAAiC;AACnC,MAAA,gBAAA,CAAiB,KAAK,qBAAA,CAAsB,YAAA,CAAa,oBAAA,EAAsC,OAAA,EAAS,IAAI,CAAC,CAAA;AAAA,IAC/G;AACA,IAAA,IAAI,mCAAoC,CAAC,YAAA,CAAa,oBAAA,IAAwB,OAAA,CAAQ,IAAI,oBAAA,EAAuB;AAC/G,MAAA,gBAAA,CAAiB,KAAK,OAAO,CAAA;AAAA,IAC/B;AACA,IAAA,IAAI,4BAAA,EAA8B;AAChC,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,UAAA,CAAW,YAAA,CAAa,iBAAA,IAAqB,EAAC,EAAG,OAAA,CAAQ,GAAG,CAAA,EAAG;AAClF,QAAA,gBAAA,CAAiB,IAAA,CAAK,qBAAA,CAAsB,CAAA,EAAG,OAAO,CAAC,CAAA;AAAA,MACzD;AAAA,IACF;AAEA,IAAA,IAAI,gBAAA,CAAiB,WAAW,CAAA,EAAG;AACjC,MAAA,OAAO,eAAe,MAAA,GAAS,EAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AAAA,IACpF;AAEA,IAAA,MAAM,eAAA,GAAkB,QAAQ,gBAAgB,CAAA;AAEhD,IAAA,OAAO,cAAA,CAAe;AAAA,MACpB,GAAI,cAAA,CAAe,MAAA,GAAS,CAAC,EAAA,CAAG,QAAQ,qBAAA,CAAsB,cAAc,CAAC,CAAA,GAAI,EAAC;AAAA,MAClF,EAAA,CAAG,QAAQ,qBAAA,CAAsB;AAAA,QAC/B,GAAG,OAAA,CAAQ,oBAAA;AAAA;AAAA,UACQ,WAAA,CAAY;AAAA,YAC3B,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,WACvB,CAAA;AAAA;AAAA,UACgB;AAAA,YACf,GAAG,OAAA,CAAQ,0BAAA;AAAA;AAAA,cACY,MAAA;AAAA;AAAA,cACA,MAAA;AAAA;AAAA,cACA,EAAA,CAAG,OAAA,CAAQ,gBAAA,CAAiB,KAAK,CAAA;AAAA;AAAA,cACjC,MAAA;AAAA;AAAA,cACA;AAAA;AACvB,WACF;AAAA;AAAA,UACiB;AAAA;AACnB,OACD;AAAA,KACF,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,eAAe,MAAA,GAAS,EAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AACpF;AAQA,SAAS,MAAA,CAAyB,gBAAyB,GAAA,EAAmD;AAC5G,EAAA,OAAO,OAAO,cAAA,KAAmB,QAAA,IAAY,cAAA,KAAmB,QAAQ,GAAA,IAAO,cAAA;AACjF;AAGA,SAAS,uBAAA,CACP,IAAA,EACA,QAAA,EACA,SAAA,EACA,GAAA,EACa;AACb,EAAA,IAAI,CAAC,GAAA,CAAI,gBAAA,IAAqB,QAAA,IAAY,SAAA,EAAY;AACpD,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwB,EAAA,CAAG,OAAA,CAAQ,iBAAiB,OAAO,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwB,EAAA,CAAG,OAAA,CAAQ,iBAAiB,QAAQ,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACzF;AACA,EAAA,OAAO,IAAA;AACT;;;;"} +\ No newline at end of file ++{"version":3,"file":"schema-object.mjs","sources":["../../src/transform/schema-object.ts"],"sourcesContent":["import { parseRef } from \"@redocly/openapi-core/lib/ref-utils.js\";\nimport ts from \"typescript\";\nimport {\n addJSDocComment,\n BOOLEAN,\n NEVER,\n NULL,\n NUMBER,\n oapiRef,\n QUESTION_TOKEN,\n STRING,\n tsArrayLiteralExpression,\n tsEnum,\n tsIntersection,\n tsIsPrimitive,\n tsLiteral,\n tsModifiers,\n tsNullable,\n tsPropertyIndex,\n tsRecord,\n tsUnion,\n tsWithRequired,\n UNDEFINED,\n UNKNOWN,\n} from \"../lib/ts.js\";\nimport { createDiscriminatorProperty, createRef, getEntries } from \"../lib/utils.js\";\nimport type { ReferenceObject, SchemaObject, TransformNodeOptions } from \"../types.js\";\n\n/**\n * Transform SchemaObject nodes (4.8.24)\n * @see https://spec.openapis.org/oas/v3.1.0#schema-object\n */\nexport default function transformSchemaObject(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n const type = transformSchemaObjectWithComposition(schemaObject, options, fromAdditionalProperties);\n if (typeof options.ctx.postTransform === \"function\") {\n const postTransformResult = options.ctx.postTransform(type, options);\n if (postTransformResult) {\n return postTransformResult;\n }\n }\n return type;\n}\n\n/**\n * Transform SchemaObjects\n */\nexport function transformSchemaObjectWithComposition(\n schemaObject: SchemaObject | ReferenceObject,\n options: TransformNodeOptions,\n fromAdditionalProperties = false,\n): ts.TypeNode {\n /**\n * Unexpected types & edge cases\n */\n\n // missing/falsy type returns `never`\n if (!schemaObject) {\n return NEVER;\n }\n // `true` returns `unknown` (this exists, but is untyped)\n if ((schemaObject as unknown) === true) {\n return UNKNOWN;\n }\n // for any other unexpected type, throw error\n if (Array.isArray(schemaObject) || typeof schemaObject !== \"object\") {\n throw new Error(\n `Expected SchemaObject, received ${Array.isArray(schemaObject) ? \"Array\" : typeof schemaObject} at ${options.path}`,\n );\n }\n\n /**\n * ReferenceObject\n */\n if (\"$ref\" in schemaObject) {\n return oapiRef(schemaObject.$ref);\n }\n\n /**\n * const (valid for any type)\n */\n if (schemaObject.const !== null && schemaObject.const !== undefined) {\n return tsLiteral(schemaObject.const);\n }\n\n /**\n * enum (non-objects)\n * note: enum is valid for any type, but for objects, handle in oneOf below\n */\n if (\n Array.isArray(schemaObject.enum) &&\n (!(\"type\" in schemaObject) || schemaObject.type !== \"object\") &&\n !(\"properties\" in schemaObject)\n ) {\n const hasAdditionalProperties = \"additionalProperties\" in schemaObject && !!schemaObject.additionalProperties;\n\n if (!hasAdditionalProperties || (schemaObject.type === \"string\" && hasAdditionalProperties)) {\n // hoist enum to top level if string/number enum and option is enabled\n if (shouldTransformToTsEnum(options, schemaObject)) {\n let enumName = parseRef(options.path ?? \"\").pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumName = enumName.replace(\"components/schemas\", \"\");\n const metadata = schemaObject.enum.map((_, i) => ({\n name: schemaObject[\"x-enum-varnames\"]?.[i] ?? schemaObject[\"x-enumNames\"]?.[i],\n description: schemaObject[\"x-enum-descriptions\"]?.[i] ?? schemaObject[\"x-enumDescriptions\"]?.[i],\n }));\n\n // enums can contain null values, but dont want to output them\n let hasNull = false;\n const validSchemaEnums = schemaObject.enum.filter((enumValue) => {\n if (enumValue === null) {\n hasNull = true;\n return false;\n }\n\n return true;\n });\n const enumType = tsEnum(enumName, validSchemaEnums as (string | number)[], metadata, {\n shouldCache: options.ctx.dedupeEnums,\n export: true,\n // readonly: TS enum do not support the readonly modifier\n });\n if (!options.ctx.injectFooter.includes(enumType)) {\n options.ctx.injectFooter.push(enumType);\n }\n const ref = ts.factory.createTypeReferenceNode(enumType.name);\n\n const finalType: ts.TypeNode = hasNull ? tsUnion([ref, NULL]) : ref;\n\n return applyAdditionalPropertiesToEnum(hasAdditionalProperties, finalType, schemaObject);\n }\n\n const enumType = schemaObject.enum.map(tsLiteral);\n if ((Array.isArray(schemaObject.type) && schemaObject.type.includes(\"null\")) || schemaObject.nullable) {\n enumType.push(NULL);\n }\n\n const unionType = applyAdditionalPropertiesToEnum(hasAdditionalProperties, tsUnion(enumType), schemaObject);\n\n // hoist array with valid enum values to top level if string/number enum and option is enabled\n if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === \"string\" || typeof v === \"number\")) {\n const parsed = parseRef(options.path ?? \"\");\n let enumValuesVariableName = parsed.pointer.join(\"/\");\n // allow #/components/schemas to have simpler names\n enumValuesVariableName = enumValuesVariableName.replace(\"components/schemas\", \"\");\n enumValuesVariableName = `${enumValuesVariableName}Values`;\n\n // build a ref path for the type that ignores union indices (anyOf/oneOf) so\n // type references remain stable even when names include union positions\n const cleanedPointer: string[] = [];\n // Track ALL properties after a oneOf/anyOf that need Extract<> narrowing.\n // We apply Extract<> before EVERY property access after a union index because:\n // - When the property exists on ALL variants, Extract<> is a no-op (returns same type)\n // - When the property only exists on SOME variants, it correctly narrows the union\n // - When both variants have same property name but different inner schemas,\n // we still narrow at each level to handle nested unions correctly\n // This robust approach handles both simple and complex union structures.\n const extractProperties: string[] = [];\n for (let i = 0; i < parsed.pointer.length; i++) {\n // Example: #/paths/analytics/data/get/responses/400/content/application/json/anyOf/0/message\n const segment = parsed.pointer[i];\n if ((segment === \"anyOf\" || segment === \"oneOf\") && i < parsed.pointer.length - 1) {\n const next = parsed.pointer[i + 1];\n if (/^\\d+$/.test(next)) {\n // If we encounter something like \"anyOf/0\", we want to skip that part of the path\n i++;\n // Collect ALL remaining segments after the union index.\n // Each one will be wrapped with Extract<> to safely narrow the type\n // at each level, handling both top-level and nested union variants.\n const remainingSegments = parsed.pointer.slice(i + 1);\n for (const seg of remainingSegments) {\n // Skip union keywords and indices, only add actual property names\n if (seg !== \"anyOf\" && seg !== \"oneOf\" && !/^\\d+$/.test(seg)) {\n extractProperties.push(seg);\n }\n }\n continue;\n }\n }\n cleanedPointer.push(segment);\n }\n const cleanedRefPath = createRef(cleanedPointer);\n\n const enumValuesArray = tsArrayLiteralExpression(\n enumValuesVariableName,\n // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type\n fromAdditionalProperties\n ? ts.factory.createIndexedAccessTypeNode(\n oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"string\")),\n )\n : oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }),\n schemaObject.enum as (string | number)[],\n {\n export: true,\n readonly: true,\n injectFooter: options.ctx.injectFooter,\n },\n );\n\n options.ctx.injectFooter.push(enumValuesArray);\n }\n\n return unionType;\n }\n }\n\n /**\n * Object + composition (anyOf/allOf/oneOf) types\n */\n\n /** Collect oneOf/anyOf */\n function collectUnionCompositions(items: (SchemaObject | ReferenceObject)[], unionKey: \"anyOf\" | \"oneOf\") {\n const output: ts.TypeNode[] = [];\n for (const [index, item] of items.entries()) {\n output.push(\n transformSchemaObject(item, {\n ...options,\n // include index in path so generated names from nested enums/enumValues are unique\n path: createRef([options.path, unionKey, String(index)]),\n }),\n );\n }\n\n return output;\n }\n\n /** Collect allOf with Omit<> for discriminators */\n function collectAllOfCompositions(items: (SchemaObject | ReferenceObject)[], required?: string[]): ts.TypeNode[] {\n const output: ts.TypeNode[] = [];\n for (const item of items) {\n let itemType: ts.TypeNode;\n // if this is a $ref, use WithRequired if parent specifies required properties\n // (but only for valid keys)\n if (\"$ref\" in item) {\n itemType = transformSchemaObject(item, options);\n\n const resolved = options.ctx.resolve(item.$ref);\n\n // make keys required, if necessary\n if (\n resolved &&\n typeof resolved === \"object\" &&\n \"properties\" in resolved &&\n // we have already handled this item (discriminator property was already added as required)\n !options.ctx.discriminators.refsHandled.includes(item.$ref)\n ) {\n // add WithRequired if necessary\n const validRequired = (required ?? []).filter((key) => !!resolved.properties?.[key]);\n if (validRequired.length) {\n itemType = tsWithRequired(itemType, validRequired, options.ctx.injectFooter);\n }\n }\n }\n // otherwise, if this is a schema object, combine parent `required[]` with its own, if any\n else {\n const itemRequired = [...(required ?? [])];\n if (typeof item === \"object\" && Array.isArray(item.required)) {\n itemRequired.push(...item.required);\n }\n itemType = transformSchemaObject({ ...item, required: itemRequired }, options);\n }\n\n output.push(itemType);\n }\n return output;\n }\n\n // compile final type\n let finalType: ts.TypeNode | undefined;\n\n // core + allOf: intersect\n const coreObjectType = transformSchemaObjectCore(schemaObject, options);\n const allOfType = collectAllOfCompositions(schemaObject.allOf ?? [], schemaObject.required);\n if (coreObjectType || allOfType.length) {\n const allOf: ts.TypeNode | undefined = allOfType.length ? tsIntersection(allOfType) : undefined;\n finalType = tsIntersection([...(coreObjectType ? [coreObjectType] : []), ...(allOf ? [allOf] : [])]);\n }\n // anyOf: union\n // (note: this may seem counterintuitive, but as TypeScript’s unions are not true XORs, they mimic behavior closer to anyOf than oneOf)\n const anyOfType = collectUnionCompositions(schemaObject.anyOf ?? [], \"anyOf\");\n if (anyOfType.length) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...anyOfType]);\n }\n // oneOf: union (within intersection with other types, if any)\n const oneOfType = collectUnionCompositions(\n schemaObject.oneOf ||\n (\"type\" in schemaObject &&\n schemaObject.type === \"object\" &&\n (schemaObject.enum as (SchemaObject | ReferenceObject)[])) ||\n [],\n \"oneOf\",\n );\n if (oneOfType.length) {\n // note: oneOf is the only type that may include primitives\n if (oneOfType.every(tsIsPrimitive)) {\n finalType = tsUnion([...(finalType ? [finalType] : []), ...oneOfType]);\n } else {\n finalType = tsIntersection([...(finalType ? [finalType] : []), tsUnion(oneOfType)]);\n }\n }\n\n // When no final type can be generated, fall back to unknown type (or related variants)\n if (!finalType) {\n if (\"type\" in schemaObject) {\n finalType = tsRecord(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER);\n } else {\n finalType = UNKNOWN;\n }\n }\n\n if (finalType !== UNKNOWN && schemaObject.nullable) {\n finalType = tsNullable([finalType]);\n }\n\n return finalType;\n}\n\n/**\n * Check if the given OAPI enum should be transformed to a TypeScript enum\n */\nfunction shouldTransformToTsEnum(options: TransformNodeOptions, schemaObject: SchemaObject): boolean {\n // Enum conversion not enabled or no enum present\n if (!options.ctx.enum || !schemaObject.enum) {\n return false;\n }\n\n // Enum must have string, number or null values\n if (!schemaObject.enum.every((v) => [\"string\", \"number\", null].includes(typeof v))) {\n return false;\n }\n\n // If conditionalEnums is enabled, only convert if x-enum-* metadata is present\n if (options.ctx.conditionalEnums) {\n const hasEnumMetadata =\n Array.isArray(schemaObject[\"x-enum-varnames\"]) ||\n Array.isArray(schemaObject[\"x-enumNames\"]) ||\n Array.isArray(schemaObject[\"x-enum-descriptions\"]) ||\n Array.isArray(schemaObject[\"x-enumDescriptions\"]);\n if (!hasEnumMetadata) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Handle SchemaObject minus composition (anyOf/allOf/oneOf)\n */\nfunction transformSchemaObjectCore(schemaObject: SchemaObject, options: TransformNodeOptions): ts.TypeNode | undefined {\n if (\"type\" in schemaObject && schemaObject.type) {\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(schemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n if (result.questionToken) {\n return ts.factory.createUnionTypeNode([result.schema, UNDEFINED]);\n } else {\n return result.schema;\n }\n } else {\n return result;\n }\n }\n }\n\n // primitives\n // type: null\n if (schemaObject.type === \"null\") {\n return NULL;\n }\n // type: string\n if (schemaObject.type === \"string\") {\n return STRING;\n }\n // type: number / type: integer\n if (schemaObject.type === \"number\" || schemaObject.type === \"integer\") {\n return NUMBER;\n }\n // type: boolean\n if (schemaObject.type === \"boolean\") {\n return BOOLEAN;\n }\n\n // type: array (with support for tuples)\n if (schemaObject.type === \"array\") {\n // default to `unknown[]`\n let itemType: ts.TypeNode = UNKNOWN;\n // tuple type\n if (schemaObject.prefixItems || Array.isArray(schemaObject.items)) {\n const prefixItems = schemaObject.prefixItems ?? (schemaObject.items as (SchemaObject | ReferenceObject)[]);\n itemType = ts.factory.createTupleTypeNode(prefixItems.map((item) => transformSchemaObject(item, options)));\n }\n // standard array type\n else if (schemaObject.items) {\n if (hasKey(schemaObject.items, \"type\") && schemaObject.items.type === \"array\") {\n itemType = ts.factory.createArrayTypeNode(transformSchemaObject(schemaObject.items, options));\n } else {\n itemType = transformSchemaObject(schemaObject.items, options);\n }\n }\n\n const min: number =\n typeof schemaObject.minItems === \"number\" && schemaObject.minItems >= 0 ? schemaObject.minItems : 0;\n const max: number | undefined =\n typeof schemaObject.maxItems === \"number\" && schemaObject.maxItems >= 0 && min <= schemaObject.maxItems\n ? schemaObject.maxItems\n : undefined;\n const estimateCodeSize = typeof max !== \"number\" ? min : (max * (max + 1) - min * (min - 1)) / 2;\n if (\n options.ctx.arrayLength &&\n (min !== 0 || max !== undefined) &&\n estimateCodeSize < 30 // \"30\" is an arbitrary number but roughly around when TS starts to struggle with tuple inference in practice\n ) {\n if (min === max) {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n return tsUnion([ts.factory.createTupleTypeNode(elements)]);\n } else if ((schemaObject.maxItems as number) > 0) {\n // if maxItems is set, then return a union of all permutations of possible tuple types\n const members: ts.TypeNode[] = [];\n // populate 1 short of min …\n for (let i = 0; i <= (max ?? 0) - min; i++) {\n const elements: ts.TypeNode[] = [];\n for (let j = min; j < i + min; j++) {\n elements.push(itemType);\n }\n members.push(ts.factory.createTupleTypeNode(elements));\n }\n return tsUnion(members);\n }\n // if maxItems not set, then return a simple tuple type the length of `min`\n else {\n const elements: ts.TypeNode[] = [];\n for (let i = 0; i < min; i++) {\n elements.push(itemType);\n }\n elements.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(itemType)));\n return ts.factory.createTupleTypeNode(elements);\n }\n }\n\n const finalType =\n ts.isTupleTypeNode(itemType) || ts.isArrayTypeNode(itemType)\n ? itemType\n : ts.factory.createArrayTypeNode(itemType); // wrap itemType in array type, but only if not a tuple or array already\n\n return options.ctx.immutable\n ? ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, finalType)\n : finalType;\n }\n\n // polymorphic, or 3.1 nullable\n if (Array.isArray(schemaObject.type) && !Array.isArray(schemaObject)) {\n // skip any primitive types that appear in oneOf as well\n const uniqueTypes: ts.TypeNode[] = [];\n if (Array.isArray(schemaObject.oneOf)) {\n for (const t of schemaObject.type) {\n if (\n (t === \"boolean\" || t === \"string\" || t === \"number\" || t === \"integer\" || t === \"null\") &&\n schemaObject.oneOf.find((o) => typeof o === \"object\" && \"type\" in o && o.type === t)\n ) {\n continue;\n }\n uniqueTypes.push(\n t === \"null\" || t === null\n ? NULL\n : transformSchemaObject(\n { ...schemaObject, type: t, oneOf: undefined } as SchemaObject, // don’t stack oneOf transforms\n options,\n ),\n );\n }\n } else {\n for (const t of schemaObject.type) {\n if (t === \"null\" || t === null) {\n uniqueTypes.push(NULL);\n } else {\n uniqueTypes.push(transformSchemaObject({ ...schemaObject, type: t } as SchemaObject, options));\n }\n }\n }\n return tsUnion(uniqueTypes);\n }\n }\n\n // type: object\n const coreObjectType: ts.TypeElement[] = [];\n\n // discriminators: explicit mapping on schema object\n for (const k of [\"allOf\", \"anyOf\"] as const) {\n if (!schemaObject[k]) {\n continue;\n }\n // for all magic inheritance, we will have already gathered it into\n // ctx.discriminators. But stop objects from referencing their own\n // discriminator meant for children (!schemaObject.discriminator)\n // and don't add discriminator properties if we already added/patched\n // them (options.ctx.discriminators.refsHandled.includes(options.path!).\n const discriminator =\n !schemaObject.discriminator &&\n !options.ctx.discriminators.refsHandled.includes(options.path ?? \"\") &&\n options.ctx.discriminators.objects[options.path ?? \"\"];\n if (discriminator) {\n coreObjectType.unshift(\n createDiscriminatorProperty(discriminator, {\n path: options.path ?? \"\",\n readonly: options.ctx.immutable,\n }),\n );\n break;\n }\n }\n\n if (\n (\"properties\" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length) ||\n (\"additionalProperties\" in schemaObject && schemaObject.additionalProperties) ||\n (\"patternProperties\" in schemaObject && schemaObject.patternProperties) ||\n (\"$defs\" in schemaObject && schemaObject.$defs)\n ) {\n // properties\n if (\"properties\" in schemaObject && schemaObject.properties && Object.keys(schemaObject?.properties).length) {\n for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) {\n if ((typeof v !== \"object\" && typeof v !== \"boolean\") || Array.isArray(v)) {\n throw new Error(\n `${options.path}: invalid property ${k}. Expected Schema Object or boolean, got ${\n Array.isArray(v) ? \"Array\" : typeof v\n }`,\n );\n }\n\n const { $ref, readOnly, writeOnly, hasDefault } =\n typeof v === \"object\"\n ? {\n $ref: \"$ref\" in v && v.$ref,\n readOnly: \"readOnly\" in v && v.readOnly,\n writeOnly: \"writeOnly\" in v && v.writeOnly,\n hasDefault: \"default\" in v && v.default !== undefined,\n }\n : {};\n\n // handle excludeDeprecated option\n if (options.ctx.excludeDeprecated) {\n const resolved = $ref ? options.ctx.resolve($ref) : v;\n if ((resolved as SchemaObject)?.deprecated) {\n continue;\n }\n }\n let optional =\n schemaObject.required?.includes(k) ||\n (schemaObject.required === undefined && options.ctx.propertiesRequiredByDefault) ||\n (hasDefault &&\n options.ctx.defaultNonNullable &&\n !options.path?.includes(\"parameters\") &&\n !options.path?.includes(\"requestBody\") &&\n !options.path?.includes(\"requestBodies\")) // can’t be required, even with defaults\n ? undefined\n : QUESTION_TOKEN;\n let type = $ref\n ? oapiRef($ref)\n : transformSchemaObject(v, {\n ...options,\n path: createRef([options.path, k]),\n });\n\n if (typeof options.ctx.transform === \"function\") {\n const result = options.ctx.transform(v as SchemaObject, options);\n if (result && typeof result === \"object\") {\n if (\"schema\" in result) {\n type = result.schema;\n optional = result.questionToken ? QUESTION_TOKEN : optional;\n } else {\n type = result;\n }\n }\n }\n\n type = wrapWithReadWriteMarker(type, !!readOnly, !!writeOnly, options.ctx);\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && readOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ optional,\n /* type */ type,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n coreObjectType.push(property);\n }\n }\n\n // $defs\n if (\"$defs\" in schemaObject && typeof schemaObject.$defs === \"object\" && Object.keys(schemaObject.$defs).length) {\n const defKeys: ts.TypeElement[] = [];\n for (const [k, v] of Object.entries(schemaObject.$defs)) {\n const defReadOnly = \"readOnly\" in v && !!v.readOnly;\n const defWriteOnly = \"writeOnly\" in v && !!v.writeOnly;\n const defType = wrapWithReadWriteMarker(\n transformSchemaObject(v, { ...options, path: createRef([options.path, \"$defs\", k]) }),\n defReadOnly,\n defWriteOnly,\n options.ctx,\n );\n\n let property = ts.factory.createPropertySignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable || (!options.ctx.readWriteMarkers && defReadOnly),\n }),\n /* name */ tsPropertyIndex(k),\n /* questionToken */ undefined,\n /* type */ defType,\n );\n\n // Apply transformProperty hook if available\n if (typeof options.ctx.transformProperty === \"function\") {\n const result = options.ctx.transformProperty(property, v as SchemaObject, {\n ...options,\n path: createRef([options.path, \"$defs\", k]),\n });\n if (result) {\n property = result;\n }\n }\n\n addJSDocComment(v, property);\n defKeys.push(property);\n }\n coreObjectType.push(\n ts.factory.createPropertySignature(\n /* modifiers */ undefined,\n /* name */ tsPropertyIndex(\"$defs\"),\n /* questionToken */ undefined,\n /* type */ ts.factory.createTypeLiteralNode(defKeys),\n ),\n );\n }\n\n // additionalProperties / patternProperties\n const hasExplicitAdditionalProperties =\n typeof schemaObject.additionalProperties === \"object\" && Object.keys(schemaObject.additionalProperties).length;\n const hasImplicitAdditionalProperties =\n schemaObject.additionalProperties === true ||\n (typeof schemaObject.additionalProperties === \"object\" &&\n Object.keys(schemaObject.additionalProperties).length === 0);\n const patternProperties = hasKey(schemaObject, \"patternProperties\") ? schemaObject.patternProperties : undefined;\n const hasExplicitPatternProperties =\n typeof patternProperties === \"object\" && patternProperties !== null && Object.keys(patternProperties).length > 0;\n const stringIndexTypes = [];\n if (hasExplicitAdditionalProperties) {\n stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties as SchemaObject, options, true));\n }\n if (hasImplicitAdditionalProperties || (!schemaObject.additionalProperties && options.ctx.additionalProperties)) {\n stringIndexTypes.push(UNKNOWN);\n }\n if (hasExplicitPatternProperties && patternProperties && typeof patternProperties === \"object\") {\n for (const [_, v] of getEntries(\n patternProperties as Record,\n options.ctx,\n )) {\n stringIndexTypes.push(transformSchemaObject(v, options));\n }\n }\n\n if (stringIndexTypes.length === 0) {\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n }\n\n const stringIndexType = tsUnion(stringIndexTypes);\n\n return tsIntersection([\n ...(coreObjectType.length ? [ts.factory.createTypeLiteralNode(coreObjectType)] : []),\n ts.factory.createTypeLiteralNode([\n ts.factory.createIndexSignature(\n /* modifiers */ tsModifiers({\n readonly: options.ctx.immutable,\n }),\n /* parameters */ [\n ts.factory.createParameterDeclaration(\n /* modifiers */ undefined,\n /* dotDotDotToken */ undefined,\n /* name */ ts.factory.createIdentifier(\"key\"),\n /* questionToken */ undefined,\n /* type */ STRING,\n ),\n ],\n /* type */ stringIndexType,\n ),\n ]),\n ]);\n }\n\n return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined;\n}\n\n/**\n * Check if an object has a key\n * @param possibleObject - The object to check\n * @param key - The key to check for\n * @returns True if the object has the key, false otherwise\n */\nfunction hasKey(possibleObject: unknown, key: K): possibleObject is { [key in K]: unknown } {\n return typeof possibleObject === \"object\" && possibleObject !== null && key in possibleObject;\n}\n\nfunction applyAdditionalPropertiesToEnum(\n hasAdditionalProperties: boolean,\n unionType: ts.TypeNode,\n schemaObject: SchemaObject,\n) {\n // If additionalProperties is true, add (string & {}) to the union\n if (hasAdditionalProperties && schemaObject.type === \"string\") {\n const stringAndEmptyObject = tsIntersection([STRING, ts.factory.createTypeLiteralNode([])]);\n return tsUnion([unionType, stringAndEmptyObject]);\n }\n return unionType;\n}\n\n/** Wrap type with $Read or $Write marker when readWriteMarkers flag is enabled */\nfunction wrapWithReadWriteMarker(\n type: ts.TypeNode,\n readOnly: boolean,\n writeOnly: boolean,\n ctx: { readWriteMarkers: boolean },\n): ts.TypeNode {\n if (!ctx.readWriteMarkers || (readOnly && writeOnly)) {\n return type;\n }\n if (readOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Read\"), [type]);\n }\n if (writeOnly) {\n return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(\"$Write\"), [type]);\n }\n return type;\n}\n"],"names":["enumType","finalType"],"mappings":";;;;;AAgCA,SAAwB,qBAAA,CACtB,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AACb,EAAA,MAAM,IAAA,GAAO,oCAAA,CAAqC,YAAA,EAAc,OAAA,EAAS,wBAAwB,CAAA;AACjG,EAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,aAAA,KAAkB,UAAA,EAAY;AACnD,IAAA,MAAM,mBAAA,GAAsB,OAAA,CAAQ,GAAA,CAAI,aAAA,CAAc,MAAM,OAAO,CAAA;AACnE,IAAA,IAAI,mBAAA,EAAqB;AACvB,MAAA,OAAO,mBAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAKO,SAAS,oCAAA,CACd,YAAA,EACA,OAAA,EACA,wBAAA,GAA2B,KAAA,EACd;AAMb,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,IAAK,iBAA6B,IAAA,EAAM;AACtC,IAAA,OAAO,OAAA;AAAA,EACT;AAEA,EAAA,IAAI,MAAM,OAAA,CAAQ,YAAY,CAAA,IAAK,OAAO,iBAAiB,QAAA,EAAU;AACnE,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,gCAAA,EAAmC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,GAAI,UAAU,OAAO,YAAY,CAAA,IAAA,EAAO,OAAA,CAAQ,IAAI,CAAA;AAAA,KACnH;AAAA,EACF;AAKA,EAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,IAAA,OAAO,OAAA,CAAQ,aAAa,IAAI,CAAA;AAAA,EAClC;AAKA,EAAA,IAAI,YAAA,CAAa,KAAA,KAAU,IAAA,IAAQ,YAAA,CAAa,UAAU,MAAA,EAAW;AACnE,IAAA,OAAO,SAAA,CAAU,aAAa,KAAK,CAAA;AAAA,EACrC;AAMA,EAAA,IACE,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,KAC9B,EAAE,MAAA,IAAU,YAAA,CAAA,IAAiB,YAAA,CAAa,IAAA,KAAS,QAAA,CAAA,IACpD,EAAE,gBAAgB,YAAA,CAAA,EAClB;AACA,IAAA,MAAM,uBAAA,GAA0B,sBAAA,IAA0B,YAAA,IAAgB,CAAC,CAAC,YAAA,CAAa,oBAAA;AAEzF,IAAA,IAAI,CAAC,uBAAA,IAA4B,YAAA,CAAa,IAAA,KAAS,YAAY,uBAAA,EAA0B;AAE3F,MAAA,IAAI,uBAAA,CAAwB,OAAA,EAAS,YAAY,CAAA,EAAG;AAClD,QAAA,IAAI,QAAA,GAAW,SAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA,CAAE,OAAA,CAAQ,KAAK,GAAG,CAAA;AAE5D,QAAA,QAAA,GAAW,QAAA,CAAS,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AACpD,QAAA,MAAM,WAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAI,CAAC,GAAG,CAAA,MAAO;AAAA,UAChD,IAAA,EAAM,aAAa,iBAAiB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,aAAa,CAAA,GAAI,CAAC,CAAA;AAAA,UAC7E,WAAA,EAAa,aAAa,qBAAqB,CAAA,GAAI,CAAC,CAAA,IAAK,YAAA,CAAa,oBAAoB,CAAA,GAAI,CAAC;AAAA,SACjG,CAAE,CAAA;AAGF,QAAA,IAAI,OAAA,GAAU,KAAA;AACd,QAAA,MAAM,gBAAA,GAAmB,YAAA,CAAa,IAAA,CAAK,MAAA,CAAO,CAAC,SAAA,KAAc;AAC/D,UAAA,IAAI,cAAc,IAAA,EAAM;AACtB,YAAA,OAAA,GAAU,IAAA;AACV,YAAA,OAAO,KAAA;AAAA,UACT;AAEA,UAAA,OAAO,IAAA;AAAA,QACT,CAAC,CAAA;AACD,QAAA,MAAMA,SAAAA,GAAW,MAAA,CAAO,QAAA,EAAU,gBAAA,EAAyC,QAAA,EAAU;AAAA,UACnF,WAAA,EAAa,QAAQ,GAAA,CAAI,WAAA;AAAA,UACzB,MAAA,EAAQ;AAAA;AAAA,SAET,CAAA;AACD,QAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,QAAA,CAASA,SAAQ,CAAA,EAAG;AAChD,UAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAKA,SAAQ,CAAA;AAAA,QACxC;AACA,QAAA,MAAM,GAAA,GAAM,EAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwBA,UAAS,IAAI,CAAA;AAE5D,QAAA,MAAMC,aAAyB,OAAA,GAAU,OAAA,CAAQ,CAAC,GAAA,EAAK,IAAI,CAAC,CAAA,GAAI,GAAA;AAEhE,QAAA,OAAO,+BAAA,CAAgC,uBAAA,EAAyBA,UAAAA,EAAW,YAAY,CAAA;AAAA,MACzF;AAEA,MAAA,MAAM,QAAA,GAAW,YAAA,CAAa,IAAA,CAAK,GAAA,CAAI,SAAS,CAAA;AAChD,MAAA,IAAK,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,IAAK,YAAA,CAAa,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA,IAAM,YAAA,CAAa,QAAA,EAAU;AACrG,QAAA,QAAA,CAAS,KAAK,IAAI,CAAA;AAAA,MACpB;AAEA,MAAA,MAAM,YAAY,+BAAA,CAAgC,uBAAA,EAAyB,OAAA,CAAQ,QAAQ,GAAG,YAAY,CAAA;AAG1G,MAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,YAAA,CAAa,KAAK,KAAA,CAAM,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EAAG;AAC5G,QAAA,MAAM,MAAA,GAAS,QAAA,CAAS,OAAA,CAAQ,IAAA,IAAQ,EAAE,CAAA;AAC1C,QAAA,IAAI,sBAAA,GAAyB,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA;AAEpD,QAAA,sBAAA,GAAyB,sBAAA,CAAuB,OAAA,CAAQ,oBAAA,EAAsB,EAAE,CAAA;AAChF,QAAA,sBAAA,GAAyB,GAAG,sBAAsB,CAAA,MAAA,CAAA;AAIlD,QAAA,MAAM,iBAA2B,EAAC;AAQlC,QAAA,MAAM,oBAA8B,EAAC;AACrC,QAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,MAAA,CAAO,OAAA,CAAQ,QAAQ,CAAA,EAAA,EAAK;AAE9C,UAAA,MAAM,OAAA,GAAU,MAAA,CAAO,OAAA,CAAQ,CAAC,CAAA;AAChC,UAAA,IAAA,CAAK,OAAA,KAAY,WAAW,OAAA,KAAY,OAAA,KAAY,IAAI,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACjF,YAAA,MAAM,IAAA,GAAO,MAAA,CAAO,OAAA,CAAQ,CAAA,GAAI,CAAC,CAAA;AACjC,YAAA,IAAI,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA,EAAG;AAEtB,cAAA,CAAA,EAAA;AAIA,cAAA,MAAM,iBAAA,GAAoB,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAC,CAAA;AACpD,cAAA,KAAA,MAAW,OAAO,iBAAA,EAAmB;AAEnC,gBAAA,IAAI,GAAA,KAAQ,WAAW,GAAA,KAAQ,OAAA,IAAW,CAAC,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,EAAG;AAC5D,kBAAA,iBAAA,CAAkB,KAAK,GAAG,CAAA;AAAA,gBAC5B;AAAA,cACF;AACA,cAAA;AAAA,YACF;AAAA,UACF;AACA,UAAA,cAAA,CAAe,KAAK,OAAO,CAAA;AAAA,QAC7B;AACA,QAAA,MAAM,cAAA,GAAiB,UAAU,cAAc,CAAA;AAE/C,QAAA,MAAM,eAAA,GAAkB,wBAAA;AAAA,UACtB,sBAAA;AAAA;AAAA,UAEA,wBAAA,GACI,GAAG,OAAA,CAAQ,2BAAA;AAAA,YACT,QAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,YACpE,GAAG,OAAA,CAAQ,uBAAA,CAAwB,GAAG,OAAA,CAAQ,gBAAA,CAAiB,QAAQ,CAAC;AAAA,WAC1E,GACA,QAAQ,cAAA,EAAgB,MAAA,EAAW,EAAE,IAAA,EAAM,IAAA,EAAM,mBAAmB,CAAA;AAAA,UACxE,YAAA,CAAa,IAAA;AAAA,UACb;AAAA,YACE,MAAA,EAAQ,IAAA;AAAA,YACR,QAAA,EAAU,IAAA;AAAA,YACV,YAAA,EAAc,QAAQ,GAAA,CAAI;AAAA;AAC5B,SACF;AAEA,QAAA,OAAA,CAAQ,GAAA,CAAI,YAAA,CAAa,IAAA,CAAK,eAAe,CAAA;AAAA,MAC/C;AAEA,MAAA,OAAO,SAAA;AAAA,IACT;AAAA,EACF;AAOA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAA6B;AACxG,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,CAAC,KAAA,EAAO,IAAI,CAAA,IAAK,KAAA,CAAM,SAAQ,EAAG;AAC3C,MAAA,MAAA,CAAO,IAAA;AAAA,QACL,sBAAsB,IAAA,EAAM;AAAA,UAC1B,GAAG,OAAA;AAAA;AAAA,UAEH,IAAA,EAAM,UAAU,CAAC,OAAA,CAAQ,MAAM,QAAA,EAAU,MAAA,CAAO,KAAK,CAAC,CAAC;AAAA,SACxD;AAAA,OACH;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,SAAS,wBAAA,CAAyB,OAA2C,QAAA,EAAoC;AAC/G,IAAA,MAAM,SAAwB,EAAC;AAC/B,IAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,MAAA,IAAI,QAAA;AAGJ,MAAA,IAAI,UAAU,IAAA,EAAM;AAClB,QAAA,QAAA,GAAW,qBAAA,CAAsB,MAAM,OAAO,CAAA;AAE9C,QAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,KAAK,IAAI,CAAA;AAG5D,QAAA,IACE,QAAA,IACA,OAAO,QAAA,KAAa,QAAA,IACpB,YAAA,IAAgB,QAAA;AAAA,QAEhB,CAAC,QAAQ,GAAA,CAAI,cAAA,CAAe,YAAY,QAAA,CAAS,IAAA,CAAK,IAAI,CAAA,EAC1D;AAEA,UAAA,MAAM,aAAA,GAAA,CAAiB,QAAA,IAAY,EAAC,EAAG,MAAA,CAAO,CAAC,GAAA,KAAQ,CAAC,CAAC,QAAA,CAAS,UAAA,GAAa,GAAG,CAAC,CAAA;AACnF,UAAA,IAAI,cAAc,MAAA,EAAQ;AACxB,YAAA,QAAA,GAAW,cAAA,CAAe,QAAA,EAAU,aAAA,EAAe,OAAA,CAAQ,IAAI,YAAY,CAAA;AAAA,UAC7E;AAAA,QACF;AAAA,MACF,CAAA,MAEK;AACH,QAAA,MAAM,YAAA,GAAe,CAAC,GAAI,QAAA,IAAY,EAAG,CAAA;AACzC,QAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,MAAM,OAAA,CAAQ,IAAA,CAAK,QAAQ,CAAA,EAAG;AAC5D,UAAA,YAAA,CAAa,IAAA,CAAK,GAAG,IAAA,CAAK,QAAQ,CAAA;AAAA,QACpC;AACA,QAAA,QAAA,GAAW,sBAAsB,EAAE,GAAG,MAAM,QAAA,EAAU,YAAA,IAAgB,OAAO,CAAA;AAAA,MAC/E;AAEA,MAAA,MAAA,CAAO,KAAK,QAAQ,CAAA;AAAA,IACtB;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAGA,EAAA,IAAI,SAAA;AAGJ,EAAA,MAAM,cAAA,GAAiB,yBAAA,CAA0B,YAAA,EAAc,OAAO,CAAA;AACtE,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,SAAS,EAAC,EAAG,aAAa,QAAQ,CAAA;AAC1F,EAAA,IAAI,cAAA,IAAkB,UAAU,MAAA,EAAQ;AACtC,IAAA,MAAM,KAAA,GAAiC,SAAA,CAAU,MAAA,GAAS,cAAA,CAAe,SAAS,CAAA,GAAI,MAAA;AACtF,IAAA,SAAA,GAAY,eAAe,CAAC,GAAI,cAAA,GAAiB,CAAC,cAAc,CAAA,GAAI,EAAC,EAAI,GAAI,QAAQ,CAAC,KAAK,CAAA,GAAI,EAAG,CAAC,CAAA;AAAA,EACrG;AAGA,EAAA,MAAM,YAAY,wBAAA,CAAyB,YAAA,CAAa,KAAA,IAAS,IAAI,OAAO,CAAA;AAC5E,EAAA,IAAI,UAAU,MAAA,EAAQ;AACpB,IAAA,SAAA,GAAY,OAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,EACvE;AAEA,EAAA,MAAM,SAAA,GAAY,wBAAA;AAAA,IAChB,YAAA,CAAa,SACV,MAAA,IAAU,YAAA,IACT,aAAa,IAAA,KAAS,QAAA,IACrB,YAAA,CAAa,IAAA,IAChB,EAAC;AAAA,IACH;AAAA,GACF;AACA,EAAA,IAAI,UAAU,MAAA,EAAQ;AAEpB,IAAA,IAAI,SAAA,CAAU,KAAA,CAAM,aAAa,CAAA,EAAG;AAClC,MAAA,SAAA,GAAY,OAAA,CAAQ,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,GAAG,SAAS,CAAC,CAAA;AAAA,IACvE,CAAA,MAAO;AACL,MAAA,SAAA,GAAY,cAAA,CAAe,CAAC,GAAI,SAAA,GAAY,CAAC,SAAS,CAAA,GAAI,EAAC,EAAI,OAAA,CAAQ,SAAS,CAAC,CAAC,CAAA;AAAA,IACpF;AAAA,EACF;AAGA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,IAAI,UAAU,YAAA,EAAc;AAC1B,MAAA,SAAA,GAAY,SAAS,MAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,mBAAA,GAAsB,UAAU,KAAK,CAAA;AAAA,IAChF,CAAA,MAAO;AACL,MAAA,SAAA,GAAY,OAAA;AAAA,IACd;AAAA,EACF;AAEA,EAAA,IAAI,SAAA,KAAc,OAAA,IAAW,YAAA,CAAa,QAAA,EAAU;AAClD,IAAA,SAAA,GAAY,UAAA,CAAW,CAAC,SAAS,CAAC,CAAA;AAAA,EACpC;AAEA,EAAA,OAAO,SAAA;AACT;AAKA,SAAS,uBAAA,CAAwB,SAA+B,YAAA,EAAqC;AAEnG,EAAA,IAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,IAAA,IAAQ,CAAC,aAAa,IAAA,EAAM;AAC3C,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,KAAM,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,CAAA,CAAE,QAAA,CAAS,OAAO,CAAC,CAAC,CAAA,EAAG;AAClF,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IAAI,OAAA,CAAQ,IAAI,gBAAA,EAAkB;AAChC,IAAA,MAAM,eAAA,GACJ,MAAM,OAAA,CAAQ,YAAA,CAAa,iBAAiB,CAAC,CAAA,IAC7C,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,aAAa,CAAC,CAAA,IACzC,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,qBAAqB,CAAC,KACjD,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,oBAAoB,CAAC,CAAA;AAClD,IAAA,IAAI,CAAC,eAAA,EAAiB;AACpB,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT;AAKA,SAAS,yBAAA,CAA0B,cAA4B,OAAA,EAAwD;AACrH,EAAA,IAAI,MAAA,IAAU,YAAA,IAAgB,YAAA,CAAa,IAAA,EAAM;AAC/C,IAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,MAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,cAAc,OAAO,CAAA;AAC1D,MAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,QAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,UAAA,IAAI,OAAO,aAAA,EAAe;AACxB,YAAA,OAAO,GAAG,OAAA,CAAQ,mBAAA,CAAoB,CAAC,MAAA,CAAO,MAAA,EAAQ,SAAS,CAAC,CAAA;AAAA,UAClE,CAAA,MAAO;AACL,YAAA,OAAO,MAAA,CAAO,MAAA;AAAA,UAChB;AAAA,QACF,CAAA,MAAO;AACL,UAAA,OAAO,MAAA;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAIA,IAAA,IAAI,YAAA,CAAa,SAAS,MAAA,EAAQ;AAChC,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,QAAA,EAAU;AAClC,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,IAAA,KAAS,QAAA,IAAY,YAAA,CAAa,SAAS,SAAA,EAAW;AACrE,MAAA,OAAO,MAAA;AAAA,IACT;AAEA,IAAA,IAAI,YAAA,CAAa,SAAS,SAAA,EAAW;AACnC,MAAA,OAAO,OAAA;AAAA,IACT;AAGA,IAAA,IAAI,YAAA,CAAa,SAAS,OAAA,EAAS;AAEjC,MAAA,IAAI,QAAA,GAAwB,OAAA;AAE5B,MAAA,IAAI,aAAa,WAAA,IAAe,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACjE,QAAA,MAAM,WAAA,GAAc,YAAA,CAAa,WAAA,IAAgB,YAAA,CAAa,KAAA;AAC9D,QAAA,QAAA,GAAW,EAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,WAAA,CAAY,GAAA,CAAI,CAAC,IAAA,KAAS,qBAAA,CAAsB,IAAA,EAAM,OAAO,CAAC,CAAC,CAAA;AAAA,MAC3G,CAAA,MAAA,IAES,aAAa,KAAA,EAAO;AAC3B,QAAA,IAAI,MAAA,CAAO,aAAa,KAAA,EAAO,MAAM,KAAK,YAAA,CAAa,KAAA,CAAM,SAAS,OAAA,EAAS;AAC7E,UAAA,QAAA,GAAW,GAAG,OAAA,CAAQ,mBAAA,CAAoB,sBAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAC,CAAA;AAAA,QAC9F,CAAA,MAAO;AACL,UAAA,QAAA,GAAW,qBAAA,CAAsB,YAAA,CAAa,KAAA,EAAO,OAAO,CAAA;AAAA,QAC9D;AAAA,MACF;AAEA,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,YAAY,YAAA,CAAa,QAAA,IAAY,CAAA,GAAI,YAAA,CAAa,QAAA,GAAW,CAAA;AACpG,MAAA,MAAM,GAAA,GACJ,OAAO,YAAA,CAAa,QAAA,KAAa,QAAA,IAAY,YAAA,CAAa,QAAA,IAAY,CAAA,IAAK,GAAA,IAAO,YAAA,CAAa,QAAA,GAC3F,YAAA,CAAa,QAAA,GACb,MAAA;AACN,MAAA,MAAM,gBAAA,GAAmB,OAAO,GAAA,KAAQ,QAAA,GAAW,GAAA,GAAA,CAAO,OAAO,GAAA,GAAM,CAAA,CAAA,GAAK,GAAA,IAAO,GAAA,GAAM,CAAA,CAAA,IAAM,CAAA;AAC/F,MAAA,IACE,OAAA,CAAQ,IAAI,WAAA,KACX,GAAA,KAAQ,KAAK,GAAA,KAAQ,MAAA,CAAA,IACtB,mBAAmB,EAAA,EACnB;AACA,QAAA,IAAI,QAAQ,GAAA,EAAK;AACf,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,OAAO,QAAQ,CAAC,EAAA,CAAG,QAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AAAA,QAC3D,CAAA,MAAA,IAAY,YAAA,CAAa,QAAA,GAAsB,CAAA,EAAG;AAEhD,UAAA,MAAM,UAAyB,EAAC;AAEhC,UAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,IAAA,CAAM,GAAA,IAAO,CAAA,IAAK,KAAK,CAAA,EAAA,EAAK;AAC1C,YAAA,MAAM,WAA0B,EAAC;AACjC,YAAA,KAAA,IAAS,CAAA,GAAI,GAAA,EAAK,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,EAAA,EAAK;AAClC,cAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,YACxB;AACA,YAAA,OAAA,CAAQ,IAAA,CAAK,EAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAA;AAAA,UACvD;AACA,UAAA,OAAO,QAAQ,OAAO,CAAA;AAAA,QACxB,CAAA,MAEK;AACH,UAAA,MAAM,WAA0B,EAAC;AACjC,UAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,EAAK,CAAA,EAAA,EAAK;AAC5B,YAAA,QAAA,CAAS,KAAK,QAAQ,CAAA;AAAA,UACxB;AACA,UAAA,QAAA,CAAS,IAAA,CAAK,GAAG,OAAA,CAAQ,kBAAA,CAAmB,GAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAC,CAAC,CAAA;AACrF,UAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,mBAAA,CAAoB,QAAQ,CAAA;AAAA,QAChD;AAAA,MACF;AAEA,MAAA,MAAM,SAAA,GACJ,EAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,IAAK,EAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,GACvD,QAAA,GACA,EAAA,CAAG,OAAA,CAAQ,oBAAoB,QAAQ,CAAA;AAE7C,MAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,GACf,EAAA,CAAG,OAAA,CAAQ,uBAAuB,EAAA,CAAG,UAAA,CAAW,eAAA,EAAiB,SAAS,CAAA,GAC1E,SAAA;AAAA,IACN;AAGA,IAAA,IAAI,KAAA,CAAM,QAAQ,YAAA,CAAa,IAAI,KAAK,CAAC,KAAA,CAAM,OAAA,CAAQ,YAAY,CAAA,EAAG;AAEpE,MAAA,MAAM,cAA6B,EAAC;AACpC,MAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACrC,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAA,CACG,CAAA,KAAM,aAAa,CAAA,KAAM,QAAA,IAAY,MAAM,QAAA,IAAY,CAAA,KAAM,SAAA,IAAa,CAAA,KAAM,MAAA,KACjF,YAAA,CAAa,MAAM,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAA,KAAM,QAAA,IAAY,UAAU,CAAA,IAAK,CAAA,CAAE,IAAA,KAAS,CAAC,CAAA,EACnF;AACA,YAAA;AAAA,UACF;AACA,UAAA,WAAA,CAAY,IAAA;AAAA,YACV,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,GAClB,IAAA,GACA,qBAAA;AAAA,cACE,EAAE,GAAG,YAAA,EAAc,IAAA,EAAM,CAAA,EAAG,OAAO,MAAA,EAAU;AAAA;AAAA,cAC7C;AAAA;AACF,WACN;AAAA,QACF;AAAA,MACF,CAAA,MAAO;AACL,QAAA,KAAA,MAAW,CAAA,IAAK,aAAa,IAAA,EAAM;AACjC,UAAA,IAAI,CAAA,KAAM,MAAA,IAAU,CAAA,KAAM,IAAA,EAAM;AAC9B,YAAA,WAAA,CAAY,KAAK,IAAI,CAAA;AAAA,UACvB,CAAA,MAAO;AACL,YAAA,WAAA,CAAY,IAAA,CAAK,sBAAsB,EAAE,GAAG,cAAc,IAAA,EAAM,CAAA,EAAE,EAAmB,OAAO,CAAC,CAAA;AAAA,UAC/F;AAAA,QACF;AAAA,MACF;AACA,MAAA,OAAO,QAAQ,WAAW,CAAA;AAAA,IAC5B;AAAA,EACF;AAGA,EAAA,MAAM,iBAAmC,EAAC;AAG1C,EAAA,KAAA,MAAW,CAAA,IAAK,CAAC,OAAA,EAAS,OAAO,CAAA,EAAY;AAC3C,IAAA,IAAI,CAAC,YAAA,CAAa,CAAC,CAAA,EAAG;AACpB,MAAA;AAAA,IACF;AAMA,IAAA,MAAM,aAAA,GACJ,CAAC,YAAA,CAAa,aAAA,IACd,CAAC,OAAA,CAAQ,GAAA,CAAI,eAAe,WAAA,CAAY,QAAA,CAAS,QAAQ,IAAA,IAAQ,EAAE,KACnE,OAAA,CAAQ,GAAA,CAAI,eAAe,OAAA,CAAQ,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACvD,IAAA,IAAI,aAAA,EAAe;AACjB,MAAA,cAAA,CAAe,OAAA;AAAA,QACb,4BAA4B,aAAA,EAAe;AAAA,UACzC,IAAA,EAAM,QAAQ,IAAA,IAAQ,EAAA;AAAA,UACtB,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,SACvB;AAAA,OACH;AACA,MAAA;AAAA,IACF;AAAA,EACF;AAEA,EAAA,IACG,YAAA,IAAgB,gBAAgB,YAAA,CAAa,UAAA,IAAc,OAAO,IAAA,CAAK,YAAA,CAAa,UAAU,CAAA,CAAE,MAAA,IAChG,0BAA0B,YAAA,IAAgB,YAAA,CAAa,wBACvD,mBAAA,IAAuB,YAAA,IAAgB,aAAa,iBAAA,IACpD,OAAA,IAAW,YAAA,IAAgB,YAAA,CAAa,KAAA,EACzC;AAEA,IAAA,IAAI,YAAA,IAAgB,gBAAgB,YAAA,CAAa,UAAA,IAAc,OAAO,IAAA,CAAK,YAAA,EAAc,UAAU,CAAA,CAAE,MAAA,EAAQ;AAC3G,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,UAAA,CAAW,YAAA,CAAa,UAAA,IAAc,EAAC,EAAG,OAAA,CAAQ,GAAG,CAAA,EAAG;AAC3E,QAAA,IAAK,OAAO,MAAM,QAAA,IAAY,OAAO,MAAM,SAAA,IAAc,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,EAAG;AACzE,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,EAAG,OAAA,CAAQ,IAAI,CAAA,mBAAA,EAAsB,CAAC,CAAA,yCAAA,EACpC,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAAI,OAAA,GAAU,OAAO,CACtC,CAAA;AAAA,WACF;AAAA,QACF;AAEA,QAAA,MAAM,EAAE,MAAM,QAAA,EAAU,SAAA,EAAW,YAAW,GAC5C,OAAO,MAAM,QAAA,GACT;AAAA,UACE,IAAA,EAAM,MAAA,IAAU,CAAA,IAAK,CAAA,CAAE,IAAA;AAAA,UACvB,QAAA,EAAU,UAAA,IAAc,CAAA,IAAK,CAAA,CAAE,QAAA;AAAA,UAC/B,SAAA,EAAW,WAAA,IAAe,CAAA,IAAK,CAAA,CAAE,SAAA;AAAA,UACjC,UAAA,EAAY,SAAA,IAAa,CAAA,IAAK,CAAA,CAAE,OAAA,KAAY;AAAA,YAE9C,EAAC;AAGP,QAAA,IAAI,OAAA,CAAQ,IAAI,iBAAA,EAAmB;AACjC,UAAA,MAAM,WAAW,IAAA,GAAO,OAAA,CAAQ,GAAA,CAAI,OAAA,CAAsB,IAAI,CAAA,GAAI,CAAA;AAClE,UAAA,IAAK,UAA2B,UAAA,EAAY;AAC1C,YAAA;AAAA,UACF;AAAA,QACF;AACA,QAAA,IAAI,QAAA,GACF,YAAA,CAAa,QAAA,EAAU,QAAA,CAAS,CAAC,CAAA,IAChC,YAAA,CAAa,QAAA,KAAa,MAAA,IAAa,QAAQ,GAAA,CAAI,2BAAA,IACnD,UAAA,IACC,OAAA,CAAQ,IAAI,kBAAA,IACZ,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,YAAY,CAAA,IACpC,CAAC,QAAQ,IAAA,EAAM,QAAA,CAAS,aAAa,CAAA,IACrC,CAAC,OAAA,CAAQ,IAAA,EAAM,QAAA,CAAS,eAAe,IACrC,MAAA,GACA,cAAA;AACN,QAAA,IAAI,OAAO,IAAA,GACP,OAAA,CAAQ,IAAI,CAAA,GACZ,sBAAsB,CAAA,EAAG;AAAA,UACvB,GAAG,OAAA;AAAA,UACH,MAAM,SAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,SAClC,CAAA;AAEL,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,SAAA,KAAc,UAAA,EAAY;AAC/C,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,SAAA,CAAU,GAAmB,OAAO,CAAA;AAC/D,UAAA,IAAI,MAAA,IAAU,OAAO,MAAA,KAAW,QAAA,EAAU;AACxC,YAAA,IAAI,YAAY,MAAA,EAAQ;AACtB,cAAA,IAAA,GAAO,MAAA,CAAO,MAAA;AACd,cAAA,QAAA,GAAW,MAAA,CAAO,gBAAgB,cAAA,GAAiB,QAAA;AAAA,YACrD,CAAA,MAAO;AACL,cAAA,IAAA,GAAO,MAAA;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAEA,QAAA,IAAA,GAAO,uBAAA,CAAwB,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC,SAAA,EAAW,OAAA,CAAQ,GAAG,CAAA;AAEzE,QAAA,IAAI,QAAA,GAAW,GAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACJ,WAAA,CAAY;AAAA,YAC9B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmB,gBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,QAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAM,SAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,CAAC,CAAC;AAAA,WAClC,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAA,eAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,cAAA,CAAe,KAAK,QAAQ,CAAA;AAAA,MAC9B;AAAA,IACF;AAGA,IAAA,IAAI,OAAA,IAAW,YAAA,IAAgB,OAAO,YAAA,CAAa,KAAA,KAAU,QAAA,IAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,KAAK,CAAA,CAAE,MAAA,EAAQ;AAC/G,MAAA,MAAM,UAA4B,EAAC;AACnC,MAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,YAAA,CAAa,KAAK,CAAA,EAAG;AACvD,QAAA,MAAM,WAAA,GAAc,UAAA,IAAc,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,QAAA;AAC3C,QAAA,MAAM,YAAA,GAAe,WAAA,IAAe,CAAA,IAAK,CAAC,CAAC,CAAA,CAAE,SAAA;AAC7C,QAAA,MAAM,OAAA,GAAU,uBAAA;AAAA,UACd,qBAAA,CAAsB,CAAA,EAAG,EAAE,GAAG,SAAS,IAAA,EAAM,SAAA,CAAU,CAAC,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC,GAAG,CAAA;AAAA,UACpF,WAAA;AAAA,UACA,YAAA;AAAA,UACA,OAAA,CAAQ;AAAA,SACV;AAEA,QAAA,IAAI,QAAA,GAAW,GAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACL,WAAA,CAAY;AAAA,YAC7B,UAAU,OAAA,CAAQ,GAAA,CAAI,aAAc,CAAC,OAAA,CAAQ,IAAI,gBAAA,IAAoB;AAAA,WACtE,CAAA;AAAA;AAAA,UACmB,gBAAgB,CAAC,CAAA;AAAA;AAAA,UACjB,MAAA;AAAA;AAAA,UACA;AAAA,SACtB;AAGA,QAAA,IAAI,OAAO,OAAA,CAAQ,GAAA,CAAI,iBAAA,KAAsB,UAAA,EAAY;AACvD,UAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,iBAAA,CAAkB,UAAU,CAAA,EAAmB;AAAA,YACxE,GAAG,OAAA;AAAA,YACH,MAAM,SAAA,CAAU,CAAC,QAAQ,IAAA,EAAM,OAAA,EAAS,CAAC,CAAC;AAAA,WAC3C,CAAA;AACD,UAAA,IAAI,MAAA,EAAQ;AACV,YAAA,QAAA,GAAW,MAAA;AAAA,UACb;AAAA,QACF;AAEA,QAAA,eAAA,CAAgB,GAAG,QAAQ,CAAA;AAC3B,QAAA,OAAA,CAAQ,KAAK,QAAQ,CAAA;AAAA,MACvB;AACA,MAAA,cAAA,CAAe,IAAA;AAAA,QACb,GAAG,OAAA,CAAQ,uBAAA;AAAA;AAAA,UACW,MAAA;AAAA;AAAA,UACA,gBAAgB,OAAO,CAAA;AAAA;AAAA,UACvB,MAAA;AAAA;AAAA,UACA,EAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,OAAO;AAAA;AAC9D,OACF;AAAA,IACF;AAGA,IAAA,MAAM,+BAAA,GACJ,OAAO,YAAA,CAAa,oBAAA,KAAyB,YAAY,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,CAAA,CAAE,MAAA;AAC1G,IAAA,MAAM,+BAAA,GACJ,YAAA,CAAa,oBAAA,KAAyB,IAAA,IACrC,OAAO,YAAA,CAAa,oBAAA,KAAyB,QAAA,IAC5C,MAAA,CAAO,IAAA,CAAK,YAAA,CAAa,oBAAoB,EAAE,MAAA,KAAW,CAAA;AAC9D,IAAA,MAAM,oBAAoB,MAAA,CAAO,YAAA,EAAc,mBAAmB,CAAA,GAAI,aAAa,iBAAA,GAAoB,MAAA;AACvG,IAAA,MAAM,4BAAA,GACJ,OAAO,iBAAA,KAAsB,QAAA,IAAY,iBAAA,KAAsB,QAAQ,MAAA,CAAO,IAAA,CAAK,iBAAiB,CAAA,CAAE,MAAA,GAAS,CAAA;AACjH,IAAA,MAAM,mBAAmB,EAAC;AAC1B,IAAA,IAAI,+BAAA,EAAiC;AACnC,MAAA,gBAAA,CAAiB,KAAK,qBAAA,CAAsB,YAAA,CAAa,oBAAA,EAAsC,OAAA,EAAS,IAAI,CAAC,CAAA;AAAA,IAC/G;AACA,IAAA,IAAI,mCAAoC,CAAC,YAAA,CAAa,oBAAA,IAAwB,OAAA,CAAQ,IAAI,oBAAA,EAAuB;AAC/G,MAAA,gBAAA,CAAiB,KAAK,OAAO,CAAA;AAAA,IAC/B;AACA,IAAA,IAAI,4BAAA,IAAgC,iBAAA,IAAqB,OAAO,iBAAA,KAAsB,QAAA,EAAU;AAC9F,MAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,CAAA,IAAK,UAAA;AAAA,QACnB,iBAAA;AAAA,QACA,OAAA,CAAQ;AAAA,OACV,EAAG;AACD,QAAA,gBAAA,CAAiB,IAAA,CAAK,qBAAA,CAAsB,CAAA,EAAG,OAAO,CAAC,CAAA;AAAA,MACzD;AAAA,IACF;AAEA,IAAA,IAAI,gBAAA,CAAiB,WAAW,CAAA,EAAG;AACjC,MAAA,OAAO,eAAe,MAAA,GAAS,EAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AAAA,IACpF;AAEA,IAAA,MAAM,eAAA,GAAkB,QAAQ,gBAAgB,CAAA;AAEhD,IAAA,OAAO,cAAA,CAAe;AAAA,MACpB,GAAI,cAAA,CAAe,MAAA,GAAS,CAAC,EAAA,CAAG,QAAQ,qBAAA,CAAsB,cAAc,CAAC,CAAA,GAAI,EAAC;AAAA,MAClF,EAAA,CAAG,QAAQ,qBAAA,CAAsB;AAAA,QAC/B,GAAG,OAAA,CAAQ,oBAAA;AAAA;AAAA,UACQ,WAAA,CAAY;AAAA,YAC3B,QAAA,EAAU,QAAQ,GAAA,CAAI;AAAA,WACvB,CAAA;AAAA;AAAA,UACgB;AAAA,YACf,GAAG,OAAA,CAAQ,0BAAA;AAAA;AAAA,cACY,MAAA;AAAA;AAAA,cACA,MAAA;AAAA;AAAA,cACA,EAAA,CAAG,OAAA,CAAQ,gBAAA,CAAiB,KAAK,CAAA;AAAA;AAAA,cACjC,MAAA;AAAA;AAAA,cACA;AAAA;AACvB,WACF;AAAA;AAAA,UACiB;AAAA;AACnB,OACD;AAAA,KACF,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,eAAe,MAAA,GAAS,EAAA,CAAG,OAAA,CAAQ,qBAAA,CAAsB,cAAc,CAAA,GAAI,MAAA;AACpF;AAQA,SAAS,MAAA,CAAyB,gBAAyB,GAAA,EAAmD;AAC5G,EAAA,OAAO,OAAO,cAAA,KAAmB,QAAA,IAAY,cAAA,KAAmB,QAAQ,GAAA,IAAO,cAAA;AACjF;AAEA,SAAS,+BAAA,CACP,uBAAA,EACA,SAAA,EACA,YAAA,EACA;AAEA,EAAA,IAAI,uBAAA,IAA2B,YAAA,CAAa,IAAA,KAAS,QAAA,EAAU;AAC7D,IAAA,MAAM,oBAAA,GAAuB,cAAA,CAAe,CAAC,MAAA,EAAQ,EAAA,CAAG,QAAQ,qBAAA,CAAsB,EAAE,CAAC,CAAC,CAAA;AAC1F,IAAA,OAAO,OAAA,CAAQ,CAAC,SAAA,EAAW,oBAAoB,CAAC,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,SAAA;AACT;AAGA,SAAS,uBAAA,CACP,IAAA,EACA,QAAA,EACA,SAAA,EACA,GAAA,EACa;AACb,EAAA,IAAI,CAAC,GAAA,CAAI,gBAAA,IAAqB,QAAA,IAAY,SAAA,EAAY;AACpD,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwB,EAAA,CAAG,OAAA,CAAQ,iBAAiB,OAAO,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACxF;AACA,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,uBAAA,CAAwB,EAAA,CAAG,OAAA,CAAQ,iBAAiB,QAAQ,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAAA,EACzF;AACA,EAAA,OAAO,IAAA;AACT;;;;"} +\ No newline at end of file +diff --git a/package/dist/index.cjs b/package/dist/index.cjs +new file mode 100644 +index 0000000000000000000000000000000000000000..a2a38744991540e00b6a085aed403feedf0c51b6 +--- /dev/null ++++ b/package/dist/index.cjs +@@ -0,0 +1,3362 @@ ++"use strict"; ++var __create = Object.create; ++var __defProp = Object.defineProperty; ++var __getOwnPropDesc = Object.getOwnPropertyDescriptor; ++var __getOwnPropNames = Object.getOwnPropertyNames; ++var __getProtoOf = Object.getPrototypeOf; ++var __hasOwnProp = Object.prototype.hasOwnProperty; ++var __typeError = (msg) => { ++ throw TypeError(msg); ++}; ++var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; ++var __commonJS = (cb, mod) => function __require() { ++ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; ++}; ++var __export = (target, all) => { ++ for (var name in all) ++ __defProp(target, name, { get: all[name], enumerable: true }); ++}; ++var __copyProps = (to, from, except, desc) => { ++ if (from && typeof from === "object" || typeof from === "function") { ++ for (let key of __getOwnPropNames(from)) ++ if (!__hasOwnProp.call(to, key) && key !== except) ++ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); ++ } ++ return to; ++}; ++var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( ++ // If the importer is in node compatibility mode or this is not an ESM ++ // file that has been converted to a CommonJS file using a Babel- ++ // compatible transform (i.e. "__esModule" has not been set), then set ++ // "default" to the CommonJS "module.exports" for node compatibility. ++ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, ++ mod ++)); ++var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); ++var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); ++var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); ++var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); ++var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); ++var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); ++ ++// ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js ++var require_picocolors = __commonJS({ ++ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2, module2) { ++ var p = process || {}; ++ var argv = p.argv || []; ++ var env2 = p.env || {}; ++ var isColorSupported = !(!!env2.NO_COLOR || argv.includes("--no-color")) && (!!env2.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env2.TERM !== "dumb" || !!env2.CI); ++ var formatter = (open, close, replace = open) => (input) => { ++ let string = "" + input, index = string.indexOf(close, open.length); ++ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; ++ }; ++ var replaceClose = (string, close, replace, index) => { ++ let result = "", cursor = 0; ++ do { ++ result += string.substring(cursor, index) + replace; ++ cursor = index + close.length; ++ index = string.indexOf(close, cursor); ++ } while (~index); ++ return result + string.substring(cursor); ++ }; ++ var createColors = (enabled = isColorSupported) => { ++ let f = enabled ? formatter : () => String; ++ return { ++ isColorSupported: enabled, ++ reset: f("\x1B[0m", "\x1B[0m"), ++ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), ++ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), ++ italic: f("\x1B[3m", "\x1B[23m"), ++ underline: f("\x1B[4m", "\x1B[24m"), ++ inverse: f("\x1B[7m", "\x1B[27m"), ++ hidden: f("\x1B[8m", "\x1B[28m"), ++ strikethrough: f("\x1B[9m", "\x1B[29m"), ++ black: f("\x1B[30m", "\x1B[39m"), ++ red: f("\x1B[31m", "\x1B[39m"), ++ green: f("\x1B[32m", "\x1B[39m"), ++ yellow: f("\x1B[33m", "\x1B[39m"), ++ blue: f("\x1B[34m", "\x1B[39m"), ++ magenta: f("\x1B[35m", "\x1B[39m"), ++ cyan: f("\x1B[36m", "\x1B[39m"), ++ white: f("\x1B[37m", "\x1B[39m"), ++ gray: f("\x1B[90m", "\x1B[39m"), ++ bgBlack: f("\x1B[40m", "\x1B[49m"), ++ bgRed: f("\x1B[41m", "\x1B[49m"), ++ bgGreen: f("\x1B[42m", "\x1B[49m"), ++ bgYellow: f("\x1B[43m", "\x1B[49m"), ++ bgBlue: f("\x1B[44m", "\x1B[49m"), ++ bgMagenta: f("\x1B[45m", "\x1B[49m"), ++ bgCyan: f("\x1B[46m", "\x1B[49m"), ++ bgWhite: f("\x1B[47m", "\x1B[49m"), ++ blackBright: f("\x1B[90m", "\x1B[39m"), ++ redBright: f("\x1B[91m", "\x1B[39m"), ++ greenBright: f("\x1B[92m", "\x1B[39m"), ++ yellowBright: f("\x1B[93m", "\x1B[39m"), ++ blueBright: f("\x1B[94m", "\x1B[39m"), ++ magentaBright: f("\x1B[95m", "\x1B[39m"), ++ cyanBright: f("\x1B[96m", "\x1B[39m"), ++ whiteBright: f("\x1B[97m", "\x1B[39m"), ++ bgBlackBright: f("\x1B[100m", "\x1B[49m"), ++ bgRedBright: f("\x1B[101m", "\x1B[49m"), ++ bgGreenBright: f("\x1B[102m", "\x1B[49m"), ++ bgYellowBright: f("\x1B[103m", "\x1B[49m"), ++ bgBlueBright: f("\x1B[104m", "\x1B[49m"), ++ bgMagentaBright: f("\x1B[105m", "\x1B[49m"), ++ bgCyanBright: f("\x1B[106m", "\x1B[49m"), ++ bgWhiteBright: f("\x1B[107m", "\x1B[49m") ++ }; ++ }; ++ module2.exports = createColors(); ++ module2.exports.createColors = createColors; ++ } ++}); ++ ++// ../../node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/index.js ++var require_js_tokens = __commonJS({ ++ "../../node_modules/.pnpm/js-tokens@4.0.0/node_modules/js-tokens/index.js"(exports2) { ++ Object.defineProperty(exports2, "__esModule", { ++ value: true ++ }); ++ exports2.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; ++ exports2.matchToToken = function(match) { ++ var token = { type: "invalid", value: match[0], closed: void 0 }; ++ if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]); ++ else if (match[5]) token.type = "comment"; ++ else if (match[6]) token.type = "comment", token.closed = !!match[7]; ++ else if (match[8]) token.type = "regex"; ++ else if (match[9]) token.type = "number"; ++ else if (match[10]) token.type = "name"; ++ else if (match[11]) token.type = "punctuator"; ++ else if (match[12]) token.type = "whitespace"; ++ return token; ++ }; ++ } ++}); ++ ++// ../../node_modules/.pnpm/@babel+helper-validator-identifier@7.25.9/node_modules/@babel/helper-validator-identifier/lib/identifier.js ++var require_identifier = __commonJS({ ++ "../../node_modules/.pnpm/@babel+helper-validator-identifier@7.25.9/node_modules/@babel/helper-validator-identifier/lib/identifier.js"(exports2) { ++ "use strict"; ++ Object.defineProperty(exports2, "__esModule", { ++ value: true ++ }); ++ exports2.isIdentifierChar = isIdentifierChar; ++ exports2.isIdentifierName = isIdentifierName; ++ exports2.isIdentifierStart = isIdentifierStart; ++ var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CD\uA7D0\uA7D1\uA7D3\uA7D5-\uA7DC\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; ++ var nonASCIIidentifierChars = "\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65"; ++ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); ++ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); ++ nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; ++ var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; ++ var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; ++ function isInAstralSet(code, set) { ++ let pos = 65536; ++ for (let i = 0, length = set.length; i < length; i += 2) { ++ pos += set[i]; ++ if (pos > code) return false; ++ pos += set[i + 1]; ++ if (pos >= code) return true; ++ } ++ return false; ++ } ++ function isIdentifierStart(code) { ++ if (code < 65) return code === 36; ++ if (code <= 90) return true; ++ if (code < 97) return code === 95; ++ if (code <= 122) return true; ++ if (code <= 65535) { ++ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)); ++ } ++ return isInAstralSet(code, astralIdentifierStartCodes); ++ } ++ function isIdentifierChar(code) { ++ if (code < 48) return code === 36; ++ if (code < 58) return true; ++ if (code < 65) return false; ++ if (code <= 90) return true; ++ if (code < 97) return code === 95; ++ if (code <= 122) return true; ++ if (code <= 65535) { ++ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)); ++ } ++ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); ++ } ++ function isIdentifierName(name) { ++ let isFirst = true; ++ for (let i = 0; i < name.length; i++) { ++ let cp = name.charCodeAt(i); ++ if ((cp & 64512) === 55296 && i + 1 < name.length) { ++ const trail = name.charCodeAt(++i); ++ if ((trail & 64512) === 56320) { ++ cp = 65536 + ((cp & 1023) << 10) + (trail & 1023); ++ } ++ } ++ if (isFirst) { ++ isFirst = false; ++ if (!isIdentifierStart(cp)) { ++ return false; ++ } ++ } else if (!isIdentifierChar(cp)) { ++ return false; ++ } ++ } ++ return !isFirst; ++ } ++ } ++}); ++ ++// ../../node_modules/.pnpm/@babel+helper-validator-identifier@7.25.9/node_modules/@babel/helper-validator-identifier/lib/keyword.js ++var require_keyword = __commonJS({ ++ "../../node_modules/.pnpm/@babel+helper-validator-identifier@7.25.9/node_modules/@babel/helper-validator-identifier/lib/keyword.js"(exports2) { ++ "use strict"; ++ Object.defineProperty(exports2, "__esModule", { ++ value: true ++ }); ++ exports2.isKeyword = isKeyword; ++ exports2.isReservedWord = isReservedWord; ++ exports2.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; ++ exports2.isStrictBindReservedWord = isStrictBindReservedWord; ++ exports2.isStrictReservedWord = isStrictReservedWord; ++ var reservedWords = { ++ keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], ++ strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], ++ strictBind: ["eval", "arguments"] ++ }; ++ var keywords = new Set(reservedWords.keyword); ++ var reservedWordsStrictSet = new Set(reservedWords.strict); ++ var reservedWordsStrictBindSet = new Set(reservedWords.strictBind); ++ function isReservedWord(word, inModule) { ++ return inModule && word === "await" || word === "enum"; ++ } ++ function isStrictReservedWord(word, inModule) { ++ return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); ++ } ++ function isStrictBindOnlyReservedWord(word) { ++ return reservedWordsStrictBindSet.has(word); ++ } ++ function isStrictBindReservedWord(word, inModule) { ++ return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); ++ } ++ function isKeyword(word) { ++ return keywords.has(word); ++ } ++ } ++}); ++ ++// ../../node_modules/.pnpm/@babel+helper-validator-identifier@7.25.9/node_modules/@babel/helper-validator-identifier/lib/index.js ++var require_lib = __commonJS({ ++ "../../node_modules/.pnpm/@babel+helper-validator-identifier@7.25.9/node_modules/@babel/helper-validator-identifier/lib/index.js"(exports2) { ++ "use strict"; ++ Object.defineProperty(exports2, "__esModule", { ++ value: true ++ }); ++ Object.defineProperty(exports2, "isIdentifierChar", { ++ enumerable: true, ++ get: function() { ++ return _identifier.isIdentifierChar; ++ } ++ }); ++ Object.defineProperty(exports2, "isIdentifierName", { ++ enumerable: true, ++ get: function() { ++ return _identifier.isIdentifierName; ++ } ++ }); ++ Object.defineProperty(exports2, "isIdentifierStart", { ++ enumerable: true, ++ get: function() { ++ return _identifier.isIdentifierStart; ++ } ++ }); ++ Object.defineProperty(exports2, "isKeyword", { ++ enumerable: true, ++ get: function() { ++ return _keyword.isKeyword; ++ } ++ }); ++ Object.defineProperty(exports2, "isReservedWord", { ++ enumerable: true, ++ get: function() { ++ return _keyword.isReservedWord; ++ } ++ }); ++ Object.defineProperty(exports2, "isStrictBindOnlyReservedWord", { ++ enumerable: true, ++ get: function() { ++ return _keyword.isStrictBindOnlyReservedWord; ++ } ++ }); ++ Object.defineProperty(exports2, "isStrictBindReservedWord", { ++ enumerable: true, ++ get: function() { ++ return _keyword.isStrictBindReservedWord; ++ } ++ }); ++ Object.defineProperty(exports2, "isStrictReservedWord", { ++ enumerable: true, ++ get: function() { ++ return _keyword.isStrictReservedWord; ++ } ++ }); ++ var _identifier = require_identifier(); ++ var _keyword = require_keyword(); ++ } ++}); ++ ++// ../../node_modules/.pnpm/@babel+code-frame@7.26.2/node_modules/@babel/code-frame/lib/index.js ++var require_lib2 = __commonJS({ ++ "../../node_modules/.pnpm/@babel+code-frame@7.26.2/node_modules/@babel/code-frame/lib/index.js"(exports2) { ++ "use strict"; ++ Object.defineProperty(exports2, "__esModule", { value: true }); ++ var picocolors = require_picocolors(); ++ var jsTokens = require_js_tokens(); ++ var helperValidatorIdentifier = require_lib(); ++ function isColorSupported() { ++ return typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported; ++ } ++ var compose = (f, g) => (v) => f(g(v)); ++ function buildDefs(colors) { ++ return { ++ keyword: colors.cyan, ++ capitalized: colors.yellow, ++ jsxIdentifier: colors.yellow, ++ punctuator: colors.yellow, ++ number: colors.magenta, ++ string: colors.green, ++ regex: colors.magenta, ++ comment: colors.gray, ++ invalid: compose(compose(colors.white, colors.bgRed), colors.bold), ++ gutter: colors.gray, ++ marker: compose(colors.red, colors.bold), ++ message: compose(colors.red, colors.bold), ++ reset: colors.reset ++ }; ++ } ++ var defsOn = buildDefs(picocolors.createColors(true)); ++ var defsOff = buildDefs(picocolors.createColors(false)); ++ function getDefs(enabled) { ++ return enabled ? defsOn : defsOff; ++ } ++ var sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]); ++ var NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/; ++ var BRACKET = /^[()[\]{}]$/; ++ var tokenize; ++ { ++ const JSX_TAG = /^[a-z][\w-]*$/i; ++ const getTokenType = function(token, offset, text) { ++ if (token.type === "name") { ++ if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) { ++ return "keyword"; ++ } ++ if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === " defs[type](str)).join("\n"); ++ } else { ++ highlighted += value; ++ } ++ } ++ return highlighted; ++ } ++ var deprecationWarningShown = false; ++ var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; ++ function getMarkerLines(loc, source, opts) { ++ const startLoc = Object.assign({ ++ column: 0, ++ line: -1 ++ }, loc.start); ++ const endLoc = Object.assign({}, startLoc, loc.end); ++ const { ++ linesAbove = 2, ++ linesBelow = 3 ++ } = opts || {}; ++ const startLine = startLoc.line; ++ const startColumn = startLoc.column; ++ const endLine = endLoc.line; ++ const endColumn = endLoc.column; ++ let start = Math.max(startLine - (linesAbove + 1), 0); ++ let end = Math.min(source.length, endLine + linesBelow); ++ if (startLine === -1) { ++ start = 0; ++ } ++ if (endLine === -1) { ++ end = source.length; ++ } ++ const lineDiff = endLine - startLine; ++ const markerLines = {}; ++ if (lineDiff) { ++ for (let i = 0; i <= lineDiff; i++) { ++ const lineNumber = i + startLine; ++ if (!startColumn) { ++ markerLines[lineNumber] = true; ++ } else if (i === 0) { ++ const sourceLength = source[lineNumber - 1].length; ++ markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; ++ } else if (i === lineDiff) { ++ markerLines[lineNumber] = [0, endColumn]; ++ } else { ++ const sourceLength = source[lineNumber - i].length; ++ markerLines[lineNumber] = [0, sourceLength]; ++ } ++ } ++ } else { ++ if (startColumn === endColumn) { ++ if (startColumn) { ++ markerLines[startLine] = [startColumn, 0]; ++ } else { ++ markerLines[startLine] = true; ++ } ++ } else { ++ markerLines[startLine] = [startColumn, endColumn - startColumn]; ++ } ++ } ++ return { ++ start, ++ end, ++ markerLines ++ }; ++ } ++ function codeFrameColumns2(rawLines, loc, opts = {}) { ++ const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode; ++ const defs = getDefs(shouldHighlight); ++ const lines = rawLines.split(NEWLINE); ++ const { ++ start, ++ end, ++ markerLines ++ } = getMarkerLines(loc, lines, opts); ++ const hasColumns = loc.start && typeof loc.start.column === "number"; ++ const numberMaxWidth = String(end).length; ++ const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines; ++ let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index2) => { ++ const number = start + 1 + index2; ++ const paddedNumber = ` ${number}`.slice(-numberMaxWidth); ++ const gutter = ` ${paddedNumber} |`; ++ const hasMarker = markerLines[number]; ++ const lastMarkerLine = !markerLines[number + 1]; ++ if (hasMarker) { ++ let markerLine = ""; ++ if (Array.isArray(hasMarker)) { ++ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); ++ const numberOfMarkers = hasMarker[1] || 1; ++ markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join(""); ++ if (lastMarkerLine && opts.message) { ++ markerLine += " " + defs.message(opts.message); ++ } ++ } ++ return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); ++ } else { ++ return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`; ++ } ++ }).join("\n"); ++ if (opts.message && !hasColumns) { ++ frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message} ++${frame}`; ++ } ++ if (shouldHighlight) { ++ return defs.reset(frame); ++ } else { ++ return frame; ++ } ++ } ++ function index(rawLines, lineNumber, colNumber, opts = {}) { ++ if (!deprecationWarningShown) { ++ deprecationWarningShown = true; ++ const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; ++ if (process.emitWarning) { ++ process.emitWarning(message, "DeprecationWarning"); ++ } else { ++ const deprecationError = new Error(message); ++ deprecationError.name = "DeprecationWarning"; ++ console.warn(new Error(message)); ++ } ++ } ++ colNumber = Math.max(colNumber, 0); ++ const location = { ++ start: { ++ column: colNumber, ++ line: lineNumber ++ } ++ }; ++ return codeFrameColumns2(rawLines, location, opts); ++ } ++ exports2.codeFrameColumns = codeFrameColumns2; ++ exports2.default = index; ++ exports2.highlight = highlight; ++ } ++}); ++ ++// ../../node_modules/.pnpm/ansi-colors@4.1.3/node_modules/ansi-colors/symbols.js ++var require_symbols = __commonJS({ ++ "../../node_modules/.pnpm/ansi-colors@4.1.3/node_modules/ansi-colors/symbols.js"(exports2, module2) { ++ "use strict"; ++ var isHyper = typeof process !== "undefined" && process.env.TERM_PROGRAM === "Hyper"; ++ var isWindows = typeof process !== "undefined" && process.platform === "win32"; ++ var isLinux = typeof process !== "undefined" && process.platform === "linux"; ++ var common = { ++ ballotDisabled: "\u2612", ++ ballotOff: "\u2610", ++ ballotOn: "\u2611", ++ bullet: "\u2022", ++ bulletWhite: "\u25E6", ++ fullBlock: "\u2588", ++ heart: "\u2764", ++ identicalTo: "\u2261", ++ line: "\u2500", ++ mark: "\u203B", ++ middot: "\xB7", ++ minus: "\uFF0D", ++ multiplication: "\xD7", ++ obelus: "\xF7", ++ pencilDownRight: "\u270E", ++ pencilRight: "\u270F", ++ pencilUpRight: "\u2710", ++ percent: "%", ++ pilcrow2: "\u2761", ++ pilcrow: "\xB6", ++ plusMinus: "\xB1", ++ question: "?", ++ section: "\xA7", ++ starsOff: "\u2606", ++ starsOn: "\u2605", ++ upDownArrow: "\u2195" ++ }; ++ var windows = Object.assign({}, common, { ++ check: "\u221A", ++ cross: "\xD7", ++ ellipsisLarge: "...", ++ ellipsis: "...", ++ info: "i", ++ questionSmall: "?", ++ pointer: ">", ++ pointerSmall: "\xBB", ++ radioOff: "( )", ++ radioOn: "(*)", ++ warning: "\u203C" ++ }); ++ var other = Object.assign({}, common, { ++ ballotCross: "\u2718", ++ check: "\u2714", ++ cross: "\u2716", ++ ellipsisLarge: "\u22EF", ++ ellipsis: "\u2026", ++ info: "\u2139", ++ questionFull: "\uFF1F", ++ questionSmall: "\uFE56", ++ pointer: isLinux ? "\u25B8" : "\u276F", ++ pointerSmall: isLinux ? "\u2023" : "\u203A", ++ radioOff: "\u25EF", ++ radioOn: "\u25C9", ++ warning: "\u26A0" ++ }); ++ module2.exports = isWindows && !isHyper ? windows : other; ++ Reflect.defineProperty(module2.exports, "common", { enumerable: false, value: common }); ++ Reflect.defineProperty(module2.exports, "windows", { enumerable: false, value: windows }); ++ Reflect.defineProperty(module2.exports, "other", { enumerable: false, value: other }); ++ } ++}); ++ ++// ../../node_modules/.pnpm/ansi-colors@4.1.3/node_modules/ansi-colors/index.js ++var require_ansi_colors = __commonJS({ ++ "../../node_modules/.pnpm/ansi-colors@4.1.3/node_modules/ansi-colors/index.js"(exports2, module2) { ++ "use strict"; ++ var isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); ++ var ANSI_REGEX = /[\u001b\u009b][[\]#;?()]*(?:(?:(?:[^\W_]*;?[^\W_]*)\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g; ++ var hasColor = () => { ++ if (typeof process !== "undefined") { ++ return process.env.FORCE_COLOR !== "0"; ++ } ++ return false; ++ }; ++ var create = () => { ++ const colors = { ++ enabled: hasColor(), ++ visible: true, ++ styles: {}, ++ keys: {} ++ }; ++ const ansi = (style2) => { ++ let open = style2.open = `\x1B[${style2.codes[0]}m`; ++ let close = style2.close = `\x1B[${style2.codes[1]}m`; ++ let regex = style2.regex = new RegExp(`\\u001b\\[${style2.codes[1]}m`, "g"); ++ style2.wrap = (input, newline) => { ++ if (input.includes(close)) input = input.replace(regex, close + open); ++ let output = open + input + close; ++ return newline ? output.replace(/\r*\n/g, `${close}$&${open}`) : output; ++ }; ++ return style2; ++ }; ++ const wrap = (style2, input, newline) => { ++ return typeof style2 === "function" ? style2(input) : style2.wrap(input, newline); ++ }; ++ const style = (input, stack) => { ++ if (input === "" || input == null) return ""; ++ if (colors.enabled === false) return input; ++ if (colors.visible === false) return ""; ++ let str = "" + input; ++ let nl = str.includes("\n"); ++ let n = stack.length; ++ if (n > 0 && stack.includes("unstyle")) { ++ stack = [.../* @__PURE__ */ new Set(["unstyle", ...stack])].reverse(); ++ } ++ while (n-- > 0) str = wrap(colors.styles[stack[n]], str, nl); ++ return str; ++ }; ++ const define = (name, codes, type) => { ++ colors.styles[name] = ansi({ name, codes }); ++ let keys = colors.keys[type] || (colors.keys[type] = []); ++ keys.push(name); ++ Reflect.defineProperty(colors, name, { ++ configurable: true, ++ enumerable: true, ++ set(value) { ++ colors.alias(name, value); ++ }, ++ get() { ++ let color = (input) => style(input, color.stack); ++ Reflect.setPrototypeOf(color, colors); ++ color.stack = this.stack ? this.stack.concat(name) : [name]; ++ return color; ++ } ++ }); ++ }; ++ define("reset", [0, 0], "modifier"); ++ define("bold", [1, 22], "modifier"); ++ define("dim", [2, 22], "modifier"); ++ define("italic", [3, 23], "modifier"); ++ define("underline", [4, 24], "modifier"); ++ define("inverse", [7, 27], "modifier"); ++ define("hidden", [8, 28], "modifier"); ++ define("strikethrough", [9, 29], "modifier"); ++ define("black", [30, 39], "color"); ++ define("red", [31, 39], "color"); ++ define("green", [32, 39], "color"); ++ define("yellow", [33, 39], "color"); ++ define("blue", [34, 39], "color"); ++ define("magenta", [35, 39], "color"); ++ define("cyan", [36, 39], "color"); ++ define("white", [37, 39], "color"); ++ define("gray", [90, 39], "color"); ++ define("grey", [90, 39], "color"); ++ define("bgBlack", [40, 49], "bg"); ++ define("bgRed", [41, 49], "bg"); ++ define("bgGreen", [42, 49], "bg"); ++ define("bgYellow", [43, 49], "bg"); ++ define("bgBlue", [44, 49], "bg"); ++ define("bgMagenta", [45, 49], "bg"); ++ define("bgCyan", [46, 49], "bg"); ++ define("bgWhite", [47, 49], "bg"); ++ define("blackBright", [90, 39], "bright"); ++ define("redBright", [91, 39], "bright"); ++ define("greenBright", [92, 39], "bright"); ++ define("yellowBright", [93, 39], "bright"); ++ define("blueBright", [94, 39], "bright"); ++ define("magentaBright", [95, 39], "bright"); ++ define("cyanBright", [96, 39], "bright"); ++ define("whiteBright", [97, 39], "bright"); ++ define("bgBlackBright", [100, 49], "bgBright"); ++ define("bgRedBright", [101, 49], "bgBright"); ++ define("bgGreenBright", [102, 49], "bgBright"); ++ define("bgYellowBright", [103, 49], "bgBright"); ++ define("bgBlueBright", [104, 49], "bgBright"); ++ define("bgMagentaBright", [105, 49], "bgBright"); ++ define("bgCyanBright", [106, 49], "bgBright"); ++ define("bgWhiteBright", [107, 49], "bgBright"); ++ colors.ansiRegex = ANSI_REGEX; ++ colors.hasColor = colors.hasAnsi = (str) => { ++ colors.ansiRegex.lastIndex = 0; ++ return typeof str === "string" && str !== "" && colors.ansiRegex.test(str); ++ }; ++ colors.alias = (name, color) => { ++ let fn = typeof color === "string" ? colors[color] : color; ++ if (typeof fn !== "function") { ++ throw new TypeError("Expected alias to be the name of an existing color (string) or a function"); ++ } ++ if (!fn.stack) { ++ Reflect.defineProperty(fn, "name", { value: name }); ++ colors.styles[name] = fn; ++ fn.stack = [name]; ++ } ++ Reflect.defineProperty(colors, name, { ++ configurable: true, ++ enumerable: true, ++ set(value) { ++ colors.alias(name, value); ++ }, ++ get() { ++ let color2 = (input) => style(input, color2.stack); ++ Reflect.setPrototypeOf(color2, colors); ++ color2.stack = this.stack ? this.stack.concat(fn.stack) : fn.stack; ++ return color2; ++ } ++ }); ++ }; ++ colors.theme = (custom) => { ++ if (!isObject(custom)) throw new TypeError("Expected theme to be an object"); ++ for (let name of Object.keys(custom)) { ++ colors.alias(name, custom[name]); ++ } ++ return colors; ++ }; ++ colors.alias("unstyle", (str) => { ++ if (typeof str === "string" && str !== "") { ++ colors.ansiRegex.lastIndex = 0; ++ return str.replace(colors.ansiRegex, ""); ++ } ++ return ""; ++ }); ++ colors.alias("noop", (str) => str); ++ colors.none = colors.clear = colors.noop; ++ colors.stripColor = colors.unstyle; ++ colors.symbols = require_symbols(); ++ colors.define = define; ++ return colors; ++ }; ++ module2.exports = create(); ++ module2.exports.create = create; ++ } ++}); ++ ++// src/index.ts ++var index_exports = {}; ++__export(index_exports, { ++ BOOLEAN: () => BOOLEAN, ++ COMMENT_HEADER: () => COMMENT_HEADER, ++ FALSE: () => FALSE, ++ JS_ENUM_INVALID_CHARS_RE: () => JS_ENUM_INVALID_CHARS_RE, ++ JS_PROPERTY_INDEX_INVALID_CHARS_RE: () => JS_PROPERTY_INDEX_INVALID_CHARS_RE, ++ JS_PROPERTY_INDEX_RE: () => JS_PROPERTY_INDEX_RE, ++ NEVER: () => NEVER, ++ NULL: () => NULL, ++ NUMBER: () => NUMBER, ++ QUESTION_TOKEN: () => QUESTION_TOKEN, ++ SPECIAL_CHARACTER_MAP: () => SPECIAL_CHARACTER_MAP, ++ STRING: () => STRING, ++ TRUE: () => TRUE, ++ UNDEFINED: () => UNDEFINED, ++ UNKNOWN: () => UNKNOWN, ++ addJSDocComment: () => addJSDocComment, ++ astToString: () => astToString, ++ c: () => import_ansi_colors.default, ++ createDiscriminatorProperty: () => createDiscriminatorProperty, ++ createRef: () => createRef, ++ debug: () => debug, ++ default: () => openapiTS, ++ enumCache: () => enumCache, ++ error: () => error, ++ formatTime: () => formatTime, ++ getEntries: () => getEntries, ++ injectOperationObject: () => injectOperationObject, ++ oapiRef: () => oapiRef, ++ resolveRef: () => resolveRef, ++ scanDiscriminators: () => scanDiscriminators, ++ stringToAST: () => stringToAST, ++ transformComponentsObject: () => transformComponentsObject, ++ transformHeaderObject: () => transformHeaderObject, ++ transformMediaTypeObject: () => transformMediaTypeObject, ++ transformOperationObject: () => transformOperationObject, ++ transformParameterObject: () => transformParameterObject, ++ transformPathItemObject: () => transformPathItemObject, ++ transformPathsObject: () => transformPathsObject, ++ transformRequestBodyObject: () => transformRequestBodyObject, ++ transformResponseObject: () => transformResponseObject, ++ transformResponsesObject: () => transformResponsesObject, ++ transformSchema: () => transformSchema, ++ transformSchemaObject: () => transformSchemaObject, ++ transformSchemaObjectWithComposition: () => transformSchemaObjectWithComposition, ++ tsArrayLiteralExpression: () => tsArrayLiteralExpression, ++ tsDedupe: () => tsDedupe, ++ tsEnum: () => tsEnum, ++ tsEnumMember: () => tsEnumMember, ++ tsIntersection: () => tsIntersection, ++ tsIsPrimitive: () => tsIsPrimitive, ++ tsLiteral: () => tsLiteral, ++ tsModifiers: () => tsModifiers, ++ tsNullable: () => tsNullable, ++ tsOmit: () => tsOmit, ++ tsPropertyIndex: () => tsPropertyIndex, ++ tsReadonlyArray: () => tsReadonlyArray, ++ tsRecord: () => tsRecord, ++ tsUnion: () => tsUnion, ++ tsWithRequired: () => tsWithRequired, ++ walk: () => walk, ++ warn: () => warn ++}); ++module.exports = __toCommonJS(index_exports); ++var import_openapi_core2 = require("@redocly/openapi-core"); ++var import_node_perf_hooks5 = require("node:perf_hooks"); ++ ++// src/lib/redoc.ts ++var import_openapi_core = require("@redocly/openapi-core"); ++var import_node_perf_hooks = require("node:perf_hooks"); ++var import_node_stream = require("node:stream"); ++var import_node_url = require("node:url"); ++ ++// ../../node_modules/.pnpm/parse-json@8.1.0/node_modules/parse-json/index.js ++var import_code_frame = __toESM(require_lib2(), 1); ++ ++// ../../node_modules/.pnpm/index-to-position@0.1.2/node_modules/index-to-position/index.js ++var safeLastIndexOf = (string, searchString, index) => index < 0 ? -1 : string.lastIndexOf(searchString, index); ++function getPosition(text, textIndex) { ++ const lineBreakBefore = safeLastIndexOf(text, "\n", textIndex - 1); ++ const column = textIndex - lineBreakBefore - 1; ++ let line = 0; ++ for (let index = lineBreakBefore; index >= 0; index = safeLastIndexOf(text, "\n", index - 1)) { ++ line++; ++ } ++ return { line, column }; ++} ++function indexToLineColumn(text, textIndex, { oneBased = false } = {}) { ++ if (textIndex < 0 || textIndex >= text.length && text.length > 0) { ++ throw new RangeError("Index out of bounds"); ++ } ++ const position = getPosition(text, textIndex); ++ return oneBased ? { line: position.line + 1, column: position.column + 1 } : position; ++} ++ ++// ../../node_modules/.pnpm/parse-json@8.1.0/node_modules/parse-json/index.js ++var getCodePoint = (character) => `\\u{${character.codePointAt(0).toString(16)}}`; ++var _message; ++var _JSONError = class _JSONError extends Error { ++ constructor(message) { ++ var _a; ++ super(); ++ __publicField(this, "name", "JSONError"); ++ __publicField(this, "fileName"); ++ __publicField(this, "codeFrame"); ++ __publicField(this, "rawCodeFrame"); ++ __privateAdd(this, _message); ++ __privateSet(this, _message, message); ++ (_a = Error.captureStackTrace) == null ? void 0 : _a.call(Error, this, _JSONError); ++ } ++ get message() { ++ const { fileName, codeFrame } = this; ++ return `${__privateGet(this, _message)}${fileName ? ` in ${fileName}` : ""}${codeFrame ? ` ++ ++${codeFrame} ++` : ""}`; ++ } ++ set message(message) { ++ __privateSet(this, _message, message); ++ } ++}; ++_message = new WeakMap(); ++var JSONError = _JSONError; ++var generateCodeFrame = (string, location, highlightCode = true) => (0, import_code_frame.codeFrameColumns)(string, { start: location }, { highlightCode }); ++var getErrorLocation = (string, message) => { ++ const match = message.match(/in JSON at position (?\d+)(?: \(line (?\d+) column (?\d+)\))?$/); ++ if (!match) { ++ return; ++ } ++ let { index, line, column } = match.groups; ++ if (line && column) { ++ return { line: Number(line), column: Number(column) }; ++ } ++ index = Number(index); ++ if (index === string.length) { ++ const { line: line2, column: column2 } = indexToLineColumn(string, string.length - 1, { oneBased: true }); ++ return { line: line2, column: column2 + 1 }; ++ } ++ return indexToLineColumn(string, index, { oneBased: true }); ++}; ++var addCodePointToUnexpectedToken = (message) => message.replace( ++ // TODO[engine:node@>=20]: The token always quoted after Node.js 20 ++ /(?<=^Unexpected token )(?')?(.)\k/, ++ (_, _quote, token) => `"${token}"(${getCodePoint(token)})` ++); ++function parseJson(string, reviver, fileName) { ++ if (typeof reviver === "string") { ++ fileName = reviver; ++ reviver = void 0; ++ } ++ let message; ++ try { ++ return JSON.parse(string, reviver); ++ } catch (error2) { ++ message = error2.message; ++ } ++ let location; ++ if (string) { ++ location = getErrorLocation(string, message); ++ message = addCodePointToUnexpectedToken(message); ++ } else { ++ message += " while parsing empty string"; ++ } ++ const jsonError = new JSONError(message); ++ jsonError.fileName = fileName; ++ if (location) { ++ jsonError.codeFrame = generateCodeFrame(string, location); ++ jsonError.rawCodeFrame = generateCodeFrame( ++ string, ++ location, ++ /* highlightCode */ ++ false ++ ); ++ } ++ throw jsonError; ++} ++ ++// src/lib/utils.ts ++var import_ref_utils2 = require("@redocly/openapi-core/lib/ref-utils.js"); ++var import_ansi_colors = __toESM(require_ansi_colors(), 1); ++ ++// ../../node_modules/.pnpm/supports-color@9.4.0/node_modules/supports-color/index.js ++var import_node_process = __toESM(require("node:process"), 1); ++var import_node_os = __toESM(require("node:os"), 1); ++var import_node_tty = __toESM(require("node:tty"), 1); ++function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) { ++ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; ++ const position = argv.indexOf(prefix + flag); ++ const terminatorPosition = argv.indexOf("--"); ++ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); ++} ++var { env } = import_node_process.default; ++var flagForceColor; ++if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { ++ flagForceColor = 0; ++} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { ++ flagForceColor = 1; ++} ++function envForceColor() { ++ if ("FORCE_COLOR" in env) { ++ if (env.FORCE_COLOR === "true") { ++ return 1; ++ } ++ if (env.FORCE_COLOR === "false") { ++ return 0; ++ } ++ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); ++ } ++} ++function translateLevel(level) { ++ if (level === 0) { ++ return false; ++ } ++ return { ++ level, ++ hasBasic: true, ++ has256: level >= 2, ++ has16m: level >= 3 ++ }; ++} ++function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { ++ const noFlagForceColor = envForceColor(); ++ if (noFlagForceColor !== void 0) { ++ flagForceColor = noFlagForceColor; ++ } ++ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; ++ if (forceColor === 0) { ++ return 0; ++ } ++ if (sniffFlags) { ++ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { ++ return 3; ++ } ++ if (hasFlag("color=256")) { ++ return 2; ++ } ++ } ++ if ("TF_BUILD" in env && "AGENT_NAME" in env) { ++ return 1; ++ } ++ if (haveStream && !streamIsTTY && forceColor === void 0) { ++ return 0; ++ } ++ const min = forceColor || 0; ++ if (env.TERM === "dumb") { ++ return min; ++ } ++ if (import_node_process.default.platform === "win32") { ++ const osRelease = import_node_os.default.release().split("."); ++ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { ++ return Number(osRelease[2]) >= 14931 ? 3 : 2; ++ } ++ return 1; ++ } ++ if ("CI" in env) { ++ if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) { ++ return 3; ++ } ++ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { ++ return 1; ++ } ++ return min; ++ } ++ if ("TEAMCITY_VERSION" in env) { ++ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; ++ } ++ if (env.COLORTERM === "truecolor") { ++ return 3; ++ } ++ if (env.TERM === "xterm-kitty") { ++ return 3; ++ } ++ if ("TERM_PROGRAM" in env) { ++ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); ++ switch (env.TERM_PROGRAM) { ++ case "iTerm.app": { ++ return version >= 3 ? 3 : 2; ++ } ++ case "Apple_Terminal": { ++ return 2; ++ } ++ } ++ } ++ if (/-256(color)?$/i.test(env.TERM)) { ++ return 2; ++ } ++ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { ++ return 1; ++ } ++ if ("COLORTERM" in env) { ++ return 1; ++ } ++ return min; ++} ++function createSupportsColor(stream, options = {}) { ++ const level = _supportsColor(stream, { ++ streamIsTTY: stream && stream.isTTY, ++ ...options ++ }); ++ return translateLevel(level); ++} ++var supportsColor = { ++ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }), ++ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) }) ++}; ++var supports_color_default = supportsColor; ++ ++// src/lib/utils.ts ++var import_typescript2 = __toESM(require("typescript"), 1); ++ ++// src/lib/ts.ts ++var import_ref_utils = require("@redocly/openapi-core/lib/ref-utils.js"); ++var import_typescript = __toESM(require("typescript"), 1); ++var JS_PROPERTY_INDEX_RE = /^[A-Za-z_$][A-Za-z_$0-9]*$/; ++var JS_ENUM_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+(.)?/g; ++var JS_PROPERTY_INDEX_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+/g; ++var SPECIAL_CHARACTER_MAP = { ++ "+": "Plus" ++ // Add more mappings as needed ++}; ++var BOOLEAN = import_typescript.default.factory.createKeywordTypeNode(import_typescript.default.SyntaxKind.BooleanKeyword); ++var FALSE = import_typescript.default.factory.createLiteralTypeNode(import_typescript.default.factory.createFalse()); ++var NEVER = import_typescript.default.factory.createKeywordTypeNode(import_typescript.default.SyntaxKind.NeverKeyword); ++var NULL = import_typescript.default.factory.createLiteralTypeNode(import_typescript.default.factory.createNull()); ++var NUMBER = import_typescript.default.factory.createKeywordTypeNode(import_typescript.default.SyntaxKind.NumberKeyword); ++var QUESTION_TOKEN = import_typescript.default.factory.createToken(import_typescript.default.SyntaxKind.QuestionToken); ++var STRING = import_typescript.default.factory.createKeywordTypeNode(import_typescript.default.SyntaxKind.StringKeyword); ++var TRUE = import_typescript.default.factory.createLiteralTypeNode(import_typescript.default.factory.createTrue()); ++var UNDEFINED = import_typescript.default.factory.createKeywordTypeNode(import_typescript.default.SyntaxKind.UndefinedKeyword); ++var UNKNOWN = import_typescript.default.factory.createKeywordTypeNode(import_typescript.default.SyntaxKind.UnknownKeyword); ++var LB_RE = /\r?\n/g; ++var COMMENT_RE = /\*\//g; ++function addJSDocComment(schemaObject, node) { ++ if (!schemaObject || typeof schemaObject !== "object" || Array.isArray(schemaObject)) { ++ return; ++ } ++ const output = []; ++ if (schemaObject.title) { ++ output.push(schemaObject.title.replace(LB_RE, "\n * ")); ++ } ++ if (schemaObject.summary) { ++ output.push(schemaObject.summary.replace(LB_RE, "\n * ")); ++ } ++ if (schemaObject.format) { ++ output.push(`Format: ${schemaObject.format}`); ++ } ++ if (schemaObject.deprecated) { ++ output.push("@deprecated"); ++ } ++ const supportedJsDocTags = ["description", "default", "example"]; ++ for (const field of supportedJsDocTags) { ++ const allowEmptyString = field === "default" || field === "example"; ++ if (schemaObject[field] === void 0) { ++ continue; ++ } ++ if (schemaObject[field] === "" && !allowEmptyString) { ++ continue; ++ } ++ const serialized = typeof schemaObject[field] === "object" ? JSON.stringify(schemaObject[field], null, 2) : schemaObject[field]; ++ output.push(`@${field} ${String(serialized).replace(LB_RE, "\n * ")}`); ++ } ++ if ("const" in schemaObject) { ++ output.push("@constant"); ++ } ++ if (schemaObject.enum) { ++ let type = "unknown"; ++ if (Array.isArray(schemaObject.type)) { ++ type = schemaObject.type.join("|"); ++ } else if (typeof schemaObject.type === "string") { ++ type = schemaObject.type; ++ } ++ output.push(`@enum {${type}${schemaObject.nullable ? "|null" : ""}}`); ++ } ++ if (output.length) { ++ let text = output.length === 1 ? `* ${output.join("\n")} ` : `* ++ * ${output.join("\n * ")} ++ `; ++ text = text.replace(COMMENT_RE, "*\\/"); ++ import_typescript.default.addSyntheticLeadingComment( ++ /* node */ ++ node, ++ /* kind */ ++ import_typescript.default.SyntaxKind.MultiLineCommentTrivia, ++ // note: MultiLine just refers to a "/* */" comment ++ /* text */ ++ text, ++ /* hasTrailingNewLine */ ++ true ++ ); ++ } ++} ++function oapiRef(path) { ++ const { pointer } = (0, import_ref_utils.parseRef)(path); ++ if (pointer.length === 0) { ++ throw new Error(`Error parsing $ref: ${path}. Is this a valid $ref?`); ++ } ++ let t = import_typescript.default.factory.createTypeReferenceNode( ++ import_typescript.default.factory.createIdentifier(String(pointer[0])) ++ ); ++ if (pointer.length > 1) { ++ for (let i = 1; i < pointer.length; i++) { ++ if (i > 2 && i < pointer.length - 1 && pointer[i] === "properties") { ++ continue; ++ } ++ t = import_typescript.default.factory.createIndexedAccessTypeNode( ++ t, ++ import_typescript.default.factory.createLiteralTypeNode( ++ typeof pointer[i] === "number" ? import_typescript.default.factory.createNumericLiteral(pointer[i]) : import_typescript.default.factory.createStringLiteral(pointer[i]) ++ ) ++ ); ++ } ++ } ++ return t; ++} ++function astToString(ast, options) { ++ var _a, _b; ++ const sourceFile = import_typescript.default.createSourceFile( ++ (_a = options == null ? void 0 : options.fileName) != null ? _a : "openapi-ts.ts", ++ (_b = options == null ? void 0 : options.sourceText) != null ? _b : "", ++ import_typescript.default.ScriptTarget.ESNext, ++ false, ++ import_typescript.default.ScriptKind.TS ++ ); ++ sourceFile.statements = import_typescript.default.factory.createNodeArray(Array.isArray(ast) ? ast : [ast]); ++ const printer = import_typescript.default.createPrinter({ ++ newLine: import_typescript.default.NewLineKind.LineFeed, ++ removeComments: false, ++ ...options == null ? void 0 : options.formatOptions ++ }); ++ return printer.printFile(sourceFile); ++} ++function stringToAST(source) { ++ return import_typescript.default.createSourceFile( ++ /* fileName */ ++ "stringInput", ++ /* sourceText */ ++ source, ++ /* languageVersion */ ++ import_typescript.default.ScriptTarget.ESNext, ++ /* setParentNodes */ ++ void 0, ++ /* scriptKind */ ++ void 0 ++ ).statements; ++} ++function tsDedupe(types) { ++ var _a, _b; ++ const encounteredTypes = /* @__PURE__ */ new Set(); ++ const filteredTypes = []; ++ for (const t of types) { ++ if (!("text" in ((_a = t.literal) != null ? _a : t))) { ++ const { kind } = (_b = t.literal) != null ? _b : t; ++ if (encounteredTypes.has(kind)) { ++ continue; ++ } ++ if (tsIsPrimitive(t)) { ++ encounteredTypes.add(kind); ++ } ++ } ++ filteredTypes.push(t); ++ } ++ return filteredTypes; ++} ++var enumCache = /* @__PURE__ */ new Map(); ++function tsEnum(name, members, metadata, options) { ++ var _a; ++ let enumName = sanitizeMemberName(name); ++ enumName = `${enumName[0].toUpperCase()}${enumName.substring(1)}`; ++ let key = ""; ++ if (options == null ? void 0 : options.shouldCache) { ++ key = `${members.slice(0).sort().map((v, i) => { ++ var _a2, _b, _c; ++ return `${(_b = (_a2 = metadata == null ? void 0 : metadata[i]) == null ? void 0 : _a2.name) != null ? _b : String(v)}:${((_c = metadata == null ? void 0 : metadata[i]) == null ? void 0 : _c.description) || ""}`; ++ }).join(",")}`; ++ if (enumCache.has(key)) { ++ return enumCache.get(key); ++ } ++ } ++ const enumDeclaration = import_typescript.default.factory.createEnumDeclaration( ++ /* modifiers */ ++ options ? tsModifiers({ export: (_a = options.export) != null ? _a : false }) : void 0, ++ /* name */ ++ enumName, ++ /* members */ ++ members.map((value, i) => tsEnumMember(value, metadata == null ? void 0 : metadata[i])) ++ ); ++ (options == null ? void 0 : options.shouldCache) && enumCache.set(key, enumDeclaration); ++ return enumDeclaration; ++} ++function tsArrayLiteralExpression(name, elementType, values, options) { ++ var _a; ++ let variableName = sanitizeMemberName(name); ++ variableName = `${variableName[0].toLowerCase()}${variableName.substring(1)}`; ++ const arrayType = (options == null ? void 0 : options.readonly) ? tsReadonlyArray(elementType, options.injectFooter) : import_typescript.default.factory.createArrayTypeNode(elementType); ++ return import_typescript.default.factory.createVariableStatement( ++ options ? tsModifiers({ export: (_a = options.export) != null ? _a : false }) : void 0, ++ import_typescript.default.factory.createVariableDeclarationList( ++ [ ++ import_typescript.default.factory.createVariableDeclaration( ++ variableName, ++ void 0, ++ arrayType, ++ import_typescript.default.factory.createArrayLiteralExpression( ++ values.map((value) => { ++ if (typeof value === "number") { ++ if (value < 0) { ++ return import_typescript.default.factory.createPrefixUnaryExpression( ++ import_typescript.default.SyntaxKind.MinusToken, ++ import_typescript.default.factory.createNumericLiteral(Math.abs(value)) ++ ); ++ } else { ++ return import_typescript.default.factory.createNumericLiteral(value); ++ } ++ } else { ++ return import_typescript.default.factory.createStringLiteral(value); ++ } ++ }) ++ ) ++ ) ++ ], ++ import_typescript.default.NodeFlags.Const ++ ) ++ ); ++} ++function sanitizeMemberName(name) { ++ let sanitizedName = name.replace(JS_ENUM_INVALID_CHARS_RE, (c2) => { ++ const last = c2[c2.length - 1]; ++ return JS_PROPERTY_INDEX_INVALID_CHARS_RE.test(last) ? "" : last.toUpperCase(); ++ }); ++ if (Number(name[0]) >= 0) { ++ sanitizedName = `Value${name}`; ++ } ++ return sanitizedName; ++} ++function tsEnumMember(value, metadata = {}) { ++ var _a; ++ let name = (_a = metadata.name) != null ? _a : String(value); ++ if (!JS_PROPERTY_INDEX_RE.test(name)) { ++ if (Number(name[0]) >= 0) { ++ name = `Value${name}`.replace(".", "_"); ++ } else if (name[0] === "-") { ++ name = `ValueMinus${name.slice(1)}`; ++ } ++ const invalidCharMatch = name.match(JS_PROPERTY_INDEX_INVALID_CHARS_RE); ++ if (invalidCharMatch) { ++ if (invalidCharMatch[0] === name) { ++ name = `"${name}"`; ++ } else { ++ name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, (s) => { ++ return s in SPECIAL_CHARACTER_MAP ? SPECIAL_CHARACTER_MAP[s] : "_"; ++ }); ++ } ++ } ++ } ++ let member; ++ if (typeof value === "number") { ++ const literal = value < 0 ? import_typescript.default.factory.createPrefixUnaryExpression( ++ import_typescript.default.SyntaxKind.MinusToken, ++ import_typescript.default.factory.createNumericLiteral(Math.abs(value)) ++ ) : import_typescript.default.factory.createNumericLiteral(value); ++ member = import_typescript.default.factory.createEnumMember(name, literal); ++ } else { ++ member = import_typescript.default.factory.createEnumMember(name, import_typescript.default.factory.createStringLiteral(value)); ++ } ++ if (metadata.description === void 0) { ++ return member; ++ } ++ return import_typescript.default.addSyntheticLeadingComment( ++ member, ++ import_typescript.default.SyntaxKind.SingleLineCommentTrivia, ++ " ".concat(metadata.description.trim()), ++ true ++ ); ++} ++function tsIntersection(types) { ++ if (types.length === 0) { ++ return NEVER; ++ } ++ if (types.length === 1) { ++ return types[0]; ++ } ++ return import_typescript.default.factory.createIntersectionTypeNode(tsDedupe(types)); ++} ++function tsIsPrimitive(type) { ++ if (!type) { ++ return true; ++ } ++ return import_typescript.default.SyntaxKind[type.kind] === "BooleanKeyword" || import_typescript.default.SyntaxKind[type.kind] === "NeverKeyword" || import_typescript.default.SyntaxKind[type.kind] === "NullKeyword" || import_typescript.default.SyntaxKind[type.kind] === "NumberKeyword" || import_typescript.default.SyntaxKind[type.kind] === "StringKeyword" || import_typescript.default.SyntaxKind[type.kind] === "UndefinedKeyword" || "literal" in type && tsIsPrimitive(type.literal); ++} ++function tsLiteral(value) { ++ if (typeof value === "string") { ++ return import_typescript.default.factory.createIdentifier(JSON.stringify(value)); ++ } ++ if (typeof value === "number") { ++ const literal = value < 0 ? import_typescript.default.factory.createPrefixUnaryExpression( ++ import_typescript.default.SyntaxKind.MinusToken, ++ import_typescript.default.factory.createNumericLiteral(Math.abs(value)) ++ ) : import_typescript.default.factory.createNumericLiteral(value); ++ return import_typescript.default.factory.createLiteralTypeNode(literal); ++ } ++ if (typeof value === "boolean") { ++ return value === true ? TRUE : FALSE; ++ } ++ if (value === null) { ++ return NULL; ++ } ++ if (Array.isArray(value)) { ++ if (value.length === 0) { ++ return import_typescript.default.factory.createArrayTypeNode(NEVER); ++ } ++ return import_typescript.default.factory.createTupleTypeNode(value.map((v) => tsLiteral(v))); ++ } ++ if (typeof value === "object") { ++ const keys = []; ++ for (const [k, v] of Object.entries(value)) { ++ keys.push( ++ import_typescript.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex(k), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ tsLiteral(v) ++ ) ++ ); ++ } ++ return keys.length ? import_typescript.default.factory.createTypeLiteralNode(keys) : tsRecord(STRING, NEVER); ++ } ++ return UNKNOWN; ++} ++function tsModifiers(modifiers) { ++ const typeMods = []; ++ if (modifiers.export) { ++ typeMods.push(import_typescript.default.factory.createModifier(import_typescript.default.SyntaxKind.ExportKeyword)); ++ } ++ if (modifiers.readonly) { ++ typeMods.push(import_typescript.default.factory.createModifier(import_typescript.default.SyntaxKind.ReadonlyKeyword)); ++ } ++ return typeMods; ++} ++function tsNullable(types) { ++ return import_typescript.default.factory.createUnionTypeNode([...types, NULL]); ++} ++function tsOmit(type, keys) { ++ return import_typescript.default.factory.createTypeReferenceNode(import_typescript.default.factory.createIdentifier("Omit"), [ ++ type, ++ import_typescript.default.factory.createUnionTypeNode(keys.map((k) => tsLiteral(k))) ++ ]); ++} ++function tsRecord(key, value) { ++ return import_typescript.default.factory.createTypeReferenceNode(import_typescript.default.factory.createIdentifier("Record"), [key, value]); ++} ++function tsPropertyIndex(index) { ++ if (typeof index === "number" && !(index < 0) || typeof index === "string" && String(Number(index)) === index && index[0] !== "-") { ++ return import_typescript.default.factory.createNumericLiteral(index); ++ } ++ return typeof index === "string" && JS_PROPERTY_INDEX_RE.test(index) ? import_typescript.default.factory.createIdentifier(index) : import_typescript.default.factory.createStringLiteral(String(index)); ++} ++function tsUnion(types) { ++ if (types.length === 0) { ++ return NEVER; ++ } ++ if (types.length === 1) { ++ return types[0]; ++ } ++ return import_typescript.default.factory.createUnionTypeNode(tsDedupe(types)); ++} ++function tsWithRequired(type, keys, injectFooter) { ++ if (keys.length === 0) { ++ return type; ++ } ++ if (!injectFooter.some((node) => { ++ var _a; ++ return import_typescript.default.isTypeAliasDeclaration(node) && ((_a = node == null ? void 0 : node.name) == null ? void 0 : _a.escapedText) === "WithRequired"; ++ })) { ++ const helper = stringToAST("type WithRequired = T & { [P in K]-?: T[P] };")[0]; ++ injectFooter.push(helper); ++ } ++ return import_typescript.default.factory.createTypeReferenceNode(import_typescript.default.factory.createIdentifier("WithRequired"), [ ++ type, ++ tsUnion(keys.map((k) => tsLiteral(k))) ++ ]); ++} ++function tsReadonlyArray(type, injectFooter) { ++ if (injectFooter && !injectFooter.some((node) => { ++ var _a; ++ return import_typescript.default.isTypeAliasDeclaration(node) && ((_a = node == null ? void 0 : node.name) == null ? void 0 : _a.escapedText) === "ReadonlyArray"; ++ })) { ++ const helper = stringToAST( ++ "type ReadonlyArray = [Exclude] extends [any[]] ? Readonly> : Readonly[]>;" ++ )[0]; ++ injectFooter.push(helper); ++ } ++ return import_typescript.default.factory.createTypeReferenceNode(import_typescript.default.factory.createIdentifier("ReadonlyArray"), [type]); ++} ++ ++// src/lib/utils.ts ++if (!supports_color_default.stdout || supports_color_default.stdout.hasBasic === false) { ++ import_ansi_colors.default.enabled = false; ++} ++var DEBUG_GROUPS = { ++ redoc: import_ansi_colors.default.cyanBright, ++ lint: import_ansi_colors.default.yellowBright, ++ bundle: import_ansi_colors.default.magentaBright, ++ ts: import_ansi_colors.default.blueBright ++}; ++function createDiscriminatorProperty(discriminator, { path, readonly = false }) { ++ let value = (0, import_ref_utils2.parseRef)(path).pointer.pop(); ++ if (discriminator.mapping) { ++ const matchedValue = Object.entries(discriminator.mapping).find( ++ ([, v]) => !v.startsWith("#") && v === value || v.startsWith("#") && (0, import_ref_utils2.parseRef)(v).pointer.pop() === value ++ ); ++ if (matchedValue) { ++ value = matchedValue[0]; ++ } ++ } ++ return import_typescript2.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ ++ readonly ++ }), ++ /* name */ ++ tsPropertyIndex(discriminator.propertyName), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ tsLiteral(value) ++ ); ++} ++function createRef(parts) { ++ let pointer = "#"; ++ for (const part of parts) { ++ if (part === void 0 || part === null || part === "") { ++ continue; ++ } ++ const maybeRef = (0, import_ref_utils2.parseRef)(String(part)).pointer; ++ if (maybeRef.length) { ++ for (const refPart of maybeRef) { ++ pointer += `/${(0, import_ref_utils2.escapePointer)(refPart)}`; ++ } ++ } else { ++ pointer += `/${(0, import_ref_utils2.escapePointer)(part)}`; ++ } ++ } ++ return pointer; ++} ++function debug(msg, group, time) { ++ if (process.env.DEBUG && (!group || process.env.DEBUG === "*" || process.env.DEBUG === "openapi-ts:*" || process.env.DEBUG.toLocaleLowerCase() === `openapi-ts:${group.toLocaleLowerCase()}`)) { ++ const groupColor = group && DEBUG_GROUPS[group] || import_ansi_colors.default.whiteBright; ++ const groupName = groupColor(`openapi-ts:${group != null ? group : "info"}`); ++ let timeFormatted = ""; ++ if (typeof time === "number") { ++ timeFormatted = import_ansi_colors.default.green(` ${formatTime(time)} `); ++ } ++ console.debug(` ${import_ansi_colors.default.bold(groupName)}${timeFormatted}${msg}`); ++ } ++} ++function error(msg) { ++ console.error(import_ansi_colors.default.red(` \u2718 ${msg}`)); ++} ++function formatTime(t) { ++ if (typeof t === "number") { ++ if (t < 1e3) { ++ return `${Math.round(10 * t) / 10}ms`; ++ } ++ if (t < 6e4) { ++ return `${Math.round(t / 100) / 10}s`; ++ } ++ return `${Math.round(t / 6e3) / 10}m`; ++ } ++ return t; ++} ++function getEntries(obj, options) { ++ let entries = Object.entries(obj); ++ if (options == null ? void 0 : options.alphabetize) { ++ entries.sort(([a], [b]) => a.localeCompare(b, "en-us", { numeric: true })); ++ } ++ if (options == null ? void 0 : options.excludeDeprecated) { ++ entries = entries.filter(([, v]) => !(v && typeof v === "object" && "deprecated" in v && v.deprecated)); ++ } ++ return entries; ++} ++function resolveRef(schema, $ref, { silent = false, visited = [] }) { ++ const { pointer } = (0, import_ref_utils2.parseRef)($ref); ++ if (!pointer.length) { ++ return void 0; ++ } ++ let node = schema; ++ for (const key of pointer) { ++ if (node && typeof node === "object" && node[key]) { ++ node = node[key]; ++ } else { ++ warn(`Could not resolve $ref "${$ref}"`, silent); ++ return void 0; ++ } ++ } ++ if (node && typeof node === "object" && node.$ref) { ++ if (visited.includes(node.$ref)) { ++ warn(`Could not resolve circular $ref "${$ref}"`, silent); ++ return void 0; ++ } ++ return resolveRef(schema, node.$ref, { ++ silent, ++ visited: [...visited, node.$ref] ++ }); ++ } ++ return node; ++} ++function createDiscriminatorEnum(values, prevSchema) { ++ return { ++ type: "string", ++ enum: values, ++ description: (prevSchema == null ? void 0 : prevSchema.description) ? `${prevSchema.description} (enum property replaced by openapi-typescript)` : "discriminator enum property added by openapi-typescript" ++ }; ++} ++function patchDiscriminatorEnum(schema, ref, values, discriminator, discriminatorRef, options) { ++ var _a; ++ const resolvedSchema = resolveRef(schema, ref, { ++ silent: (_a = options.silent) != null ? _a : false ++ }); ++ if (resolvedSchema == null ? void 0 : resolvedSchema.allOf) { ++ resolvedSchema.allOf.push({ ++ type: "object", ++ // discriminator enum properties always need to be required ++ required: [discriminator.propertyName], ++ properties: { ++ [discriminator.propertyName]: createDiscriminatorEnum(values) ++ } ++ }); ++ return true; ++ } else if (typeof resolvedSchema === "object" && "type" in resolvedSchema && resolvedSchema.type === "object") { ++ if (!resolvedSchema.properties) { ++ resolvedSchema.properties = {}; ++ } ++ if (!resolvedSchema.required) { ++ resolvedSchema.required = [discriminator.propertyName]; ++ } else if (!resolvedSchema.required.includes(discriminator.propertyName)) { ++ resolvedSchema.required.push(discriminator.propertyName); ++ } ++ resolvedSchema.properties[discriminator.propertyName] = createDiscriminatorEnum( ++ values, ++ resolvedSchema.properties[discriminator.propertyName] ++ ); ++ return true; ++ } ++ warn( ++ `Discriminator mapping has an invalid schema (neither an object schema nor an allOf array): ${ref} => ${values.join( ++ ", " ++ )} (Discriminator: ${discriminatorRef})`, ++ options.silent ++ ); ++ return false; ++} ++function scanDiscriminators(schema, options) { ++ const objects = {}; ++ const refsHandled = []; ++ walk(schema, (obj, path) => { ++ var _a, _b; ++ const discriminator = obj == null ? void 0 : obj.discriminator; ++ if (!(discriminator == null ? void 0 : discriminator.propertyName)) { ++ return; ++ } ++ const ref = createRef(path); ++ objects[ref] = discriminator; ++ if (!(obj == null ? void 0 : obj.oneOf) || !Array.isArray(obj.oneOf)) { ++ return; ++ } ++ const oneOf = obj.oneOf; ++ const mapping = {}; ++ for (const item of oneOf) { ++ if ("$ref" in item) { ++ const value = item.$ref.split("/").pop(); ++ if (value) { ++ if (!mapping[item.$ref]) { ++ mapping[item.$ref] = { inferred: value }; ++ } else { ++ mapping[item.$ref].inferred = value; ++ } ++ } ++ } ++ } ++ if (discriminator.mapping) { ++ for (const mappedValue in discriminator.mapping) { ++ const mappedRef = discriminator.mapping[mappedValue]; ++ if (!mappedRef) { ++ continue; ++ } ++ if (!((_a = mapping[mappedRef]) == null ? void 0 : _a.defined)) { ++ mapping[mappedRef] = { defined: [] }; ++ } ++ (_b = mapping[mappedRef].defined) == null ? void 0 : _b.push(mappedValue); ++ } ++ } ++ for (const [mappedRef, { inferred, defined }] of Object.entries(mapping)) { ++ if (refsHandled.includes(mappedRef)) { ++ continue; ++ } ++ if (!inferred && !defined) { ++ continue; ++ } ++ const mappedValues = defined != null ? defined : [inferred]; ++ if (patchDiscriminatorEnum(schema, mappedRef, mappedValues, discriminator, ref, options)) { ++ refsHandled.push(mappedRef); ++ } ++ } ++ }); ++ walk(schema, (obj, path) => { ++ var _a; ++ if (!obj || !Array.isArray(obj.allOf)) { ++ return; ++ } ++ for (const item of obj.allOf) { ++ if ("$ref" in item) { ++ if (!objects[item.$ref]) { ++ return; ++ } ++ const ref = createRef(path); ++ const discriminator = objects[item.$ref]; ++ const mappedValues = []; ++ if (discriminator.mapping) { ++ for (const mappedValue in discriminator.mapping) { ++ if (discriminator.mapping[mappedValue] === ref) { ++ mappedValues.push(mappedValue); ++ } ++ } ++ if (mappedValues.length > 0) { ++ if (patchDiscriminatorEnum( ++ schema, ++ ref, ++ mappedValues, ++ discriminator, ++ item.$ref, ++ options ++ )) { ++ refsHandled.push(ref); ++ } ++ } ++ } ++ objects[ref] = { ++ ...objects[item.$ref] ++ }; ++ } else if ((_a = item.discriminator) == null ? void 0 : _a.propertyName) { ++ objects[createRef(path)] = { ...item.discriminator }; ++ } ++ } ++ }); ++ return { objects, refsHandled }; ++} ++function walk(obj, cb, path = []) { ++ if (!obj || typeof obj !== "object") { ++ return; ++ } ++ if (Array.isArray(obj)) { ++ for (let i = 0; i < obj.length; i++) { ++ walk(obj[i], cb, path.concat(i)); ++ } ++ return; ++ } ++ cb(obj, path); ++ for (const k of Object.keys(obj)) { ++ walk(obj[k], cb, path.concat(k)); ++ } ++} ++function warn(msg, silent = false) { ++ if (!silent) { ++ console.warn(import_ansi_colors.default.yellow(` \u26A0 ${msg}`)); ++ } ++} ++ ++// src/lib/redoc.ts ++async function parseSchema(schema, { absoluteRef, resolver }) { ++ if (!schema) { ++ throw new Error("Can\u2019t parse empty schema"); ++ } ++ if (schema instanceof URL) { ++ const result = await resolver.resolveDocument(null, absoluteRef, true); ++ if ("parsed" in result) { ++ return result; ++ } ++ throw result.originalError; ++ } ++ if (schema instanceof import_node_stream.Readable) { ++ const contents = await new Promise((resolve) => { ++ schema.resume(); ++ schema.setEncoding("utf8"); ++ let content = ""; ++ schema.on("data", (chunk) => { ++ content += chunk; ++ }); ++ schema.on("end", () => { ++ resolve(content.trim()); ++ }); ++ }); ++ return parseSchema(contents, { absoluteRef, resolver }); ++ } ++ if (schema instanceof Buffer) { ++ return parseSchema(schema.toString("utf8"), { absoluteRef, resolver }); ++ } ++ if (typeof schema === "string") { ++ if (schema.startsWith("http://") || schema.startsWith("https://") || schema.startsWith("file://")) { ++ const url = new URL(schema); ++ return parseSchema(url, { ++ absoluteRef: url.protocol === "file:" ? (0, import_node_url.fileURLToPath)(url) : url.href, ++ resolver ++ }); ++ } ++ if (schema[0] === "{") { ++ return { ++ source: new import_openapi_core.Source(absoluteRef, schema, "application/json"), ++ parsed: parseJson(schema) ++ }; ++ } ++ return (0, import_openapi_core.makeDocumentFromString)(schema, absoluteRef); ++ } ++ if (typeof schema === "object" && !Array.isArray(schema)) { ++ return { ++ source: new import_openapi_core.Source(absoluteRef, JSON.stringify(schema), "application/json"), ++ parsed: schema ++ }; ++ } ++ throw new Error(`Expected string, object, or Buffer. Got ${Array.isArray(schema) ? "Array" : typeof schema}`); ++} ++function _processProblems(problems, options) { ++ var _a; ++ if (problems.length) { ++ let errorMessage = void 0; ++ for (const problem of problems) { ++ const problemLocation = (_a = problem.location) == null ? void 0 : _a[0].pointer; ++ const problemMessage = problemLocation ? `${problem.message} at ${problemLocation}` : problem.message; ++ if (problem.severity === "error") { ++ errorMessage = problemMessage; ++ error(problemMessage); ++ } else { ++ warn(problemMessage, options.silent); ++ } ++ } ++ if (errorMessage) { ++ throw new Error(errorMessage); ++ } ++ } ++} ++async function validateAndBundle(source, options) { ++ var _a; ++ const redocConfigT = import_node_perf_hooks.performance.now(); ++ debug("Loaded Redoc config", "redoc", import_node_perf_hooks.performance.now() - redocConfigT); ++ const redocParseT = import_node_perf_hooks.performance.now(); ++ let absoluteRef = (0, import_node_url.fileURLToPath)(new URL((_a = options == null ? void 0 : options.cwd) != null ? _a : `file://${process.cwd()}/`)); ++ if (source instanceof URL) { ++ absoluteRef = source.protocol === "file:" ? (0, import_node_url.fileURLToPath)(source) : source.href; ++ } ++ const resolver = new import_openapi_core.BaseResolver(options.redoc.resolve); ++ const document = await parseSchema(source, { ++ absoluteRef, ++ resolver ++ }); ++ debug("Parsed schema", "redoc", import_node_perf_hooks.performance.now() - redocParseT); ++ const openapiVersion = Number.parseFloat(document.parsed.openapi); ++ if (document.parsed.swagger || !document.parsed.openapi || Number.isNaN(openapiVersion) || openapiVersion < 3 || openapiVersion >= 4) { ++ if (document.parsed.swagger) { ++ throw new Error("Unsupported Swagger version: 2.x. Use OpenAPI 3.x instead."); ++ } ++ if (document.parsed.openapi || openapiVersion < 3 || openapiVersion >= 4) { ++ throw new Error(`Unsupported OpenAPI version: ${document.parsed.openapi}`); ++ } ++ throw new Error("Unsupported schema format, expected `openapi: 3.x`"); ++ } ++ const redocLintT = import_node_perf_hooks.performance.now(); ++ const problems = await (0, import_openapi_core.lintDocument)({ ++ document, ++ config: options.redoc.styleguide, ++ externalRefResolver: resolver ++ }); ++ _processProblems(problems, options); ++ debug("Linted schema", "lint", import_node_perf_hooks.performance.now() - redocLintT); ++ const redocBundleT = import_node_perf_hooks.performance.now(); ++ const bundled = await (0, import_openapi_core.bundle)({ ++ config: options.redoc, ++ dereference: false, ++ doc: document ++ }); ++ _processProblems(bundled.problems, options); ++ debug("Bundled schema", "bundle", import_node_perf_hooks.performance.now() - redocBundleT); ++ return bundled.bundle.parsed; ++} ++ ++// src/transform/index.ts ++var import_typescript14 = __toESM(require("typescript"), 1); ++var import_node_perf_hooks4 = require("node:perf_hooks"); ++ ++// src/transform/components-object.ts ++var import_typescript11 = __toESM(require("typescript"), 1); ++ ++// ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js ++var SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu; ++var SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu; ++var SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u; ++var DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu; ++var SPLIT_REPLACE_VALUE = "$1\0$2"; ++var DEFAULT_PREFIX_SUFFIX_CHARACTERS = ""; ++function split(value) { ++ let result = value.trim(); ++ result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE); ++ result = result.replace(DEFAULT_STRIP_REGEXP, "\0"); ++ let start = 0; ++ let end = result.length; ++ while (result.charAt(start) === "\0") ++ start++; ++ if (start === end) ++ return []; ++ while (result.charAt(end - 1) === "\0") ++ end--; ++ return result.slice(start, end).split(/\0/g); ++} ++function splitSeparateNumbers(value) { ++ var _a; ++ const words = split(value); ++ for (let i = 0; i < words.length; i++) { ++ const word = words[i]; ++ const match = SPLIT_SEPARATE_NUMBER_RE.exec(word); ++ if (match) { ++ const offset = match.index + ((_a = match[1]) != null ? _a : match[2]).length; ++ words.splice(i, 1, word.slice(0, offset), word.slice(offset)); ++ } ++ } ++ return words; ++} ++function pascalCase(input, options) { ++ var _a; ++ const [prefix, words, suffix] = splitPrefixSuffix(input, options); ++ const lower = lowerFactory(options == null ? void 0 : options.locale); ++ const upper = upperFactory(options == null ? void 0 : options.locale); ++ const transform = (options == null ? void 0 : options.mergeAmbiguousCharacters) ? capitalCaseTransformFactory(lower, upper) : pascalCaseTransformFactory(lower, upper); ++ return prefix + words.map(transform).join((_a = options == null ? void 0 : options.delimiter) != null ? _a : "") + suffix; ++} ++function lowerFactory(locale) { ++ return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale); ++} ++function upperFactory(locale) { ++ return locale === false ? (input) => input.toUpperCase() : (input) => input.toLocaleUpperCase(locale); ++} ++function capitalCaseTransformFactory(lower, upper) { ++ return (word) => `${upper(word[0])}${lower(word.slice(1))}`; ++} ++function pascalCaseTransformFactory(lower, upper) { ++ return (word, index) => { ++ const char0 = word[0]; ++ const initial = index > 0 && char0 >= "0" && char0 <= "9" ? "_" + char0 : upper(char0); ++ return initial + lower(word.slice(1)); ++ }; ++} ++function splitPrefixSuffix(input, options = {}) { ++ var _a, _b, _c; ++ const splitFn = (_a = options.split) != null ? _a : options.separateNumbers ? splitSeparateNumbers : split; ++ const prefixCharacters = (_b = options.prefixCharacters) != null ? _b : DEFAULT_PREFIX_SUFFIX_CHARACTERS; ++ const suffixCharacters = (_c = options.suffixCharacters) != null ? _c : DEFAULT_PREFIX_SUFFIX_CHARACTERS; ++ let prefixIndex = 0; ++ let suffixIndex = input.length; ++ while (prefixIndex < input.length) { ++ const char = input.charAt(prefixIndex); ++ if (!prefixCharacters.includes(char)) ++ break; ++ prefixIndex++; ++ } ++ while (suffixIndex > prefixIndex) { ++ const index = suffixIndex - 1; ++ const char = input.charAt(index); ++ if (!suffixCharacters.includes(char)) ++ break; ++ suffixIndex = index; ++ } ++ return [ ++ input.slice(0, prefixIndex), ++ splitFn(input.slice(prefixIndex, suffixIndex)), ++ input.slice(suffixIndex) ++ ]; ++} ++ ++// src/transform/components-object.ts ++var import_node_perf_hooks2 = require("node:perf_hooks"); ++ ++// src/transform/header-object.ts ++var import_ref_utils4 = require("@redocly/openapi-core/lib/ref-utils.js"); ++var import_typescript4 = __toESM(require("typescript"), 1); ++ ++// src/transform/schema-object.ts ++var import_ref_utils3 = require("@redocly/openapi-core/lib/ref-utils.js"); ++var import_typescript3 = __toESM(require("typescript"), 1); ++function transformSchemaObject(schemaObject, options) { ++ const type = transformSchemaObjectWithComposition(schemaObject, options); ++ if (typeof options.ctx.postTransform === "function") { ++ const postTransformResult = options.ctx.postTransform(type, options); ++ if (postTransformResult) { ++ return postTransformResult; ++ } ++ } ++ return type; ++} ++function transformSchemaObjectWithComposition(schemaObject, options) { ++ var _a, _b, _c, _d, _e; ++ if (!schemaObject) { ++ return NEVER; ++ } ++ if (schemaObject === true) { ++ return UNKNOWN; ++ } ++ if (Array.isArray(schemaObject) || typeof schemaObject !== "object") { ++ throw new Error( ++ `Expected SchemaObject, received ${Array.isArray(schemaObject) ? "Array" : typeof schemaObject} at ${options.path}` ++ ); ++ } ++ if ("$ref" in schemaObject) { ++ return oapiRef(schemaObject.$ref); ++ } ++ if (schemaObject.const !== null && schemaObject.const !== void 0) { ++ return tsLiteral(schemaObject.const); ++ } ++ if (Array.isArray(schemaObject.enum) && (!("type" in schemaObject) || schemaObject.type !== "object") && !("properties" in schemaObject) && !("additionalProperties" in schemaObject)) { ++ if (options.ctx.enum && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number" || v === null)) { ++ let enumName = (0, import_ref_utils3.parseRef)((_a = options.path) != null ? _a : "").pointer.join("/"); ++ enumName = enumName.replace("components/schemas", ""); ++ const metadata = schemaObject.enum.map((_, i) => { ++ var _a2, _b2, _c2, _d2, _e2, _f; ++ return { ++ name: (_c2 = (_a2 = schemaObject["x-enum-varnames"]) == null ? void 0 : _a2[i]) != null ? _c2 : (_b2 = schemaObject["x-enumNames"]) == null ? void 0 : _b2[i], ++ description: (_f = (_d2 = schemaObject["x-enum-descriptions"]) == null ? void 0 : _d2[i]) != null ? _f : (_e2 = schemaObject["x-enumDescriptions"]) == null ? void 0 : _e2[i] ++ }; ++ }); ++ let hasNull = false; ++ const validSchemaEnums = schemaObject.enum.filter((enumValue) => { ++ if (enumValue === null) { ++ hasNull = true; ++ return false; ++ } ++ return true; ++ }); ++ const enumType2 = tsEnum(enumName, validSchemaEnums, metadata, { ++ shouldCache: options.ctx.dedupeEnums, ++ export: true ++ // readonly: TS enum do not support the readonly modifier ++ }); ++ if (!options.ctx.injectFooter.includes(enumType2)) { ++ options.ctx.injectFooter.push(enumType2); ++ } ++ const ref = import_typescript3.default.factory.createTypeReferenceNode(enumType2.name); ++ return hasNull ? tsUnion([ref, NULL]) : ref; ++ } ++ const enumType = schemaObject.enum.map(tsLiteral); ++ if ((Array.isArray(schemaObject.type) && schemaObject.type.includes("null") || schemaObject.nullable) && !schemaObject.default) { ++ enumType.push(NULL); ++ } ++ const unionType = tsUnion(enumType); ++ if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { ++ let enumValuesVariableName = (0, import_ref_utils3.parseRef)((_b = options.path) != null ? _b : "").pointer.join("/"); ++ enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); ++ enumValuesVariableName = `${enumValuesVariableName}Values`; ++ const enumValuesArray = tsArrayLiteralExpression( ++ enumValuesVariableName, ++ oapiRef((_c = options.path) != null ? _c : ""), ++ schemaObject.enum, ++ { ++ export: true, ++ readonly: true, ++ injectFooter: options.ctx.injectFooter ++ } ++ ); ++ options.ctx.injectFooter.push(enumValuesArray); ++ } ++ return unionType; ++ } ++ function collectUnionCompositions(items) { ++ const output = []; ++ for (const item of items) { ++ output.push(transformSchemaObject(item, options)); ++ } ++ return output; ++ } ++ function collectAllOfCompositions(items, required) { ++ const output = []; ++ for (const item of items) { ++ let itemType; ++ if ("$ref" in item) { ++ itemType = transformSchemaObject(item, options); ++ const resolved = options.ctx.resolve(item.$ref); ++ if (resolved && typeof resolved === "object" && "properties" in resolved && // we have already handled this item (discriminator property was already added as required) ++ !options.ctx.discriminators.refsHandled.includes(item.$ref)) { ++ const validRequired = (required != null ? required : []).filter((key) => { ++ var _a2; ++ return !!((_a2 = resolved.properties) == null ? void 0 : _a2[key]); ++ }); ++ if (validRequired.length) { ++ itemType = tsWithRequired(itemType, validRequired, options.ctx.injectFooter); ++ } ++ } ++ } else { ++ const itemRequired = [...required != null ? required : []]; ++ if (typeof item === "object" && Array.isArray(item.required)) { ++ itemRequired.push(...item.required); ++ } ++ itemType = transformSchemaObject({ ...item, required: itemRequired }, options); ++ } ++ output.push(itemType); ++ } ++ return output; ++ } ++ let finalType = void 0; ++ const coreObjectType = transformSchemaObjectCore(schemaObject, options); ++ const allOfType = collectAllOfCompositions((_d = schemaObject.allOf) != null ? _d : [], schemaObject.required); ++ if (coreObjectType || allOfType.length) { ++ const allOf = allOfType.length ? tsIntersection(allOfType) : void 0; ++ finalType = tsIntersection([...coreObjectType ? [coreObjectType] : [], ...allOf ? [allOf] : []]); ++ } ++ const anyOfType = collectUnionCompositions((_e = schemaObject.anyOf) != null ? _e : []); ++ if (anyOfType.length) { ++ finalType = tsUnion([...finalType ? [finalType] : [], ...anyOfType]); ++ } ++ const oneOfType = collectUnionCompositions( ++ schemaObject.oneOf || "type" in schemaObject && schemaObject.type === "object" && schemaObject.enum || [] ++ ); ++ if (oneOfType.length) { ++ if (oneOfType.every(tsIsPrimitive)) { ++ finalType = tsUnion([...finalType ? [finalType] : [], ...oneOfType]); ++ } else { ++ finalType = tsIntersection([...finalType ? [finalType] : [], tsUnion(oneOfType)]); ++ } ++ } ++ if (!finalType) { ++ if ("type" in schemaObject) { ++ finalType = tsRecord(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER); ++ } else { ++ finalType = UNKNOWN; ++ } ++ } ++ if (finalType !== UNKNOWN && schemaObject.nullable && !schemaObject.default) { ++ finalType = tsNullable([finalType]); ++ } ++ return finalType; ++} ++function transformSchemaObjectCore(schemaObject, options) { ++ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; ++ if ("type" in schemaObject && schemaObject.type) { ++ if (typeof options.ctx.transform === "function") { ++ const result = options.ctx.transform(schemaObject, options); ++ if (result && typeof result === "object") { ++ if ("schema" in result) { ++ if (result.questionToken) { ++ return import_typescript3.default.factory.createUnionTypeNode([result.schema, UNDEFINED]); ++ } else { ++ return result.schema; ++ } ++ } else { ++ return result; ++ } ++ } ++ } ++ if (schemaObject.type === "null") { ++ return NULL; ++ } ++ if (schemaObject.type === "string") { ++ return STRING; ++ } ++ if (schemaObject.type === "number" || schemaObject.type === "integer") { ++ return NUMBER; ++ } ++ if (schemaObject.type === "boolean") { ++ return BOOLEAN; ++ } ++ if (schemaObject.type === "array") { ++ let itemType = UNKNOWN; ++ if (schemaObject.prefixItems || Array.isArray(schemaObject.items)) { ++ const prefixItems = (_a = schemaObject.prefixItems) != null ? _a : schemaObject.items; ++ itemType = import_typescript3.default.factory.createTupleTypeNode(prefixItems.map((item) => transformSchemaObject(item, options))); ++ } else if (schemaObject.items) { ++ if ("type" in schemaObject.items && schemaObject.items.type === "array") { ++ itemType = import_typescript3.default.factory.createArrayTypeNode(transformSchemaObject(schemaObject.items, options)); ++ } else { ++ itemType = transformSchemaObject(schemaObject.items, options); ++ } ++ } ++ const min = typeof schemaObject.minItems === "number" && schemaObject.minItems >= 0 ? schemaObject.minItems : 0; ++ const max = typeof schemaObject.maxItems === "number" && schemaObject.maxItems >= 0 && min <= schemaObject.maxItems ? schemaObject.maxItems : void 0; ++ const estimateCodeSize = typeof max !== "number" ? min : (max * (max + 1) - min * (min - 1)) / 2; ++ if (options.ctx.arrayLength && (min !== 0 || max !== void 0) && estimateCodeSize < 30) { ++ if (min === max) { ++ const elements = []; ++ for (let i = 0; i < min; i++) { ++ elements.push(itemType); ++ } ++ return tsUnion([import_typescript3.default.factory.createTupleTypeNode(elements)]); ++ } else if (schemaObject.maxItems > 0) { ++ const members = []; ++ for (let i = 0; i <= (max != null ? max : 0) - min; i++) { ++ const elements = []; ++ for (let j = min; j < i + min; j++) { ++ elements.push(itemType); ++ } ++ members.push(import_typescript3.default.factory.createTupleTypeNode(elements)); ++ } ++ return tsUnion(members); ++ } else { ++ const elements = []; ++ for (let i = 0; i < min; i++) { ++ elements.push(itemType); ++ } ++ elements.push(import_typescript3.default.factory.createRestTypeNode(import_typescript3.default.factory.createArrayTypeNode(itemType))); ++ return import_typescript3.default.factory.createTupleTypeNode(elements); ++ } ++ } ++ const finalType = import_typescript3.default.isTupleTypeNode(itemType) || import_typescript3.default.isArrayTypeNode(itemType) ? itemType : import_typescript3.default.factory.createArrayTypeNode(itemType); ++ return options.ctx.immutable ? import_typescript3.default.factory.createTypeOperatorNode(import_typescript3.default.SyntaxKind.ReadonlyKeyword, finalType) : finalType; ++ } ++ if (Array.isArray(schemaObject.type) && !Array.isArray(schemaObject)) { ++ const uniqueTypes = []; ++ if (Array.isArray(schemaObject.oneOf)) { ++ for (const t of schemaObject.type) { ++ if ((t === "boolean" || t === "string" || t === "number" || t === "integer" || t === "null") && schemaObject.oneOf.find((o) => typeof o === "object" && "type" in o && o.type === t)) { ++ continue; ++ } ++ uniqueTypes.push( ++ t === "null" || t === null ? NULL : transformSchemaObject( ++ { ...schemaObject, type: t, oneOf: void 0 }, ++ // don’t stack oneOf transforms ++ options ++ ) ++ ); ++ } ++ } else { ++ for (const t of schemaObject.type) { ++ if (t === "null" || t === null) { ++ if (!schemaObject.default) { ++ uniqueTypes.push(NULL); ++ } ++ } else { ++ uniqueTypes.push(transformSchemaObject({ ...schemaObject, type: t }, options)); ++ } ++ } ++ } ++ return tsUnion(uniqueTypes); ++ } ++ } ++ const coreObjectType = []; ++ for (const k of ["allOf", "anyOf"]) { ++ if (!schemaObject[k]) { ++ continue; ++ } ++ const discriminator = !schemaObject.discriminator && !options.ctx.discriminators.refsHandled.includes((_b = options.path) != null ? _b : "") && options.ctx.discriminators.objects[(_c = options.path) != null ? _c : ""]; ++ if (discriminator) { ++ coreObjectType.unshift( ++ createDiscriminatorProperty(discriminator, { ++ path: (_d = options.path) != null ? _d : "", ++ readonly: options.ctx.immutable ++ }) ++ ); ++ break; ++ } ++ } ++ if ("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length || "additionalProperties" in schemaObject && schemaObject.additionalProperties || "$defs" in schemaObject && schemaObject.$defs) { ++ if (Object.keys((_e = schemaObject.properties) != null ? _e : {}).length) { ++ for (const [k, v] of getEntries((_f = schemaObject.properties) != null ? _f : {}, options.ctx)) { ++ if (typeof v !== "object" || Array.isArray(v)) { ++ throw new Error( ++ `${options.path}: invalid property ${k}. Expected Schema Object, got ${Array.isArray(v) ? "Array" : typeof v}` ++ ); ++ } ++ if (options.ctx.excludeDeprecated) { ++ const resolved = "$ref" in v ? options.ctx.resolve(v.$ref) : v; ++ if (resolved == null ? void 0 : resolved.deprecated) { ++ continue; ++ } ++ } ++ let optional = ((_g = schemaObject.required) == null ? void 0 : _g.includes(k)) || schemaObject.required === void 0 && options.ctx.propertiesRequiredByDefault || "default" in v && options.ctx.defaultNonNullable && !((_h = options.path) == null ? void 0 : _h.includes("parameters")) && !((_i = options.path) == null ? void 0 : _i.includes("requestBody")) && !((_j = options.path) == null ? void 0 : _j.includes("requestBodies")) ? void 0 : QUESTION_TOKEN; ++ let type = "$ref" in v ? oapiRef(v.$ref) : transformSchemaObject(v, { ++ ...options, ++ path: createRef([options.path, k]) ++ }); ++ if (typeof options.ctx.transform === "function") { ++ const result = options.ctx.transform(v, options); ++ if (result && typeof result === "object") { ++ if ("schema" in result) { ++ type = result.schema; ++ optional = result.questionToken ? QUESTION_TOKEN : optional; ++ } else { ++ type = result; ++ } ++ } ++ } ++ const property = import_typescript3.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ ++ readonly: options.ctx.immutable || "readOnly" in v && !!v.readOnly ++ }), ++ /* name */ ++ tsPropertyIndex(k), ++ /* questionToken */ ++ optional, ++ /* type */ ++ type ++ ); ++ addJSDocComment(v, property); ++ coreObjectType.push(property); ++ } ++ } ++ if (schemaObject.$defs && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { ++ const defKeys = []; ++ for (const [k, v] of Object.entries(schemaObject.$defs)) { ++ const property = import_typescript3.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ ++ readonly: options.ctx.immutable || "readonly" in v && !!v.readOnly ++ }), ++ /* name */ ++ tsPropertyIndex(k), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ transformSchemaObject(v, { ++ ...options, ++ path: createRef([options.path, "$defs", k]) ++ }) ++ ); ++ addJSDocComment(v, property); ++ defKeys.push(property); ++ } ++ coreObjectType.push( ++ import_typescript3.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex("$defs"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ import_typescript3.default.factory.createTypeLiteralNode(defKeys) ++ ) ++ ); ++ } ++ if (schemaObject.additionalProperties || options.ctx.additionalProperties) { ++ const hasExplicitAdditionalProperties = typeof schemaObject.additionalProperties === "object" && Object.keys(schemaObject.additionalProperties).length; ++ const addlType = hasExplicitAdditionalProperties ? transformSchemaObject(schemaObject.additionalProperties, options) : UNKNOWN; ++ return tsIntersection([ ++ ...coreObjectType.length ? [import_typescript3.default.factory.createTypeLiteralNode(coreObjectType)] : [], ++ import_typescript3.default.factory.createTypeLiteralNode([ ++ import_typescript3.default.factory.createIndexSignature( ++ /* modifiers */ ++ tsModifiers({ ++ readonly: options.ctx.immutable ++ }), ++ /* parameters */ ++ [ ++ import_typescript3.default.factory.createParameterDeclaration( ++ /* modifiers */ ++ void 0, ++ /* dotDotDotToken */ ++ void 0, ++ /* name */ ++ import_typescript3.default.factory.createIdentifier("key"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ STRING ++ ) ++ ], ++ /* type */ ++ addlType ++ ) ++ ]) ++ ]); ++ } ++ } ++ return coreObjectType.length ? import_typescript3.default.factory.createTypeLiteralNode(coreObjectType) : void 0; ++} ++ ++// src/transform/media-type-object.ts ++function transformMediaTypeObject(mediaTypeObject, options) { ++ if (!mediaTypeObject.schema) { ++ return UNKNOWN; ++ } ++ return transformSchemaObject(mediaTypeObject.schema, options); ++} ++ ++// src/transform/header-object.ts ++function transformHeaderObject(headerObject, options) { ++ var _a, _b; ++ if (headerObject.schema) { ++ return transformSchemaObject(headerObject.schema, options); ++ } ++ if (headerObject.content) { ++ const type = []; ++ for (const [contentType, mediaTypeObject] of getEntries((_a = headerObject.content) != null ? _a : {}, options.ctx)) { ++ const nextPath = `${(_b = options.path) != null ? _b : "#"}/${(0, import_ref_utils4.escapePointer)(contentType)}`; ++ const mediaType = "$ref" in mediaTypeObject ? transformSchemaObject(mediaTypeObject, { ++ ...options, ++ path: nextPath ++ }) : transformMediaTypeObject(mediaTypeObject, { ++ ...options, ++ path: nextPath ++ }); ++ const property = import_typescript4.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(contentType), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ mediaType ++ ); ++ addJSDocComment(mediaTypeObject, property); ++ type.push(property); ++ } ++ return import_typescript4.default.factory.createTypeLiteralNode(type); ++ } ++ return UNKNOWN; ++} ++ ++// src/transform/parameter-object.ts ++function transformParameterObject(parameterObject, options) { ++ return parameterObject.schema ? transformSchemaObject(parameterObject.schema, options) : STRING; ++} ++ ++// src/transform/path-item-object.ts ++var import_typescript10 = __toESM(require("typescript"), 1); ++ ++// src/transform/operation-object.ts ++var import_typescript9 = __toESM(require("typescript"), 1); ++ ++// src/transform/parameters-array.ts ++var import_typescript5 = __toESM(require("typescript"), 1); ++var PATH_PARAM_RE = /\{([^}]+)\}/g; ++function createPathParameter(paramName) { ++ return { ++ name: paramName, ++ in: "path", ++ required: true, ++ schema: { type: "string" } ++ }; ++} ++function extractPathParamsFromUrl(path) { ++ const params = []; ++ const matches = path.match(PATH_PARAM_RE); ++ if (matches) { ++ for (const match of matches) { ++ const paramName = match.slice(1, -1); ++ params.push(createPathParameter(paramName)); ++ } ++ } ++ return params; ++} ++function transformParametersArray(parametersArray, options) { ++ const type = []; ++ const workingParameters = [...parametersArray]; ++ if (options.ctx.generatePathParams && options.path) { ++ const pathString = Array.isArray(options.path) ? options.path[0] : options.path; ++ if (typeof pathString === "string") { ++ const pathParams = extractPathParamsFromUrl(pathString); ++ for (const param of pathParams) { ++ const exists = workingParameters.some((p) => { ++ const resolved = "$ref" in p ? options.ctx.resolve(p.$ref) : p; ++ return (resolved == null ? void 0 : resolved.in) === "path" && (resolved == null ? void 0 : resolved.name) === param.name; ++ }); ++ if (!exists) { ++ workingParameters.push(param); ++ } ++ } ++ } ++ } ++ const paramType = []; ++ for (const paramIn of ["query", "header", "path", "cookie"]) { ++ const paramLocType = []; ++ let operationParameters = workingParameters.map((param) => ({ ++ original: param, ++ resolved: "$ref" in param ? options.ctx.resolve(param.$ref) : param ++ })); ++ if (options.ctx.alphabetize) { ++ operationParameters.sort((a, b) => { ++ var _a, _b, _c, _d; ++ return ((_b = (_a = a.resolved) == null ? void 0 : _a.name) != null ? _b : "").localeCompare((_d = (_c = b.resolved) == null ? void 0 : _c.name) != null ? _d : ""); ++ }); ++ } ++ if (options.ctx.excludeDeprecated) { ++ operationParameters = operationParameters.filter( ++ ({ resolved }) => { ++ var _a; ++ return !(resolved == null ? void 0 : resolved.deprecated) && !((_a = resolved == null ? void 0 : resolved.schema) == null ? void 0 : _a.deprecated); ++ } ++ ); ++ } ++ for (const { original, resolved } of operationParameters) { ++ if ((resolved == null ? void 0 : resolved.in) !== paramIn) { ++ continue; ++ } ++ let optional = void 0; ++ if (paramIn !== "path" && !resolved.required) { ++ optional = QUESTION_TOKEN; ++ } ++ const subType = "$ref" in original ? oapiRef(original.$ref) : transformParameterObject(resolved, { ++ ...options, ++ path: createRef([options.path, "parameters", resolved.in, resolved.name]) ++ }); ++ const property = import_typescript5.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(resolved == null ? void 0 : resolved.name), ++ /* questionToken */ ++ optional, ++ /* type */ ++ subType ++ ); ++ addJSDocComment(resolved, property); ++ paramLocType.push(property); ++ } ++ const allOptional = paramLocType.every((node) => !!node.questionToken); ++ paramType.push( ++ import_typescript5.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(paramIn), ++ /* questionToken */ ++ allOptional || !paramLocType.length ? QUESTION_TOKEN : void 0, ++ /* type */ ++ paramLocType.length ? import_typescript5.default.factory.createTypeLiteralNode(paramLocType) : NEVER ++ ) ++ ); ++ } ++ type.push( ++ import_typescript5.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex("parameters"), ++ /* questionToken */ ++ !paramType.length ? QUESTION_TOKEN : void 0, ++ /* type */ ++ paramType.length ? import_typescript5.default.factory.createTypeLiteralNode(paramType) : NEVER ++ ) ++ ); ++ return type; ++} ++ ++// src/transform/request-body-object.ts ++var import_typescript6 = __toESM(require("typescript"), 1); ++function transformRequestBodyObject(requestBodyObject, options) { ++ var _a; ++ const type = []; ++ for (const [contentType, mediaTypeObject] of getEntries((_a = requestBodyObject.content) != null ? _a : {}, options.ctx)) { ++ const nextPath = createRef([options.path, contentType]); ++ const mediaType = "$ref" in mediaTypeObject ? transformSchemaObject(mediaTypeObject, { ++ ...options, ++ path: nextPath ++ }) : transformMediaTypeObject(mediaTypeObject, { ++ ...options, ++ path: nextPath ++ }); ++ const property = import_typescript6.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(contentType), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ mediaType ++ ); ++ addJSDocComment(mediaTypeObject, property); ++ type.push(property); ++ } ++ return import_typescript6.default.factory.createTypeLiteralNode([ ++ import_typescript6.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex("content"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ import_typescript6.default.factory.createTypeLiteralNode( ++ type.length ? type : ( ++ // add `"*/*": never` if no media types are defined ++ [ ++ import_typescript6.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex("*/*"), ++ /* questionToken */ ++ QUESTION_TOKEN, ++ /* type */ ++ NEVER ++ ) ++ ] ++ ) ++ ) ++ ) ++ ]); ++} ++ ++// src/transform/responses-object.ts ++var import_typescript8 = __toESM(require("typescript"), 1); ++ ++// src/transform/response-object.ts ++var import_typescript7 = __toESM(require("typescript"), 1); ++function transformResponseObject(responseObject, options) { ++ var _a; ++ const type = []; ++ const headersObject = []; ++ if (responseObject.headers) { ++ for (const [name, headerObject] of getEntries(responseObject.headers, options.ctx)) { ++ const optional = "$ref" in headerObject || headerObject.required ? void 0 : QUESTION_TOKEN; ++ const subType = "$ref" in headerObject ? oapiRef(headerObject.$ref) : transformHeaderObject(headerObject, { ++ ...options, ++ path: createRef([options.path, "headers", name]) ++ }); ++ const property = import_typescript7.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(name), ++ /* questionToken */ ++ optional, ++ /* type */ ++ subType ++ ); ++ addJSDocComment(headerObject, property); ++ headersObject.push(property); ++ } ++ } ++ headersObject.push( ++ import_typescript7.default.factory.createIndexSignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* parameters */ ++ [ ++ import_typescript7.default.factory.createParameterDeclaration( ++ /* modifiers */ ++ void 0, ++ /* dotDotDotToken */ ++ void 0, ++ /* name */ ++ import_typescript7.default.factory.createIdentifier("name"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ STRING ++ ) ++ ], ++ /* type */ ++ UNKNOWN ++ ) ++ ); ++ type.push( ++ import_typescript7.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex("headers"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ import_typescript7.default.factory.createTypeLiteralNode(headersObject) ++ ) ++ ); ++ const contentObject = []; ++ if (responseObject.content) { ++ for (const [contentType, mediaTypeObject] of getEntries((_a = responseObject.content) != null ? _a : {}, options.ctx)) { ++ const property = import_typescript7.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(contentType), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ transformMediaTypeObject(mediaTypeObject, { ++ ...options, ++ path: createRef([options.path, "content", contentType]) ++ }) ++ ); ++ contentObject.push(property); ++ } ++ } ++ if (contentObject.length) { ++ type.push( ++ import_typescript7.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex("content"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ import_typescript7.default.factory.createTypeLiteralNode(contentObject) ++ ) ++ ); ++ } else { ++ type.push( ++ import_typescript7.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex("content"), ++ /* questionToken */ ++ QUESTION_TOKEN, ++ /* type */ ++ NEVER ++ ) ++ ); ++ } ++ return import_typescript7.default.factory.createTypeLiteralNode(type); ++} ++ ++// src/transform/responses-object.ts ++function transformResponsesObject(responsesObject, options) { ++ const type = []; ++ for (const [responseCode, responseObject] of getEntries(responsesObject, options.ctx)) { ++ const responseType = "$ref" in responseObject ? oapiRef(responseObject.$ref) : transformResponseObject(responseObject, { ++ ...options, ++ path: createRef([options.path, "responses", responseCode]) ++ }); ++ const property = import_typescript8.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(responseCode), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ responseType ++ ); ++ addJSDocComment(responseObject, property); ++ type.push(property); ++ } ++ return type.length ? import_typescript8.default.factory.createTypeLiteralNode(type) : NEVER; ++} ++ ++// src/transform/operation-object.ts ++function transformOperationObject(operationObject, options) { ++ var _a, _b, _c; ++ const type = []; ++ type.push(...transformParametersArray((_a = operationObject.parameters) != null ? _a : [], options)); ++ if (operationObject.requestBody) { ++ const requestBodyType = "$ref" in operationObject.requestBody ? oapiRef(operationObject.requestBody.$ref) : transformRequestBodyObject(operationObject.requestBody, { ++ ...options, ++ path: createRef([options.path, "requestBody"]) ++ }); ++ const required = !!((_b = "$ref" in operationObject.requestBody ? options.ctx.resolve(operationObject.requestBody.$ref) : operationObject.requestBody) == null ? void 0 : _b.required); ++ const property = import_typescript9.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex("requestBody"), ++ /* questionToken */ ++ required ? void 0 : QUESTION_TOKEN, ++ /* type */ ++ requestBodyType ++ ); ++ addJSDocComment(operationObject.requestBody, property); ++ type.push(property); ++ } else { ++ type.push( ++ import_typescript9.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex("requestBody"), ++ /* questionToken */ ++ QUESTION_TOKEN, ++ /* type */ ++ NEVER ++ ) ++ ); ++ } ++ type.push( ++ import_typescript9.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex("responses"), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ transformResponsesObject((_c = operationObject.responses) != null ? _c : {}, options) ++ ) ++ ); ++ return type; ++} ++function injectOperationObject(operationId, operationObject, options) { ++ let operations = options.ctx.injectFooter.find( ++ (node) => import_typescript9.default.isInterfaceDeclaration(node) && node.name.text === "operations" ++ ); ++ if (!operations) { ++ operations = import_typescript9.default.factory.createInterfaceDeclaration( ++ /* modifiers */ ++ tsModifiers({ ++ export: true ++ // important: do NOT make this immutable ++ }), ++ /* name */ ++ import_typescript9.default.factory.createIdentifier("operations"), ++ /* typeParameters */ ++ void 0, ++ /* heritageClauses */ ++ void 0, ++ /* members */ ++ [] ++ ); ++ options.ctx.injectFooter.push(operations); ++ } ++ const type = transformOperationObject(operationObject, options); ++ operations.members = import_typescript9.default.factory.createNodeArray([ ++ ...operations.members, ++ import_typescript9.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(operationId), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ import_typescript9.default.factory.createTypeLiteralNode(type) ++ ) ++ ]); ++} ++ ++// src/transform/path-item-object.ts ++function transformPathItemObject(pathItem, options) { ++ var _a, _b, _c, _d, _e, _f; ++ const type = []; ++ type.push( ++ ...transformParametersArray((_a = pathItem.parameters) != null ? _a : [], { ++ ...options, ++ path: createRef([options.path, "parameters"]) ++ }) ++ ); ++ for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) { ++ const operationObject = pathItem[method]; ++ if (!operationObject || options.ctx.excludeDeprecated && ((_b = "$ref" in operationObject ? options.ctx.resolve(operationObject.$ref) : operationObject) == null ? void 0 : _b.deprecated)) { ++ type.push( ++ import_typescript10.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(method), ++ /* questionToken */ ++ QUESTION_TOKEN, ++ /* type */ ++ NEVER ++ ) ++ ); ++ continue; ++ } ++ const keyedParameters = {}; ++ if (!("$ref" in operationObject)) { ++ for (const parameter of [...(_c = pathItem.parameters) != null ? _c : [], ...(_d = operationObject.parameters) != null ? _d : []]) { ++ const name = "$ref" in parameter ? `${(_e = options.ctx.resolve(parameter.$ref)) == null ? void 0 : _e.in}-${(_f = options.ctx.resolve(parameter.$ref)) == null ? void 0 : _f.name}` : `${parameter.in}-${parameter.name}`; ++ if (name) { ++ keyedParameters[name] = parameter; ++ } ++ } ++ } ++ let operationType; ++ if ("$ref" in operationObject) { ++ operationType = oapiRef(operationObject.$ref); ++ } else if (operationObject.operationId) { ++ const operationId = operationObject.operationId.replace(HASH_RE, "/"); ++ operationType = oapiRef(createRef(["operations", operationId])); ++ injectOperationObject( ++ operationId, ++ { ...operationObject, parameters: Object.values(keyedParameters) }, ++ { ...options, path: createRef([options.path, method]) } ++ ); ++ } else { ++ operationType = import_typescript10.default.factory.createTypeLiteralNode( ++ transformOperationObject( ++ { ...operationObject, parameters: Object.values(keyedParameters) }, ++ { ...options, path: createRef([options.path, method]) } ++ ) ++ ); ++ } ++ const property = import_typescript10.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: options.ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(method), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ operationType ++ ); ++ addJSDocComment(operationObject, property); ++ type.push(property); ++ } ++ return import_typescript10.default.factory.createTypeLiteralNode(type); ++} ++var HASH_RE = /#/g; ++ ++// src/transform/components-object.ts ++var transformers = { ++ schemas: transformSchemaObject, ++ responses: transformResponseObject, ++ parameters: transformParameterObject, ++ requestBodies: transformRequestBodyObject, ++ headers: transformHeaderObject, ++ pathItems: transformPathItemObject ++}; ++function transformComponentsObject(componentsObject, ctx) { ++ const type = []; ++ const rootTypeAliases = {}; ++ for (const key of Object.keys(transformers)) { ++ const componentT = import_node_perf_hooks2.performance.now(); ++ const items = []; ++ if (componentsObject[key]) { ++ for (const [name, item] of getEntries(componentsObject[key], ctx)) { ++ let subType = transformers[key](item, { ++ path: createRef(["components", key, name]), ++ schema: item, ++ ctx ++ }); ++ let hasQuestionToken = false; ++ if (ctx.transform) { ++ const result = ctx.transform(item, { ++ path: createRef(["components", key, name]), ++ schema: item, ++ ctx ++ }); ++ if (result) { ++ if ("schema" in result) { ++ subType = result.schema; ++ hasQuestionToken = result.questionToken; ++ } else { ++ subType = result; ++ } ++ } ++ } ++ const property = import_typescript11.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(name), ++ /* questionToken */ ++ hasQuestionToken ? QUESTION_TOKEN : void 0, ++ /* type */ ++ subType ++ ); ++ addJSDocComment(item, property); ++ items.push(property); ++ if (ctx.rootTypes) { ++ const componentKey = pascalCase(singularizeComponentKey(key)); ++ let aliasName = `${componentKey}${pascalCase(name)}`; ++ let conflictCounter = 1; ++ while (rootTypeAliases[aliasName] !== void 0) { ++ conflictCounter++; ++ aliasName = `${componentKey}${pascalCase(name)}_${conflictCounter}`; ++ } ++ const ref = import_typescript11.default.factory.createTypeReferenceNode(`components['${key}']['${name}']`); ++ if (ctx.rootTypesNoSchemaPrefix && key === "schemas") { ++ aliasName = aliasName.replace(componentKey, ""); ++ } ++ const typeAlias = import_typescript11.default.factory.createTypeAliasDeclaration( ++ /* modifiers */ ++ tsModifiers({ export: true }), ++ /* name */ ++ aliasName, ++ /* typeParameters */ ++ void 0, ++ /* type */ ++ ref ++ ); ++ rootTypeAliases[aliasName] = typeAlias; ++ } ++ } ++ } ++ type.push( ++ import_typescript11.default.factory.createPropertySignature( ++ /* modifiers */ ++ void 0, ++ /* name */ ++ tsPropertyIndex(key), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ items.length ? import_typescript11.default.factory.createTypeLiteralNode(items) : NEVER ++ ) ++ ); ++ debug(`Transformed components \u2192 ${key}`, "ts", import_node_perf_hooks2.performance.now() - componentT); ++ } ++ let rootTypes = []; ++ if (ctx.rootTypes) { ++ rootTypes = Object.keys(rootTypeAliases).map((k) => rootTypeAliases[k]); ++ } ++ return [import_typescript11.default.factory.createTypeLiteralNode(type), ...rootTypes]; ++} ++function singularizeComponentKey(key) { ++ switch (key) { ++ // Handle special singular case ++ case "requestBodies": ++ return "requestBody"; ++ // Default to removing the "s" ++ default: ++ return key.slice(0, -1); ++ } ++} ++ ++// src/transform/paths-object.ts ++var import_typescript12 = __toESM(require("typescript"), 1); ++var import_node_perf_hooks3 = require("node:perf_hooks"); ++var PATH_PARAM_RE2 = /\{[^}]+\}/g; ++function transformPathsObject(pathsObject, ctx) { ++ var _a, _b; ++ const type = []; ++ for (const [url, pathItemObject] of getEntries(pathsObject, ctx)) { ++ if (!pathItemObject || typeof pathItemObject !== "object") { ++ continue; ++ } ++ const pathT = import_node_perf_hooks3.performance.now(); ++ if ("$ref" in pathItemObject) { ++ const property = import_typescript12.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(url), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ oapiRef(pathItemObject.$ref) ++ ); ++ addJSDocComment(pathItemObject, property); ++ type.push(property); ++ } else { ++ const pathItemType = transformPathItemObject(pathItemObject, { ++ path: createRef(["paths", url]), ++ ctx ++ }); ++ if (ctx.pathParamsAsTypes && url.includes("{")) { ++ const pathParams = extractPathParams(pathItemObject, ctx); ++ const matches = url.match(PATH_PARAM_RE2); ++ let rawPath = `\`${url}\``; ++ if (matches) { ++ for (const match of matches) { ++ const paramName = match.slice(1, -1); ++ const param = pathParams[paramName]; ++ switch ((_a = param == null ? void 0 : param.schema) == null ? void 0 : _a.type) { ++ case "number": ++ case "integer": ++ rawPath = rawPath.replace(match, "${number}"); ++ break; ++ case "boolean": ++ rawPath = rawPath.replace(match, "${boolean}"); ++ break; ++ default: ++ rawPath = rawPath.replace(match, "${string}"); ++ break; ++ } ++ } ++ const pathType = (_b = stringToAST(rawPath)[0]) == null ? void 0 : _b.expression; ++ if (pathType) { ++ type.push( ++ import_typescript12.default.factory.createIndexSignature( ++ /* modifiers */ ++ tsModifiers({ readonly: ctx.immutable }), ++ /* parameters */ ++ [ ++ import_typescript12.default.factory.createParameterDeclaration( ++ /* modifiers */ ++ void 0, ++ /* dotDotDotToken */ ++ void 0, ++ /* name */ ++ "path", ++ /* questionToken */ ++ void 0, ++ /* type */ ++ pathType, ++ /* initializer */ ++ void 0 ++ ) ++ ], ++ /* type */ ++ pathItemType ++ ) ++ ); ++ continue; ++ } ++ } ++ } ++ type.push( ++ import_typescript12.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ readonly: ctx.immutable }), ++ /* name */ ++ tsPropertyIndex(url), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ pathItemType ++ ) ++ ); ++ debug(`Transformed path "${url}"`, "ts", import_node_perf_hooks3.performance.now() - pathT); ++ } ++ } ++ return import_typescript12.default.factory.createTypeLiteralNode(type); ++} ++function extractPathParams(pathItemObject, ctx) { ++ var _a; ++ const params = {}; ++ for (const p of (_a = pathItemObject.parameters) != null ? _a : []) { ++ const resolved = "$ref" in p && p.$ref ? ctx.resolve(p.$ref) : p; ++ if (resolved && resolved.in === "path") { ++ params[resolved.name] = resolved; ++ } ++ } ++ for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) { ++ if (!(method in pathItemObject)) { ++ continue; ++ } ++ const resolvedMethod = pathItemObject[method].$ref ? ctx.resolve(pathItemObject[method].$ref) : pathItemObject[method]; ++ if (resolvedMethod == null ? void 0 : resolvedMethod.parameters) { ++ for (const p of resolvedMethod.parameters) { ++ const resolvedParam = "$ref" in p && p.$ref ? ctx.resolve(p.$ref) : p; ++ if (resolvedParam && resolvedParam.in === "path") { ++ params[resolvedParam.name] = resolvedParam; ++ } ++ } ++ } ++ } ++ return params; ++} ++ ++// src/transform/webhooks-object.ts ++var import_typescript13 = __toESM(require("typescript"), 1); ++function transformWebhooksObject(webhooksObject, options) { ++ const type = []; ++ for (const [name, pathItemObject] of getEntries(webhooksObject, options)) { ++ type.push( ++ import_typescript13.default.factory.createPropertySignature( ++ /* modifiers */ ++ tsModifiers({ ++ readonly: options.immutable ++ }), ++ /* name */ ++ tsPropertyIndex(name), ++ /* questionToken */ ++ void 0, ++ /* type */ ++ transformPathItemObject(pathItemObject, { ++ path: createRef(["webhooks", name]), ++ ctx: options ++ }) ++ ) ++ ); ++ } ++ return import_typescript13.default.factory.createTypeLiteralNode(type); ++} ++ ++// src/transform/paths-enum.ts ++function makeApiPathsEnum(pathsObject) { ++ const enumKeys = []; ++ const enumMetaData = []; ++ for (const [url, pathItemObject] of getEntries(pathsObject)) { ++ for (const [method, operation] of Object.entries(pathItemObject)) { ++ if (!["get", "put", "post", "delete", "options", "head", "patch", "trace"].includes(method)) { ++ continue; ++ } ++ let pathName; ++ if (operation.operationId) { ++ pathName = operation.operationId; ++ } else { ++ pathName = (method + url).split("/").map((part) => { ++ const capitalised = part.charAt(0).toUpperCase() + part.slice(1); ++ return capitalised.replace(/{.*}|:.*|[^a-zA-Z\d_]+/, ""); ++ }).join(""); ++ } ++ const adaptedUrl = url.replace(/{(\w+)}/g, ":$1"); ++ enumKeys.push(adaptedUrl); ++ enumMetaData.push({ ++ name: pathName ++ }); ++ } ++ } ++ return tsEnum("ApiPaths", enumKeys, enumMetaData, { ++ export: true ++ }); ++} ++ ++// src/transform/index.ts ++var transformers2 = { ++ paths: transformPathsObject, ++ webhooks: transformWebhooksObject, ++ components: transformComponentsObject, ++ $defs: (node, options) => transformSchemaObject(node, { path: createRef(["$defs"]), ctx: options, schema: node }) ++}; ++function transformSchema(schema, ctx) { ++ var _a, _b; ++ const type = []; ++ if (ctx.inject) { ++ const injectNodes = stringToAST(ctx.inject); ++ type.push(...injectNodes); ++ } ++ for (const root of Object.keys(transformers2)) { ++ const emptyObj = import_typescript14.default.factory.createTypeAliasDeclaration( ++ /* modifiers */ ++ tsModifiers({ export: true }), ++ /* name */ ++ root, ++ /* typeParameters */ ++ void 0, ++ /* type */ ++ tsRecord(STRING, NEVER) ++ ); ++ if (schema[root] && typeof schema[root] === "object") { ++ const rootT = import_node_perf_hooks4.performance.now(); ++ const subTypes = [].concat(transformers2[root](schema[root], ctx)); ++ for (const subType of subTypes) { ++ if (import_typescript14.default.isTypeNode(subType)) { ++ if ((_a = subType.members) == null ? void 0 : _a.length) { ++ type.push( ++ ctx.exportType ? import_typescript14.default.factory.createTypeAliasDeclaration( ++ /* modifiers */ ++ tsModifiers({ export: true }), ++ /* name */ ++ root, ++ /* typeParameters */ ++ void 0, ++ /* type */ ++ subType ++ ) : import_typescript14.default.factory.createInterfaceDeclaration( ++ /* modifiers */ ++ tsModifiers({ export: true }), ++ /* name */ ++ root, ++ /* typeParameters */ ++ void 0, ++ /* heritageClauses */ ++ void 0, ++ /* members */ ++ subType.members ++ ) ++ ); ++ debug(`${root} done`, "ts", import_node_perf_hooks4.performance.now() - rootT); ++ } else { ++ type.push(emptyObj); ++ debug(`${root} done (skipped)`, "ts", 0); ++ } ++ } else if (import_typescript14.default.isTypeAliasDeclaration(subType)) { ++ type.push(subType); ++ } else { ++ type.push(emptyObj); ++ debug(`${root} done (skipped)`, "ts", 0); ++ } ++ } ++ } else { ++ type.push(emptyObj); ++ debug(`${root} done (skipped)`, "ts", 0); ++ } ++ } ++ let hasOperations = false; ++ for (const injectedType of ctx.injectFooter) { ++ if (!hasOperations && ((_b = injectedType == null ? void 0 : injectedType.name) == null ? void 0 : _b.escapedText) === "operations") { ++ hasOperations = true; ++ } ++ type.push(injectedType); ++ } ++ if (!hasOperations) { ++ type.push( ++ import_typescript14.default.factory.createTypeAliasDeclaration( ++ /* modifiers */ ++ tsModifiers({ export: true }), ++ /* name */ ++ "operations", ++ /* typeParameters */ ++ void 0, ++ /* type */ ++ tsRecord(STRING, NEVER) ++ ) ++ ); ++ } ++ if (ctx.makePathsEnum && schema.paths) { ++ type.push(makeApiPathsEnum(schema.paths)); ++ } ++ return type; ++} ++ ++// src/index.ts ++var COMMENT_HEADER = `/** ++ * This file was auto-generated by openapi-typescript. ++ * Do not make direct changes to the file. ++ */ ++ ++`; ++async function openapiTS(source, options = {}) { ++ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v; ++ if (!source) { ++ throw new Error("Empty schema. Please specify a URL, file path, or Redocly Config"); ++ } ++ const redoc = (_a = options.redocly) != null ? _a : await (0, import_openapi_core2.createConfig)( ++ { ++ rules: { ++ "operation-operationId-unique": { severity: "error" } ++ // throw error on duplicate operationIDs ++ } ++ }, ++ { extends: ["minimal"] } ++ ); ++ const schema = await validateAndBundle(source, { ++ redoc, ++ cwd: options.cwd instanceof URL ? options.cwd : new URL(`file://${(_b = options.cwd) != null ? _b : process.cwd()}/`), ++ silent: (_c = options.silent) != null ? _c : false ++ }); ++ const ctx = { ++ additionalProperties: (_d = options.additionalProperties) != null ? _d : false, ++ alphabetize: (_e = options.alphabetize) != null ? _e : false, ++ arrayLength: (_f = options.arrayLength) != null ? _f : false, ++ defaultNonNullable: (_g = options.defaultNonNullable) != null ? _g : true, ++ discriminators: scanDiscriminators(schema, options), ++ emptyObjectsUnknown: (_h = options.emptyObjectsUnknown) != null ? _h : false, ++ enum: (_i = options.enum) != null ? _i : false, ++ enumValues: (_j = options.enumValues) != null ? _j : false, ++ dedupeEnums: (_k = options.dedupeEnums) != null ? _k : false, ++ excludeDeprecated: (_l = options.excludeDeprecated) != null ? _l : false, ++ exportType: (_m = options.exportType) != null ? _m : false, ++ immutable: (_n = options.immutable) != null ? _n : false, ++ rootTypes: (_o = options.rootTypes) != null ? _o : false, ++ rootTypesNoSchemaPrefix: (_p = options.rootTypesNoSchemaPrefix) != null ? _p : false, ++ injectFooter: [], ++ pathParamsAsTypes: (_q = options.pathParamsAsTypes) != null ? _q : false, ++ postTransform: typeof options.postTransform === "function" ? options.postTransform : void 0, ++ propertiesRequiredByDefault: (_r = options.propertiesRequiredByDefault) != null ? _r : false, ++ redoc, ++ silent: (_s = options.silent) != null ? _s : false, ++ inject: (_t = options.inject) != null ? _t : void 0, ++ transform: typeof options.transform === "function" ? options.transform : void 0, ++ makePathsEnum: (_u = options.makePathsEnum) != null ? _u : false, ++ generatePathParams: (_v = options.generatePathParams) != null ? _v : false, ++ resolve($ref) { ++ var _a2; ++ return resolveRef(schema, $ref, { silent: (_a2 = options.silent) != null ? _a2 : false }); ++ } ++ }; ++ const transformT = import_node_perf_hooks5.performance.now(); ++ const result = transformSchema(schema, ctx); ++ debug("Completed AST transformation for entire document", "ts", import_node_perf_hooks5.performance.now() - transformT); ++ return result; ++} ++// Annotate the CommonJS export names for ESM import in node: ++0 && (module.exports = { ++ BOOLEAN, ++ COMMENT_HEADER, ++ FALSE, ++ JS_ENUM_INVALID_CHARS_RE, ++ JS_PROPERTY_INDEX_INVALID_CHARS_RE, ++ JS_PROPERTY_INDEX_RE, ++ NEVER, ++ NULL, ++ NUMBER, ++ QUESTION_TOKEN, ++ SPECIAL_CHARACTER_MAP, ++ STRING, ++ TRUE, ++ UNDEFINED, ++ UNKNOWN, ++ addJSDocComment, ++ astToString, ++ c, ++ createDiscriminatorProperty, ++ createRef, ++ debug, ++ enumCache, ++ error, ++ formatTime, ++ getEntries, ++ injectOperationObject, ++ oapiRef, ++ resolveRef, ++ scanDiscriminators, ++ stringToAST, ++ transformComponentsObject, ++ transformHeaderObject, ++ transformMediaTypeObject, ++ transformOperationObject, ++ transformParameterObject, ++ transformPathItemObject, ++ transformPathsObject, ++ transformRequestBodyObject, ++ transformResponseObject, ++ transformResponsesObject, ++ transformSchema, ++ transformSchemaObject, ++ transformSchemaObjectWithComposition, ++ tsArrayLiteralExpression, ++ tsDedupe, ++ tsEnum, ++ tsEnumMember, ++ tsIntersection, ++ tsIsPrimitive, ++ tsLiteral, ++ tsModifiers, ++ tsNullable, ++ tsOmit, ++ tsPropertyIndex, ++ tsReadonlyArray, ++ tsRecord, ++ tsUnion, ++ tsWithRequired, ++ walk, ++ warn ++}); +diff --git a/package/dist/index.d.ts b/package/dist/index.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..000a7e05edfe9b4d794e28c01c7de1a569772d2e +--- /dev/null ++++ b/package/dist/index.d.ts +@@ -0,0 +1,23 @@ ++import type { Readable } from "node:stream"; ++import type ts from "typescript"; ++import type { OpenAPI3, OpenAPITSOptions } from "./types.js"; ++export * from "./lib/ts.js"; ++export * from "./lib/utils.js"; ++export { default as transformSchema } from "./transform/index.js"; ++export { default as transformComponentsObject } from "./transform/components-object.js"; ++export { default as transformHeaderObject } from "./transform/header-object.js"; ++export { default as transformMediaTypeObject } from "./transform/media-type-object.js"; ++export * from "./transform/operation-object.js"; ++export { default as transformOperationObject } from "./transform/operation-object.js"; ++export { default as transformParameterObject } from "./transform/parameter-object.js"; ++export * from "./transform/path-item-object.js"; ++export { default as transformPathItemObject } from "./transform/path-item-object.js"; ++export { default as transformPathsObject } from "./transform/paths-object.js"; ++export { default as transformRequestBodyObject } from "./transform/request-body-object.js"; ++export { default as transformResponseObject } from "./transform/response-object.js"; ++export { default as transformResponsesObject } from "./transform/responses-object.js"; ++export * from "./transform/schema-object.js"; ++export { default as transformSchemaObject } from "./transform/schema-object.js"; ++export * from "./types.js"; ++export declare const COMMENT_HEADER = "/**\n * This file was auto-generated by openapi-typescript.\n * Do not make direct changes to the file.\n */\n\n"; ++export default function openapiTS(source: string | URL | OpenAPI3 | Buffer | Readable, options?: OpenAPITSOptions): Promise; +diff --git a/package/dist/index.js b/package/dist/index.js +new file mode 100644 +index 0000000000000000000000000000000000000000..874c6af113bb443a15f3adba77367db46019f88f +--- /dev/null ++++ b/package/dist/index.js +@@ -0,0 +1,79 @@ ++import { createConfig } from "@redocly/openapi-core"; ++import { performance } from "node:perf_hooks"; ++import { validateAndBundle } from "./lib/redoc.js"; ++import { debug, resolveRef, scanDiscriminators } from "./lib/utils.js"; ++import transformSchema from "./transform/index.js"; ++export * from "./lib/ts.js"; ++export * from "./lib/utils.js"; ++export { default as transformSchema } from "./transform/index.js"; ++export { default as transformComponentsObject } from "./transform/components-object.js"; ++export { default as transformHeaderObject } from "./transform/header-object.js"; ++export { default as transformMediaTypeObject } from "./transform/media-type-object.js"; ++export * from "./transform/operation-object.js"; ++export { default as transformOperationObject } from "./transform/operation-object.js"; ++export { default as transformParameterObject } from "./transform/parameter-object.js"; ++export * from "./transform/path-item-object.js"; ++export { default as transformPathItemObject } from "./transform/path-item-object.js"; ++export { default as transformPathsObject } from "./transform/paths-object.js"; ++export { default as transformRequestBodyObject } from "./transform/request-body-object.js"; ++export { default as transformResponseObject } from "./transform/response-object.js"; ++export { default as transformResponsesObject } from "./transform/responses-object.js"; ++export * from "./transform/schema-object.js"; ++export { default as transformSchemaObject } from "./transform/schema-object.js"; ++export * from "./types.js"; ++export const COMMENT_HEADER = `/** ++ * This file was auto-generated by openapi-typescript. ++ * Do not make direct changes to the file. ++ */ ++ ++`; ++export default async function openapiTS(source, options = {}) { ++ if (!source) { ++ throw new Error("Empty schema. Please specify a URL, file path, or Redocly Config"); ++ } ++ const redoc = options.redocly ?? ++ (await createConfig({ ++ rules: { ++ "operation-operationId-unique": { severity: "error" }, ++ }, ++ }, { extends: ["minimal"] })); ++ const schema = await validateAndBundle(source, { ++ redoc, ++ cwd: options.cwd instanceof URL ? options.cwd : new URL(`file://${options.cwd ?? process.cwd()}/`), ++ silent: options.silent ?? false, ++ }); ++ const ctx = { ++ additionalProperties: options.additionalProperties ?? false, ++ alphabetize: options.alphabetize ?? false, ++ arrayLength: options.arrayLength ?? false, ++ defaultNonNullable: options.defaultNonNullable ?? true, ++ discriminators: scanDiscriminators(schema, options), ++ emptyObjectsUnknown: options.emptyObjectsUnknown ?? false, ++ enum: options.enum ?? false, ++ enumValues: options.enumValues ?? false, ++ dedupeEnums: options.dedupeEnums ?? false, ++ excludeDeprecated: options.excludeDeprecated ?? false, ++ exportType: options.exportType ?? false, ++ immutable: options.immutable ?? false, ++ rootTypes: options.rootTypes ?? false, ++ rootTypesNoSchemaPrefix: options.rootTypesNoSchemaPrefix ?? false, ++ injectFooter: [], ++ pathParamsAsTypes: options.pathParamsAsTypes ?? false, ++ postTransform: typeof options.postTransform === "function" ? options.postTransform : undefined, ++ propertiesRequiredByDefault: options.propertiesRequiredByDefault ?? false, ++ redoc, ++ silent: options.silent ?? false, ++ inject: options.inject ?? undefined, ++ transform: typeof options.transform === "function" ? options.transform : undefined, ++ makePathsEnum: options.makePathsEnum ?? false, ++ generatePathParams: options.generatePathParams ?? false, ++ resolve($ref) { ++ return resolveRef(schema, $ref, { silent: options.silent ?? false }); ++ }, ++ }; ++ const transformT = performance.now(); ++ const result = transformSchema(schema, ctx); ++ debug("Completed AST transformation for entire document", "ts", performance.now() - transformT); ++ return result; ++} ++//# sourceMappingURL=index.js.map +\ No newline at end of file +diff --git a/package/dist/index.js.map b/package/dist/index.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..9361e8525760b511525673ac2d7103d807b5d2dc +--- /dev/null ++++ b/package/dist/index.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACvE,OAAO,eAAe,MAAM,sBAAsB,CAAC;AAGnD,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,EAAE,OAAO,IAAI,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AACxF,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAChF,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AACvF,cAAc,iCAAiC,CAAC;AAChD,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AACtF,cAAc,iCAAiC,CAAC;AAChD,OAAO,EAAE,OAAO,IAAI,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AACrF,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAAE,OAAO,IAAI,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAC3F,OAAO,EAAE,OAAO,IAAI,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACpF,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AACtF,cAAc,8BAA8B,CAAC;AAC7C,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAChF,cAAc,YAAY,CAAC;AAE3B,MAAM,CAAC,MAAM,cAAc,GAAG;;;;;CAK7B,CAAC;AAUF,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,SAAS,CACrC,MAAmD,EACnD,UAA4B,EAA+B;IAE3D,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IACtF,CAAC;IAED,MAAM,KAAK,GACT,OAAO,CAAC,OAAO;QACf,CAAC,MAAM,YAAY,CACjB;YACE,KAAK,EAAE;gBACL,8BAA8B,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE;aACtD;SACF,EACD,EAAE,OAAO,EAAE,CAAC,SAAS,CAAC,EAAE,CACzB,CAAC,CAAC;IAEL,MAAM,MAAM,GAAG,MAAM,iBAAiB,CAAC,MAAM,EAAE;QAC7C,KAAK;QACL,GAAG,EAAE,OAAO,CAAC,GAAG,YAAY,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,UAAU,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC;QAClG,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK;KAChC,CAAC,CAAC;IAEH,MAAM,GAAG,GAAkB;QACzB,oBAAoB,EAAE,OAAO,CAAC,oBAAoB,IAAI,KAAK;QAC3D,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,KAAK;QACzC,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,KAAK;QACzC,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,IAAI,IAAI;QACtD,cAAc,EAAE,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;QACnD,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,IAAI,KAAK;QACzD,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,KAAK;QAC3B,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,KAAK;QACvC,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,KAAK;QACzC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,IAAI,KAAK;QACrD,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,KAAK;QACvC,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,KAAK;QACrC,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,KAAK;QACrC,uBAAuB,EAAE,OAAO,CAAC,uBAAuB,IAAI,KAAK;QACjE,YAAY,EAAE,EAAE;QAChB,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,IAAI,KAAK;QACrD,aAAa,EAAE,OAAO,OAAO,CAAC,aAAa,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS;QAC9F,2BAA2B,EAAE,OAAO,CAAC,2BAA2B,IAAI,KAAK;QACzE,KAAK;QACL,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK;QAC/B,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,SAAS;QACnC,SAAS,EAAE,OAAO,OAAO,CAAC,SAAS,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS;QAClF,aAAa,EAAE,OAAO,CAAC,aAAa,IAAI,KAAK;QAC7C,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,IAAI,KAAK;QACvD,OAAO,CAAC,IAAI;YACV,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC;QACvE,CAAC;KACF,CAAC;IAEF,MAAM,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACrC,MAAM,MAAM,GAAG,eAAe,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5C,KAAK,CAAC,kDAAkD,EAAE,IAAI,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,UAAU,CAAC,CAAC;IAEhG,OAAO,MAAM,CAAC;AAChB,CAAC"} +\ No newline at end of file +diff --git a/package/dist/lib/redoc.d.ts b/package/dist/lib/redoc.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..9be3f02330d78a14c36dd338e1ef3955c7b6bf97 +--- /dev/null ++++ b/package/dist/lib/redoc.d.ts +@@ -0,0 +1,15 @@ ++import { BaseResolver, type Config as RedoclyConfig, type Document } from "@redocly/openapi-core"; ++import { Readable } from "node:stream"; ++import type { OpenAPI3 } from "../types.js"; ++export interface ValidateAndBundleOptions { ++ redoc: RedoclyConfig; ++ silent: boolean; ++ cwd?: URL; ++} ++interface ParseSchemaOptions { ++ absoluteRef: string; ++ resolver: BaseResolver; ++} ++export declare function parseSchema(schema: unknown, { absoluteRef, resolver }: ParseSchemaOptions): Promise; ++export declare function validateAndBundle(source: string | URL | OpenAPI3 | Readable | Buffer, options: ValidateAndBundleOptions): Promise; ++export {}; +diff --git a/package/dist/lib/redoc.js b/package/dist/lib/redoc.js +new file mode 100644 +index 0000000000000000000000000000000000000000..65b6a32871426d5bb3461c2c98c4cc76b4cd1098 +--- /dev/null ++++ b/package/dist/lib/redoc.js +@@ -0,0 +1,124 @@ ++import { BaseResolver, bundle, makeDocumentFromString, Source, lintDocument, } from "@redocly/openapi-core"; ++import { performance } from "node:perf_hooks"; ++import { Readable } from "node:stream"; ++import { fileURLToPath } from "node:url"; ++import parseJson from "parse-json"; ++import { debug, error, warn } from "./utils.js"; ++export async function parseSchema(schema, { absoluteRef, resolver }) { ++ if (!schema) { ++ throw new Error("Can’t parse empty schema"); ++ } ++ if (schema instanceof URL) { ++ const result = await resolver.resolveDocument(null, absoluteRef, true); ++ if ("parsed" in result) { ++ return result; ++ } ++ throw result.originalError; ++ } ++ if (schema instanceof Readable) { ++ const contents = await new Promise((resolve) => { ++ schema.resume(); ++ schema.setEncoding("utf8"); ++ let content = ""; ++ schema.on("data", (chunk) => { ++ content += chunk; ++ }); ++ schema.on("end", () => { ++ resolve(content.trim()); ++ }); ++ }); ++ return parseSchema(contents, { absoluteRef, resolver }); ++ } ++ if (schema instanceof Buffer) { ++ return parseSchema(schema.toString("utf8"), { absoluteRef, resolver }); ++ } ++ if (typeof schema === "string") { ++ if (schema.startsWith("http://") || schema.startsWith("https://") || schema.startsWith("file://")) { ++ const url = new URL(schema); ++ return parseSchema(url, { ++ absoluteRef: url.protocol === "file:" ? fileURLToPath(url) : url.href, ++ resolver, ++ }); ++ } ++ if (schema[0] === "{") { ++ return { ++ source: new Source(absoluteRef, schema, "application/json"), ++ parsed: parseJson(schema), ++ }; ++ } ++ return makeDocumentFromString(schema, absoluteRef); ++ } ++ if (typeof schema === "object" && !Array.isArray(schema)) { ++ return { ++ source: new Source(absoluteRef, JSON.stringify(schema), "application/json"), ++ parsed: schema, ++ }; ++ } ++ throw new Error(`Expected string, object, or Buffer. Got ${Array.isArray(schema) ? "Array" : typeof schema}`); ++} ++function _processProblems(problems, options) { ++ if (problems.length) { ++ let errorMessage = undefined; ++ for (const problem of problems) { ++ const problemLocation = problem.location?.[0].pointer; ++ const problemMessage = problemLocation ? `${problem.message} at ${problemLocation}` : problem.message; ++ if (problem.severity === "error") { ++ errorMessage = problemMessage; ++ error(problemMessage); ++ } ++ else { ++ warn(problemMessage, options.silent); ++ } ++ } ++ if (errorMessage) { ++ throw new Error(errorMessage); ++ } ++ } ++} ++export async function validateAndBundle(source, options) { ++ const redocConfigT = performance.now(); ++ debug("Loaded Redoc config", "redoc", performance.now() - redocConfigT); ++ const redocParseT = performance.now(); ++ let absoluteRef = fileURLToPath(new URL(options?.cwd ?? `file://${process.cwd()}/`)); ++ if (source instanceof URL) { ++ absoluteRef = source.protocol === "file:" ? fileURLToPath(source) : source.href; ++ } ++ const resolver = new BaseResolver(options.redoc.resolve); ++ const document = await parseSchema(source, { ++ absoluteRef, ++ resolver, ++ }); ++ debug("Parsed schema", "redoc", performance.now() - redocParseT); ++ const openapiVersion = Number.parseFloat(document.parsed.openapi); ++ if (document.parsed.swagger || ++ !document.parsed.openapi || ++ Number.isNaN(openapiVersion) || ++ openapiVersion < 3 || ++ openapiVersion >= 4) { ++ if (document.parsed.swagger) { ++ throw new Error("Unsupported Swagger version: 2.x. Use OpenAPI 3.x instead."); ++ } ++ if (document.parsed.openapi || openapiVersion < 3 || openapiVersion >= 4) { ++ throw new Error(`Unsupported OpenAPI version: ${document.parsed.openapi}`); ++ } ++ throw new Error("Unsupported schema format, expected `openapi: 3.x`"); ++ } ++ const redocLintT = performance.now(); ++ const problems = await lintDocument({ ++ document, ++ config: options.redoc.styleguide, ++ externalRefResolver: resolver, ++ }); ++ _processProblems(problems, options); ++ debug("Linted schema", "lint", performance.now() - redocLintT); ++ const redocBundleT = performance.now(); ++ const bundled = await bundle({ ++ config: options.redoc, ++ dereference: false, ++ doc: document, ++ }); ++ _processProblems(bundled.problems, options); ++ debug("Bundled schema", "bundle", performance.now() - redocBundleT); ++ return bundled.bundle.parsed; ++} ++//# sourceMappingURL=redoc.js.map +\ No newline at end of file +diff --git a/package/dist/lib/redoc.js.map b/package/dist/lib/redoc.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..fe7a3c1a32ece9ba29d30496fb63ebb8747533d2 +--- /dev/null ++++ b/package/dist/lib/redoc.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"redoc.js","sourceRoot":"","sources":["../../src/lib/redoc.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,MAAM,EACN,sBAAsB,EAEtB,MAAM,EAEN,YAAY,GAEb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,SAAS,MAAM,YAAY,CAAC;AAEnC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAahD,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,MAAe,EAAE,EAAE,WAAW,EAAE,QAAQ,EAAsB;IAC9F,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAC9C,CAAC;IACD,IAAI,MAAM,YAAY,GAAG,EAAE,CAAC;QAC1B,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;QACvE,IAAI,QAAQ,IAAI,MAAM,EAAE,CAAC;YACvB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,MAAM,MAAM,CAAC,aAAa,CAAC;IAC7B,CAAC;IACD,IAAI,MAAM,YAAY,QAAQ,EAAE,CAAC;QAC/B,MAAM,QAAQ,GAAG,MAAM,IAAI,OAAO,CAAS,CAAC,OAAO,EAAE,EAAE;YACrD,MAAM,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAC3B,IAAI,OAAO,GAAG,EAAE,CAAC;YACjB,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE;gBAClC,OAAO,IAAI,KAAK,CAAC;YACnB,CAAC,CAAC,CAAC;YACH,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;gBACpB,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YAC1B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;QACH,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC1D,CAAC;IACD,IAAI,MAAM,YAAY,MAAM,EAAE,CAAC;QAC7B,OAAO,WAAW,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,CAAC;IACzE,CAAC;IACD,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAE/B,IAAI,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;YAClG,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC;YAC5B,OAAO,WAAW,CAAC,GAAG,EAAE;gBACtB,WAAW,EAAE,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI;gBACrE,QAAQ;aACT,CAAC,CAAC;QACL,CAAC;QAED,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;YACtB,OAAO;gBACL,MAAM,EAAE,IAAI,MAAM,CAAC,WAAW,EAAE,MAAM,EAAE,kBAAkB,CAAC;gBAC3D,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC;aAC1B,CAAC;QACJ,CAAC;QAED,OAAO,sBAAsB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrD,CAAC;IACD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QACzD,OAAO;YACL,MAAM,EAAE,IAAI,MAAM,CAAC,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,kBAAkB,CAAC;YAC3E,MAAM,EAAE,MAAM;SACf,CAAC;IACJ,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,MAAM,EAAE,CAAC,CAAC;AAChH,CAAC;AAED,SAAS,gBAAgB,CAAC,QAA6B,EAAE,OAA4B;IACnF,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;QACpB,IAAI,YAAY,GAAuB,SAAS,CAAC;QACjD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,MAAM,eAAe,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;YACtD,MAAM,cAAc,GAAG,eAAe,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,OAAO,eAAe,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;YACtG,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;gBACjC,YAAY,GAAG,cAAc,CAAC;gBAC9B,KAAK,CAAC,cAAc,CAAC,CAAC;YACxB,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,cAAc,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;YACvC,CAAC;QACH,CAAC;QACD,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;AACH,CAAC;AAKD,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,MAAmD,EACnD,OAAiC;IAEjC,MAAM,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACvC,KAAK,CAAC,qBAAqB,EAAE,OAAO,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC,CAAC;IACxE,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACtC,IAAI,WAAW,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,OAAO,EAAE,GAAG,IAAI,UAAU,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;IACrF,IAAI,MAAM,YAAY,GAAG,EAAE,CAAC;QAC1B,WAAW,GAAG,MAAM,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;IAClF,CAAC;IACD,MAAM,QAAQ,GAAG,IAAI,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,MAAM,EAAE;QACzC,WAAW;QACX,QAAQ;KACT,CAAC,CAAC;IACH,KAAK,CAAC,eAAe,EAAE,OAAO,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,CAAC;IAGjE,MAAM,cAAc,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAClE,IACE,QAAQ,CAAC,MAAM,CAAC,OAAO;QACvB,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO;QACxB,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC;QAC5B,cAAc,GAAG,CAAC;QAClB,cAAc,IAAI,CAAC,EACnB,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YAC5B,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;QAChF,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,CAAC,OAAO,IAAI,cAAc,GAAG,CAAC,IAAI,cAAc,IAAI,CAAC,EAAE,CAAC;YACzE,MAAM,IAAI,KAAK,CAAC,gCAAgC,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;QAC7E,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IAGD,MAAM,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACrC,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC;QAClC,QAAQ;QACR,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,UAAU;QAChC,mBAAmB,EAAE,QAAQ;KAC9B,CAAC,CAAC;IACH,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACpC,KAAK,CAAC,eAAe,EAAE,MAAM,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,UAAU,CAAC,CAAC;IAG/D,MAAM,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACvC,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC;QAC3B,MAAM,EAAE,OAAO,CAAC,KAAK;QACrB,WAAW,EAAE,KAAK;QAClB,GAAG,EAAE,QAAQ;KACd,CAAC,CAAC;IACH,gBAAgB,CAAC,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5C,KAAK,CAAC,gBAAgB,EAAE,QAAQ,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,YAAY,CAAC,CAAC;IAEpE,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;AAC/B,CAAC"} +\ No newline at end of file +diff --git a/package/dist/lib/ts.d.ts b/package/dist/lib/ts.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..6e31e0ec46ae870dc987766511a52ab26663cf8d +--- /dev/null ++++ b/package/dist/lib/ts.d.ts +@@ -0,0 +1,69 @@ ++import ts from "typescript"; ++export declare const JS_PROPERTY_INDEX_RE: RegExp; ++export declare const JS_ENUM_INVALID_CHARS_RE: RegExp; ++export declare const JS_PROPERTY_INDEX_INVALID_CHARS_RE: RegExp; ++export declare const SPECIAL_CHARACTER_MAP: Record; ++export declare const BOOLEAN: ts.KeywordTypeNode; ++export declare const FALSE: ts.LiteralTypeNode; ++export declare const NEVER: ts.KeywordTypeNode; ++export declare const NULL: ts.LiteralTypeNode; ++export declare const NUMBER: ts.KeywordTypeNode; ++export declare const QUESTION_TOKEN: ts.PunctuationToken; ++export declare const STRING: ts.KeywordTypeNode; ++export declare const TRUE: ts.LiteralTypeNode; ++export declare const UNDEFINED: ts.KeywordTypeNode; ++export declare const UNKNOWN: ts.KeywordTypeNode; ++export interface AnnotatedSchemaObject { ++ const?: unknown; ++ default?: unknown; ++ deprecated?: boolean; ++ description?: string; ++ enum?: unknown[]; ++ example?: string; ++ format?: string; ++ nullable?: boolean; ++ summary?: string; ++ title?: string; ++ type?: string | string[]; ++} ++export declare function addJSDocComment(schemaObject: AnnotatedSchemaObject, node: ts.PropertySignature): void; ++export declare function oapiRef(path: string): ts.TypeNode; ++export interface AstToStringOptions { ++ fileName?: string; ++ sourceText?: string; ++ formatOptions?: ts.PrinterOptions; ++} ++export declare function astToString(ast: ts.Node | ts.Node[] | ts.TypeElement | ts.TypeElement[], options?: AstToStringOptions): string; ++export declare function stringToAST(source: string): unknown[]; ++export declare function tsDedupe(types: ts.TypeNode[]): ts.TypeNode[]; ++export declare const enumCache: Map; ++export declare function tsEnum(name: string, members: (string | number)[], metadata?: { ++ name?: string; ++ description?: string; ++}[], options?: { ++ export?: boolean; ++ shouldCache?: boolean; ++}): ts.EnumDeclaration; ++export declare function tsArrayLiteralExpression(name: string, elementType: ts.TypeNode, values: (string | number)[], options?: { ++ export?: boolean; ++ readonly?: boolean; ++ injectFooter?: ts.Node[]; ++}): ts.VariableStatement; ++export declare function tsEnumMember(value: string | number, metadata?: { ++ name?: string; ++ description?: string; ++}): ts.EnumMember; ++export declare function tsIntersection(types: ts.TypeNode[]): ts.TypeNode; ++export declare function tsIsPrimitive(type: ts.TypeNode): boolean; ++export declare function tsLiteral(value: unknown): ts.TypeNode; ++export declare function tsModifiers(modifiers: { ++ readonly?: boolean; ++ export?: boolean; ++}): ts.Modifier[]; ++export declare function tsNullable(types: ts.TypeNode[]): ts.TypeNode; ++export declare function tsOmit(type: ts.TypeNode, keys: string[]): ts.TypeNode; ++export declare function tsRecord(key: ts.TypeNode, value: ts.TypeNode): ts.TypeReferenceNode; ++export declare function tsPropertyIndex(index: string | number): ts.Identifier | ts.NumericLiteral | ts.StringLiteral; ++export declare function tsUnion(types: ts.TypeNode[]): ts.TypeNode; ++export declare function tsWithRequired(type: ts.TypeNode, keys: string[], injectFooter: ts.Node[]): ts.TypeNode; ++export declare function tsReadonlyArray(type: ts.TypeNode, injectFooter?: ts.Node[]): ts.TypeNode; +diff --git a/package/dist/lib/ts.js b/package/dist/lib/ts.js +new file mode 100644 +index 0000000000000000000000000000000000000000..7f46f68fe5a4b6fab4b5cba34602cf1268903d5c +--- /dev/null ++++ b/package/dist/lib/ts.js +@@ -0,0 +1,322 @@ ++import { parseRef } from "@redocly/openapi-core/lib/ref-utils.js"; ++import ts from "typescript"; ++export const JS_PROPERTY_INDEX_RE = /^[A-Za-z_$][A-Za-z_$0-9]*$/; ++export const JS_ENUM_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+(.)?/g; ++export const JS_PROPERTY_INDEX_INVALID_CHARS_RE = /[^A-Za-z_$0-9]+/g; ++export const SPECIAL_CHARACTER_MAP = { ++ "+": "Plus", ++}; ++export const BOOLEAN = ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword); ++export const FALSE = ts.factory.createLiteralTypeNode(ts.factory.createFalse()); ++export const NEVER = ts.factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword); ++export const NULL = ts.factory.createLiteralTypeNode(ts.factory.createNull()); ++export const NUMBER = ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword); ++export const QUESTION_TOKEN = ts.factory.createToken(ts.SyntaxKind.QuestionToken); ++export const STRING = ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword); ++export const TRUE = ts.factory.createLiteralTypeNode(ts.factory.createTrue()); ++export const UNDEFINED = ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword); ++export const UNKNOWN = ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword); ++const LB_RE = /\r?\n/g; ++const COMMENT_RE = /\*\//g; ++export function addJSDocComment(schemaObject, node) { ++ if (!schemaObject || typeof schemaObject !== "object" || Array.isArray(schemaObject)) { ++ return; ++ } ++ const output = []; ++ if (schemaObject.title) { ++ output.push(schemaObject.title.replace(LB_RE, "\n * ")); ++ } ++ if (schemaObject.summary) { ++ output.push(schemaObject.summary.replace(LB_RE, "\n * ")); ++ } ++ if (schemaObject.format) { ++ output.push(`Format: ${schemaObject.format}`); ++ } ++ if (schemaObject.deprecated) { ++ output.push("@deprecated"); ++ } ++ const supportedJsDocTags = ["description", "default", "example"]; ++ for (const field of supportedJsDocTags) { ++ const allowEmptyString = field === "default" || field === "example"; ++ if (schemaObject[field] === undefined) { ++ continue; ++ } ++ if (schemaObject[field] === "" && !allowEmptyString) { ++ continue; ++ } ++ const serialized = typeof schemaObject[field] === "object" ? JSON.stringify(schemaObject[field], null, 2) : schemaObject[field]; ++ output.push(`@${field} ${String(serialized).replace(LB_RE, "\n * ")}`); ++ } ++ if ("const" in schemaObject) { ++ output.push("@constant"); ++ } ++ if (schemaObject.enum) { ++ let type = "unknown"; ++ if (Array.isArray(schemaObject.type)) { ++ type = schemaObject.type.join("|"); ++ } ++ else if (typeof schemaObject.type === "string") { ++ type = schemaObject.type; ++ } ++ output.push(`@enum {${type}${schemaObject.nullable ? "|null" : ""}}`); ++ } ++ if (output.length) { ++ let text = output.length === 1 ++ ? `* ${output.join("\n")} ` ++ : `* ++ * ${output.join("\n * ")}\n `; ++ text = text.replace(COMMENT_RE, "*\\/"); ++ ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, text, true); ++ } ++} ++export function oapiRef(path) { ++ const { pointer } = parseRef(path); ++ if (pointer.length === 0) { ++ throw new Error(`Error parsing $ref: ${path}. Is this a valid $ref?`); ++ } ++ let t = ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(String(pointer[0]))); ++ if (pointer.length > 1) { ++ for (let i = 1; i < pointer.length; i++) { ++ if (i > 2 && i < pointer.length - 1 && pointer[i] === "properties") { ++ continue; ++ } ++ t = ts.factory.createIndexedAccessTypeNode(t, ts.factory.createLiteralTypeNode(typeof pointer[i] === "number" ++ ? ts.factory.createNumericLiteral(pointer[i]) ++ : ts.factory.createStringLiteral(pointer[i]))); ++ } ++ } ++ return t; ++} ++export function astToString(ast, options) { ++ const sourceFile = ts.createSourceFile(options?.fileName ?? "openapi-ts.ts", options?.sourceText ?? "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS); ++ sourceFile.statements = ts.factory.createNodeArray(Array.isArray(ast) ? ast : [ast]); ++ const printer = ts.createPrinter({ ++ newLine: ts.NewLineKind.LineFeed, ++ removeComments: false, ++ ...options?.formatOptions, ++ }); ++ return printer.printFile(sourceFile); ++} ++export function stringToAST(source) { ++ return ts.createSourceFile("stringInput", source, ts.ScriptTarget.ESNext, undefined, undefined).statements; ++} ++export function tsDedupe(types) { ++ const encounteredTypes = new Set(); ++ const filteredTypes = []; ++ for (const t of types) { ++ if (!("text" in (t.literal ?? t))) { ++ const { kind } = t.literal ?? t; ++ if (encounteredTypes.has(kind)) { ++ continue; ++ } ++ if (tsIsPrimitive(t)) { ++ encounteredTypes.add(kind); ++ } ++ } ++ filteredTypes.push(t); ++ } ++ return filteredTypes; ++} ++export const enumCache = new Map(); ++export function tsEnum(name, members, metadata, options) { ++ let enumName = sanitizeMemberName(name); ++ enumName = `${enumName[0].toUpperCase()}${enumName.substring(1)}`; ++ let key = ""; ++ if (options?.shouldCache) { ++ key = `${members ++ .slice(0) ++ .sort() ++ .map((v, i) => { ++ return `${metadata?.[i]?.name ?? String(v)}:${metadata?.[i]?.description || ""}`; ++ }) ++ .join(",")}`; ++ if (enumCache.has(key)) { ++ return enumCache.get(key); ++ } ++ } ++ const enumDeclaration = ts.factory.createEnumDeclaration(options ? tsModifiers({ export: options.export ?? false }) : undefined, enumName, members.map((value, i) => tsEnumMember(value, metadata?.[i]))); ++ options?.shouldCache && enumCache.set(key, enumDeclaration); ++ return enumDeclaration; ++} ++export function tsArrayLiteralExpression(name, elementType, values, options) { ++ let variableName = sanitizeMemberName(name); ++ variableName = `${variableName[0].toLowerCase()}${variableName.substring(1)}`; ++ const arrayType = options?.readonly ++ ? tsReadonlyArray(elementType, options.injectFooter) ++ : ts.factory.createArrayTypeNode(elementType); ++ return ts.factory.createVariableStatement(options ? tsModifiers({ export: options.export ?? false }) : undefined, ts.factory.createVariableDeclarationList([ ++ ts.factory.createVariableDeclaration(variableName, undefined, arrayType, ts.factory.createArrayLiteralExpression(values.map((value) => { ++ if (typeof value === "number") { ++ if (value < 0) { ++ return ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(value))); ++ } ++ else { ++ return ts.factory.createNumericLiteral(value); ++ } ++ } ++ else { ++ return ts.factory.createStringLiteral(value); ++ } ++ }))), ++ ], ts.NodeFlags.Const)); ++} ++function sanitizeMemberName(name) { ++ let sanitizedName = name.replace(JS_ENUM_INVALID_CHARS_RE, (c) => { ++ const last = c[c.length - 1]; ++ return JS_PROPERTY_INDEX_INVALID_CHARS_RE.test(last) ? "" : last.toUpperCase(); ++ }); ++ if (Number(name[0]) >= 0) { ++ sanitizedName = `Value${name}`; ++ } ++ return sanitizedName; ++} ++export function tsEnumMember(value, metadata = {}) { ++ let name = metadata.name ?? String(value); ++ if (!JS_PROPERTY_INDEX_RE.test(name)) { ++ if (Number(name[0]) >= 0) { ++ name = `Value${name}`.replace(".", "_"); ++ } ++ else if (name[0] === "-") { ++ name = `ValueMinus${name.slice(1)}`; ++ } ++ const invalidCharMatch = name.match(JS_PROPERTY_INDEX_INVALID_CHARS_RE); ++ if (invalidCharMatch) { ++ if (invalidCharMatch[0] === name) { ++ name = `"${name}"`; ++ } ++ else { ++ name = name.replace(JS_PROPERTY_INDEX_INVALID_CHARS_RE, (s) => { ++ return s in SPECIAL_CHARACTER_MAP ? SPECIAL_CHARACTER_MAP[s] : "_"; ++ }); ++ } ++ } ++ } ++ let member; ++ if (typeof value === "number") { ++ const literal = value < 0 ++ ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(value))) ++ : ts.factory.createNumericLiteral(value); ++ member = ts.factory.createEnumMember(name, literal); ++ } ++ else { ++ member = ts.factory.createEnumMember(name, ts.factory.createStringLiteral(value)); ++ } ++ if (metadata.description === undefined) { ++ return member; ++ } ++ return ts.addSyntheticLeadingComment(member, ts.SyntaxKind.SingleLineCommentTrivia, " ".concat(metadata.description.trim()), true); ++} ++export function tsIntersection(types) { ++ if (types.length === 0) { ++ return NEVER; ++ } ++ if (types.length === 1) { ++ return types[0]; ++ } ++ return ts.factory.createIntersectionTypeNode(tsDedupe(types)); ++} ++export function tsIsPrimitive(type) { ++ if (!type) { ++ return true; ++ } ++ return (ts.SyntaxKind[type.kind] === "BooleanKeyword" || ++ ts.SyntaxKind[type.kind] === "NeverKeyword" || ++ ts.SyntaxKind[type.kind] === "NullKeyword" || ++ ts.SyntaxKind[type.kind] === "NumberKeyword" || ++ ts.SyntaxKind[type.kind] === "StringKeyword" || ++ ts.SyntaxKind[type.kind] === "UndefinedKeyword" || ++ ("literal" in type && tsIsPrimitive(type.literal))); ++} ++export function tsLiteral(value) { ++ if (typeof value === "string") { ++ return ts.factory.createIdentifier(JSON.stringify(value)); ++ } ++ if (typeof value === "number") { ++ const literal = value < 0 ++ ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(value))) ++ : ts.factory.createNumericLiteral(value); ++ return ts.factory.createLiteralTypeNode(literal); ++ } ++ if (typeof value === "boolean") { ++ return value === true ? TRUE : FALSE; ++ } ++ if (value === null) { ++ return NULL; ++ } ++ if (Array.isArray(value)) { ++ if (value.length === 0) { ++ return ts.factory.createArrayTypeNode(NEVER); ++ } ++ return ts.factory.createTupleTypeNode(value.map((v) => tsLiteral(v))); ++ } ++ if (typeof value === "object") { ++ const keys = []; ++ for (const [k, v] of Object.entries(value)) { ++ keys.push(ts.factory.createPropertySignature(undefined, tsPropertyIndex(k), undefined, tsLiteral(v))); ++ } ++ return keys.length ? ts.factory.createTypeLiteralNode(keys) : tsRecord(STRING, NEVER); ++ } ++ return UNKNOWN; ++} ++export function tsModifiers(modifiers) { ++ const typeMods = []; ++ if (modifiers.export) { ++ typeMods.push(ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)); ++ } ++ if (modifiers.readonly) { ++ typeMods.push(ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)); ++ } ++ return typeMods; ++} ++export function tsNullable(types) { ++ return ts.factory.createUnionTypeNode([...types, NULL]); ++} ++export function tsOmit(type, keys) { ++ return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("Omit"), [ ++ type, ++ ts.factory.createUnionTypeNode(keys.map((k) => tsLiteral(k))), ++ ]); ++} ++export function tsRecord(key, value) { ++ return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("Record"), [key, value]); ++} ++export function tsPropertyIndex(index) { ++ if ((typeof index === "number" && !(index < 0)) || ++ (typeof index === "string" && String(Number(index)) === index && index[0] !== "-")) { ++ return ts.factory.createNumericLiteral(index); ++ } ++ return typeof index === "string" && JS_PROPERTY_INDEX_RE.test(index) ++ ? ts.factory.createIdentifier(index) ++ : ts.factory.createStringLiteral(String(index)); ++} ++export function tsUnion(types) { ++ if (types.length === 0) { ++ return NEVER; ++ } ++ if (types.length === 1) { ++ return types[0]; ++ } ++ return ts.factory.createUnionTypeNode(tsDedupe(types)); ++} ++export function tsWithRequired(type, keys, injectFooter) { ++ if (keys.length === 0) { ++ return type; ++ } ++ if (!injectFooter.some((node) => ts.isTypeAliasDeclaration(node) && node?.name?.escapedText === "WithRequired")) { ++ const helper = stringToAST("type WithRequired = T & { [P in K]-?: T[P] };")[0]; ++ injectFooter.push(helper); ++ } ++ return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("WithRequired"), [ ++ type, ++ tsUnion(keys.map((k) => tsLiteral(k))), ++ ]); ++} ++export function tsReadonlyArray(type, injectFooter) { ++ if (injectFooter && ++ !injectFooter.some((node) => ts.isTypeAliasDeclaration(node) && node?.name?.escapedText === "ReadonlyArray")) { ++ const helper = stringToAST("type ReadonlyArray = [Exclude] extends [any[]] ? Readonly> : Readonly[]>;")[0]; ++ injectFooter.push(helper); ++ } ++ return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("ReadonlyArray"), [type]); ++} ++//# sourceMappingURL=ts.js.map +\ No newline at end of file +diff --git a/package/dist/lib/ts.js.map b/package/dist/lib/ts.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..c61104cffa627a398cf6a54a381e5c521d6b8772 +--- /dev/null ++++ b/package/dist/lib/ts.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"ts.js","sourceRoot":"","sources":["../../src/lib/ts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EAAkD,MAAM,YAAY,CAAC;AAE5E,MAAM,CAAC,MAAM,oBAAoB,GAAG,4BAA4B,CAAC;AACjE,MAAM,CAAC,MAAM,wBAAwB,GAAG,sBAAsB,CAAC;AAC/D,MAAM,CAAC,MAAM,kCAAkC,GAAG,kBAAkB,CAAC;AACrE,MAAM,CAAC,MAAM,qBAAqB,GAA2B;IAC3D,GAAG,EAAE,MAAM;CAEZ,CAAC;AAEF,MAAM,CAAC,MAAM,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;AACtF,MAAM,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;AAChF,MAAM,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;AAC9E,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;AACpF,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;AACpF,MAAM,CAAC,MAAM,IAAI,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;AAC9E,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAC;AAC1F,MAAM,CAAC,MAAM,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,EAAE,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;AAEtF,MAAM,KAAK,GAAG,QAAQ,CAAC;AACvB,MAAM,UAAU,GAAG,OAAO,CAAC;AAqB3B,MAAM,UAAU,eAAe,CAAC,YAAmC,EAAE,IAA0B;IAC7F,IAAI,CAAC,YAAY,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,CAAC;QACrF,OAAO;IACT,CAAC;IACD,MAAM,MAAM,GAAa,EAAE,CAAC;IAG5B,IAAI,YAAY,CAAC,KAAK,EAAE,CAAC;QACvB,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC;IAC9D,CAAC;IACD,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC;QACzB,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC;IAChE,CAAC;IACD,IAAI,YAAY,CAAC,MAAM,EAAE,CAAC;QACxB,MAAM,CAAC,IAAI,CAAC,WAAW,YAAY,CAAC,MAAM,EAAE,CAAC,CAAC;IAChD,CAAC;IAID,IAAI,YAAY,CAAC,UAAU,EAAE,CAAC;QAC5B,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;IAC7B,CAAC;IAGD,MAAM,kBAAkB,GAAG,CAAC,aAAa,EAAE,SAAS,EAAE,SAAS,CAAU,CAAC;IAC1E,KAAK,MAAM,KAAK,IAAI,kBAAkB,EAAE,CAAC;QACvC,MAAM,gBAAgB,GAAG,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,SAAS,CAAC;QACpE,IAAI,YAAY,CAAC,KAAK,CAAC,KAAK,SAAS,EAAE,CAAC;YACtC,SAAS;QACX,CAAC;QACD,IAAI,YAAY,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACpD,SAAS;QACX,CAAC;QACD,MAAM,UAAU,GACd,OAAO,YAAY,CAAC,KAAK,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAC/G,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,MAAM,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAGD,IAAI,OAAO,IAAI,YAAY,EAAE,CAAC;QAC5B,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAC3B,CAAC;IAGD,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;QACtB,IAAI,IAAI,GAAG,SAAS,CAAC;QACrB,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;YACrC,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACrC,CAAC;aAAM,IAAI,OAAO,YAAY,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACjD,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC;QAC3B,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,UAAU,IAAI,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACxE,CAAC;IAID,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAClB,IAAI,IAAI,GACN,MAAM,CAAC,MAAM,KAAK,CAAC;YACjB,CAAC,CAAC,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG;YAC3B,CAAC,CAAC;KACL,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QAExC,EAAE,CAAC,0BAA0B,CACF,IAAI,EACJ,EAAE,CAAC,UAAU,CAAC,sBAAsB,EACpC,IAAI,EACJ,IAAI,CAC9B,CAAC;IACJ,CAAC;AACH,CAAC;AAGD,MAAM,UAAU,OAAO,CAAC,IAAY;IAClC,MAAM,EAAE,OAAO,EAAE,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,uBAAuB,IAAI,yBAAyB,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,CAAC,GAAoD,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACzF,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAChD,CAAC;IACF,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAGxC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,KAAK,YAAY,EAAE,CAAC;gBACnE,SAAS;YACX,CAAC;YACD,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,2BAA2B,CACxC,CAAC,EACD,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAC9B,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ;gBAC5B,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC7C,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,CAAW,CAAC,CACzD,CACF,CAAC;QACJ,CAAC;IACH,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AASD,MAAM,UAAU,WAAW,CACzB,GAA4D,EAC5D,OAA4B;IAE5B,MAAM,UAAU,GAAG,EAAE,CAAC,gBAAgB,CACpC,OAAO,EAAE,QAAQ,IAAI,eAAe,EACpC,OAAO,EAAE,UAAU,IAAI,EAAE,EACzB,EAAE,CAAC,YAAY,CAAC,MAAM,EACtB,KAAK,EACL,EAAE,CAAC,UAAU,CAAC,EAAE,CACjB,CAAC;IAGF,UAAU,CAAC,UAAU,GAAG,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAErF,MAAM,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC;QAC/B,OAAO,EAAE,EAAE,CAAC,WAAW,CAAC,QAAQ;QAChC,cAAc,EAAE,KAAK;QACrB,GAAG,OAAO,EAAE,aAAa;KAC1B,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;AACvC,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,OAAO,EAAE,CAAC,gBAAgB,CACF,aAAa,EACb,MAAM,EACN,EAAE,CAAC,YAAY,CAAC,MAAM,EACtB,SAAS,EACT,SAAS,CAChC,CAAC,UAAiB,CAAC;AACtB,CAAC;AAMD,MAAM,UAAU,QAAQ,CAAC,KAAoB;IAC3C,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAC3C,MAAM,aAAa,GAAkB,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC;QAEtB,IAAI,CAAC,CAAC,MAAM,IAAI,CAAE,CAAqB,CAAC,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;YACvD,MAAM,EAAE,IAAI,EAAE,GAAI,CAAqB,CAAC,OAAO,IAAI,CAAC,CAAC;YACrD,IAAI,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC/B,SAAS;YACX,CAAC;YACD,IAAI,aAAa,CAAC,CAAC,CAAC,EAAE,CAAC;gBACrB,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC7B,CAAC;QACH,CAAC;QACD,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,GAAG,EAA8B,CAAC;AAG/D,MAAM,UAAU,MAAM,CACpB,IAAY,EACZ,OAA4B,EAC5B,QAAoD,EACpD,OAAqD;IAErD,IAAI,QAAQ,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACxC,QAAQ,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;IAClE,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,IAAI,OAAO,EAAE,WAAW,EAAE,CAAC;QACzB,GAAG,GAAG,GAAG,OAAO;aACb,KAAK,CAAC,CAAC,CAAC;aACR,IAAI,EAAE;aACN,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;YACZ,OAAO,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,IAAI,MAAM,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,IAAI,EAAE,EAAE,CAAC;QACnF,CAAC,CAAC;aACD,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACf,IAAI,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YACvB,OAAO,SAAS,CAAC,GAAG,CAAC,GAAG,CAAuB,CAAC;QAClD,CAAC;IACH,CAAC;IACD,MAAM,eAAe,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CACtC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,EACtE,QAAQ,EACR,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAC9E,CAAC;IACF,OAAO,EAAE,WAAW,IAAI,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;IAC5D,OAAO,eAAe,CAAC;AACzB,CAAC;AAGD,MAAM,UAAU,wBAAwB,CACtC,IAAY,EACZ,WAAwB,EACxB,MAA2B,EAC3B,OAA4E;IAE5E,IAAI,YAAY,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAC5C,YAAY,GAAG,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;IAE9E,MAAM,SAAS,GAAG,OAAO,EAAE,QAAQ;QACjC,CAAC,CAAC,eAAe,CAAC,WAAW,EAAE,OAAO,CAAC,YAAY,CAAC;QACpD,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAEhD,OAAO,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACvC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,EACtE,EAAE,CAAC,OAAO,CAAC,6BAA6B,CACtC;QACE,EAAE,CAAC,OAAO,CAAC,yBAAyB,CAClC,YAAY,EACZ,SAAS,EACT,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,4BAA4B,CACrC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;YACnB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC9B,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;oBACd,OAAO,EAAE,CAAC,OAAO,CAAC,2BAA2B,CAC3C,EAAE,CAAC,UAAU,CAAC,UAAU,EACxB,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CACjD,CAAC;gBACJ,CAAC;qBAAM,CAAC;oBACN,OAAO,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC;gBAChD,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;YAC/C,CAAC;QACH,CAAC,CAAC,CACH,CACF;KACF,EACD,EAAE,CAAC,SAAS,CAAC,KAAK,CACnB,CACF,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAY;IACtC,IAAI,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,wBAAwB,EAAE,CAAC,CAAC,EAAE,EAAE;QAC/D,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC7B,OAAO,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;IACjF,CAAC,CAAC,CAAC;IACH,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,aAAa,GAAG,QAAQ,IAAI,EAAE,CAAC;IACjC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAGD,MAAM,UAAU,YAAY,CAAC,KAAsB,EAAE,WAAoD,EAAE;IACzG,IAAI,IAAI,GAAG,QAAQ,CAAC,IAAI,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1C,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACrC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,IAAI,GAAG,QAAQ,IAAI,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QAC1C,CAAC;aAAM,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;YAC3B,IAAI,GAAG,aAAa,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QACtC,CAAC;QAED,MAAM,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACxE,IAAI,gBAAgB,EAAE,CAAC;YACrB,IAAI,gBAAgB,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;gBACjC,IAAI,GAAG,IAAI,IAAI,GAAG,CAAC;YACrB,CAAC;iBAAM,CAAC;gBACN,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,kCAAkC,EAAE,CAAC,CAAC,EAAE,EAAE;oBAC5D,OAAO,CAAC,IAAI,qBAAqB,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;gBACrE,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,MAAqB,CAAC;IAC1B,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GACX,KAAK,GAAG,CAAC;YACP,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,2BAA2B,CACpC,EAAE,CAAC,UAAU,CAAC,UAAU,EACxB,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CACjD;YACH,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC;QAE7C,MAAM,GAAG,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;SAAM,CAAC;QACN,MAAM,GAAG,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,CAAC;IACpF,CAAC;IAED,IAAI,QAAQ,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;QACvC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,OAAO,EAAE,CAAC,0BAA0B,CAClC,MAAM,EACN,EAAE,CAAC,UAAU,CAAC,uBAAuB,EACrC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,EACvC,IAAI,CACL,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,cAAc,CAAC,KAAoB;IACjD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,EAAE,CAAC,OAAO,CAAC,0BAA0B,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;AAChE,CAAC;AAGD,MAAM,UAAU,aAAa,CAAC,IAAiB;IAC7C,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,CACL,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,gBAAgB;QAC7C,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,cAAc;QAC3C,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,aAAa;QAC1C,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,eAAe;QAC5C,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,eAAe;QAC5C,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,kBAAkB;QAC/C,CAAC,SAAS,IAAI,IAAI,IAAI,aAAa,CAAC,IAAI,CAAC,OAA0B,CAAC,CAAC,CACtE,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAE9B,OAAO,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAA2B,CAAC;IACtF,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,OAAO,GACX,KAAK,GAAG,CAAC;YACP,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,2BAA2B,CACpC,EAAE,CAAC,UAAU,CAAC,UAAU,EACxB,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CACjD;YACH,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC;QAC7C,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC;IACnD,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE,CAAC;QAC/B,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACvC,CAAC;IACD,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAU,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjF,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,IAAI,GAAqB,EAAE,CAAC;QAClC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YAC3C,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,CAAC,CAAC,EAClB,SAAS,EACT,SAAS,CAAC,CAAC,CAAC,CACjC,CACF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAGD,MAAM,UAAU,WAAW,CAAC,SAG3B;IACC,MAAM,QAAQ,GAAkB,EAAE,CAAC;IACnC,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,SAAS,CAAC,QAAQ,EAAE,CAAC;QACvB,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAGD,MAAM,UAAU,UAAU,CAAC,KAAoB;IAC7C,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;AAC1D,CAAC;AAGD,MAAM,UAAU,MAAM,CAAC,IAAiB,EAAE,IAAc;IACtD,OAAO,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,EAAE;QAC7E,IAAI;QACJ,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;KAC9D,CAAC,CAAC;AACL,CAAC;AAGD,MAAM,UAAU,QAAQ,CAAC,GAAgB,EAAE,KAAkB;IAC3D,OAAO,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;AACjG,CAAC;AAGD,MAAM,UAAU,eAAe,CAAC,KAAsB;IACpD,IACE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAC3C,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,EAClF,CAAC;QACD,OAAO,EAAE,CAAC,OAAO,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,oBAAoB,CAAC,IAAI,CAAC,KAAK,CAAC;QAClE,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,KAAK,CAAC;QACpC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACpD,CAAC;AAGD,MAAM,UAAU,OAAO,CAAC,KAAoB;IAC1C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IACD,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;AACzD,CAAC;AAGD,MAAM,UAAU,cAAc,CAC5B,IAAiB,EACjB,IAAc,EACd,YAAuB;IAEvB,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IAGD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,IAAI,EAAE,WAAW,KAAK,cAAc,CAAC,EAAE,CAAC;QAChH,MAAM,MAAM,GAAG,WAAW,CAAC,qEAAqE,CAAC,CAAC,CAAC,CAAQ,CAAC;QAC5G,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC;IAED,OAAO,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,cAAc,CAAC,EAAE;QACrF,IAAI;QACJ,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;KACvC,CAAC,CAAC;AACL,CAAC;AAOD,MAAM,UAAU,eAAe,CAAC,IAAiB,EAAE,YAAwB;IACzE,IACE,YAAY;QACZ,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,IAAI,EAAE,WAAW,KAAK,eAAe,CAAC,EAC5G,CAAC;QACD,MAAM,MAAM,GAAG,WAAW,CACxB,wIAAwI,CACzI,CAAC,CAAC,CAAQ,CAAC;QACZ,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,eAAe,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AAClG,CAAC"} +\ No newline at end of file +diff --git a/package/dist/lib/utils.d.ts b/package/dist/lib/utils.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..ef06148a9586058d0779e17e74013a850bb3eb85 +--- /dev/null ++++ b/package/dist/lib/utils.d.ts +@@ -0,0 +1,26 @@ ++import c from "ansi-colors"; ++import ts from "typescript"; ++import type { DiscriminatorObject, OpenAPI3, OpenAPITSOptions } from "../types.js"; ++export { c }; ++export declare function createDiscriminatorProperty(discriminator: DiscriminatorObject, { path, readonly }: { ++ path: string; ++ readonly?: boolean; ++}): ts.TypeElement; ++export declare function createRef(parts: (number | string | undefined | null)[]): string; ++export declare function debug(msg: string, group?: string, time?: number): void; ++export declare function error(msg: string): void; ++export declare function formatTime(t: number): string; ++export declare function getEntries(obj: ArrayLike | Record, options?: { ++ alphabetize?: boolean; ++ excludeDeprecated?: boolean; ++}): [string, T][]; ++export declare function resolveRef(schema: any, $ref: string, { silent, visited }: { ++ silent: boolean; ++ visited?: string[]; ++}): T | undefined; ++export declare function scanDiscriminators(schema: OpenAPI3, options: OpenAPITSOptions): { ++ objects: Record; ++ refsHandled: string[]; ++}; ++export declare function walk(obj: unknown, cb: (value: Record, path: (string | number)[]) => void, path?: (string | number)[]): void; ++export declare function warn(msg: string, silent?: boolean): void; +diff --git a/package/dist/lib/utils.js b/package/dist/lib/utils.js +new file mode 100644 +index 0000000000000000000000000000000000000000..bede54e75eee62b7ecadc33fd9f502ab101a8498 +--- /dev/null ++++ b/package/dist/lib/utils.js +@@ -0,0 +1,260 @@ ++import { escapePointer, parseRef } from "@redocly/openapi-core/lib/ref-utils.js"; ++import c from "ansi-colors"; ++import supportsColor from "supports-color"; ++import ts from "typescript"; ++import { tsLiteral, tsModifiers, tsPropertyIndex } from "./ts.js"; ++if (!supportsColor.stdout || supportsColor.stdout.hasBasic === false) { ++ c.enabled = false; ++} ++const DEBUG_GROUPS = { ++ redoc: c.cyanBright, ++ lint: c.yellowBright, ++ bundle: c.magentaBright, ++ ts: c.blueBright, ++}; ++export { c }; ++export function createDiscriminatorProperty(discriminator, { path, readonly = false }) { ++ let value = parseRef(path).pointer.pop(); ++ if (discriminator.mapping) { ++ const matchedValue = Object.entries(discriminator.mapping).find(([, v]) => (!v.startsWith("#") && v === value) || (v.startsWith("#") && parseRef(v).pointer.pop() === value)); ++ if (matchedValue) { ++ value = matchedValue[0]; ++ } ++ } ++ return ts.factory.createPropertySignature(tsModifiers({ ++ readonly, ++ }), tsPropertyIndex(discriminator.propertyName), undefined, tsLiteral(value)); ++} ++export function createRef(parts) { ++ let pointer = "#"; ++ for (const part of parts) { ++ if (part === undefined || part === null || part === "") { ++ continue; ++ } ++ const maybeRef = parseRef(String(part)).pointer; ++ if (maybeRef.length) { ++ for (const refPart of maybeRef) { ++ pointer += `/${escapePointer(refPart)}`; ++ } ++ } ++ else { ++ pointer += `/${escapePointer(part)}`; ++ } ++ } ++ return pointer; ++} ++export function debug(msg, group, time) { ++ if (process.env.DEBUG && ++ (!group || ++ process.env.DEBUG === "*" || ++ process.env.DEBUG === "openapi-ts:*" || ++ process.env.DEBUG.toLocaleLowerCase() === `openapi-ts:${group.toLocaleLowerCase()}`)) { ++ const groupColor = (group && DEBUG_GROUPS[group]) || c.whiteBright; ++ const groupName = groupColor(`openapi-ts:${group ?? "info"}`); ++ let timeFormatted = ""; ++ if (typeof time === "number") { ++ timeFormatted = c.green(` ${formatTime(time)} `); ++ } ++ console.debug(` ${c.bold(groupName)}${timeFormatted}${msg}`); ++ } ++} ++export function error(msg) { ++ console.error(c.red(` ✘ ${msg}`)); ++} ++export function formatTime(t) { ++ if (typeof t === "number") { ++ if (t < 1000) { ++ return `${Math.round(10 * t) / 10}ms`; ++ } ++ if (t < 60000) { ++ return `${Math.round(t / 100) / 10}s`; ++ } ++ return `${Math.round(t / 6000) / 10}m`; ++ } ++ return t; ++} ++export function getEntries(obj, options) { ++ let entries = Object.entries(obj); ++ if (options?.alphabetize) { ++ entries.sort(([a], [b]) => a.localeCompare(b, "en-us", { numeric: true })); ++ } ++ if (options?.excludeDeprecated) { ++ entries = entries.filter(([, v]) => !(v && typeof v === "object" && "deprecated" in v && v.deprecated)); ++ } ++ return entries; ++} ++export function resolveRef(schema, $ref, { silent = false, visited = [] }) { ++ const { pointer } = parseRef($ref); ++ if (!pointer.length) { ++ return undefined; ++ } ++ let node = schema; ++ for (const key of pointer) { ++ if (node && typeof node === "object" && node[key]) { ++ node = node[key]; ++ } ++ else { ++ warn(`Could not resolve $ref "${$ref}"`, silent); ++ return undefined; ++ } ++ } ++ if (node && typeof node === "object" && node.$ref) { ++ if (visited.includes(node.$ref)) { ++ warn(`Could not resolve circular $ref "${$ref}"`, silent); ++ return undefined; ++ } ++ return resolveRef(schema, node.$ref, { ++ silent, ++ visited: [...visited, node.$ref], ++ }); ++ } ++ return node; ++} ++function createDiscriminatorEnum(values, prevSchema) { ++ return { ++ type: "string", ++ enum: values, ++ description: prevSchema?.description ++ ? `${prevSchema.description} (enum property replaced by openapi-typescript)` ++ : "discriminator enum property added by openapi-typescript", ++ }; ++} ++function patchDiscriminatorEnum(schema, ref, values, discriminator, discriminatorRef, options) { ++ const resolvedSchema = resolveRef(schema, ref, { ++ silent: options.silent ?? false, ++ }); ++ if (resolvedSchema?.allOf) { ++ resolvedSchema.allOf.push({ ++ type: "object", ++ required: [discriminator.propertyName], ++ properties: { ++ [discriminator.propertyName]: createDiscriminatorEnum(values), ++ }, ++ }); ++ return true; ++ } ++ else if (typeof resolvedSchema === "object" && "type" in resolvedSchema && resolvedSchema.type === "object") { ++ if (!resolvedSchema.properties) { ++ resolvedSchema.properties = {}; ++ } ++ if (!resolvedSchema.required) { ++ resolvedSchema.required = [discriminator.propertyName]; ++ } ++ else if (!resolvedSchema.required.includes(discriminator.propertyName)) { ++ resolvedSchema.required.push(discriminator.propertyName); ++ } ++ resolvedSchema.properties[discriminator.propertyName] = createDiscriminatorEnum(values, resolvedSchema.properties[discriminator.propertyName]); ++ return true; ++ } ++ warn(`Discriminator mapping has an invalid schema (neither an object schema nor an allOf array): ${ref} => ${values.join(", ")} (Discriminator: ${discriminatorRef})`, options.silent); ++ return false; ++} ++export function scanDiscriminators(schema, options) { ++ const objects = {}; ++ const refsHandled = []; ++ walk(schema, (obj, path) => { ++ const discriminator = obj?.discriminator; ++ if (!discriminator?.propertyName) { ++ return; ++ } ++ const ref = createRef(path); ++ objects[ref] = discriminator; ++ if (!obj?.oneOf || !Array.isArray(obj.oneOf)) { ++ return; ++ } ++ const oneOf = obj.oneOf; ++ const mapping = {}; ++ for (const item of oneOf) { ++ if ("$ref" in item) { ++ const value = item.$ref.split("/").pop(); ++ if (value) { ++ if (!mapping[item.$ref]) { ++ mapping[item.$ref] = { inferred: value }; ++ } ++ else { ++ mapping[item.$ref].inferred = value; ++ } ++ } ++ } ++ } ++ if (discriminator.mapping) { ++ for (const mappedValue in discriminator.mapping) { ++ const mappedRef = discriminator.mapping[mappedValue]; ++ if (!mappedRef) { ++ continue; ++ } ++ if (!mapping[mappedRef]?.defined) { ++ mapping[mappedRef] = { defined: [] }; ++ } ++ mapping[mappedRef].defined?.push(mappedValue); ++ } ++ } ++ for (const [mappedRef, { inferred, defined }] of Object.entries(mapping)) { ++ if (refsHandled.includes(mappedRef)) { ++ continue; ++ } ++ if (!inferred && !defined) { ++ continue; ++ } ++ const mappedValues = defined ?? [inferred]; ++ if (patchDiscriminatorEnum(schema, mappedRef, mappedValues, discriminator, ref, options)) { ++ refsHandled.push(mappedRef); ++ } ++ } ++ }); ++ walk(schema, (obj, path) => { ++ if (!obj || !Array.isArray(obj.allOf)) { ++ return; ++ } ++ for (const item of obj.allOf) { ++ if ("$ref" in item) { ++ if (!objects[item.$ref]) { ++ return; ++ } ++ const ref = createRef(path); ++ const discriminator = objects[item.$ref]; ++ const mappedValues = []; ++ if (discriminator.mapping) { ++ for (const mappedValue in discriminator.mapping) { ++ if (discriminator.mapping[mappedValue] === ref) { ++ mappedValues.push(mappedValue); ++ } ++ } ++ if (mappedValues.length > 0) { ++ if (patchDiscriminatorEnum(schema, ref, mappedValues, discriminator, item.$ref, options)) { ++ refsHandled.push(ref); ++ } ++ } ++ } ++ objects[ref] = { ++ ...objects[item.$ref], ++ }; ++ } ++ else if (item.discriminator?.propertyName) { ++ objects[createRef(path)] = { ...item.discriminator }; ++ } ++ } ++ }); ++ return { objects, refsHandled }; ++} ++export function walk(obj, cb, path = []) { ++ if (!obj || typeof obj !== "object") { ++ return; ++ } ++ if (Array.isArray(obj)) { ++ for (let i = 0; i < obj.length; i++) { ++ walk(obj[i], cb, path.concat(i)); ++ } ++ return; ++ } ++ cb(obj, path); ++ for (const k of Object.keys(obj)) { ++ walk(obj[k], cb, path.concat(k)); ++ } ++} ++export function warn(msg, silent = false) { ++ if (!silent) { ++ console.warn(c.yellow(` ⚠ ${msg}`)); ++ } ++} ++//# sourceMappingURL=utils.js.map +\ No newline at end of file +diff --git a/package/dist/lib/utils.js.map b/package/dist/lib/utils.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..96db2780c2c0d15386fb7d94e6a268cf9340d96b +--- /dev/null ++++ b/package/dist/lib/utils.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/lib/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AACjF,OAAO,CAAC,MAAM,aAAa,CAAC;AAC5B,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,MAAM,YAAY,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAElE,IAAI,CAAC,aAAa,CAAC,MAAM,IAAI,aAAa,CAAC,MAAM,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC;IACrE,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC;AACpB,CAAC;AAED,MAAM,YAAY,GAAgD;IAChE,KAAK,EAAE,CAAC,CAAC,UAAU;IACnB,IAAI,EAAE,CAAC,CAAC,YAAY;IACpB,MAAM,EAAE,CAAC,CAAC,aAAa;IACvB,EAAE,EAAE,CAAC,CAAC,UAAU;CACjB,CAAC;AAEF,OAAO,EAAE,CAAC,EAAE,CAAC;AAGb,MAAM,UAAU,2BAA2B,CACzC,aAAkC,EAClC,EAAE,IAAI,EAAE,QAAQ,GAAG,KAAK,EAAwC;IAGhE,IAAI,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;IAEzC,IAAI,aAAa,CAAC,OAAO,EAAE,CAAC;QAE1B,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,IAAI,CAC7D,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,KAAK,CAAC,CAC7G,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,KAAK,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IACD,OAAO,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACnB,WAAW,CAAC;QAC9B,QAAQ;KACT,CAAC,EACkB,eAAe,CAAC,aAAa,CAAC,YAAY,CAAC,EAC3C,SAAS,EACT,SAAS,CAAC,KAAK,CAAC,CACrC,CAAC;AACJ,CAAC;AAGD,MAAM,UAAU,SAAS,CAAC,KAA6C;IACrE,IAAI,OAAO,GAAG,GAAG,CAAC;IAClB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;YACvD,SAAS;QACX,CAAC;QACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;QAChD,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;YACpB,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAC/B,OAAO,IAAI,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC;YAC1C,CAAC;QACH,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,IAAI,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAGD,MAAM,UAAU,KAAK,CAAC,GAAW,EAAE,KAAc,EAAE,IAAa;IAC9D,IACE,OAAO,CAAC,GAAG,CAAC,KAAK;QACjB,CAAC,CAAC,KAAK;YACL,OAAO,CAAC,GAAG,CAAC,KAAK,KAAK,GAAG;YACzB,OAAO,CAAC,GAAG,CAAC,KAAK,KAAK,cAAc;YACpC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,iBAAiB,EAAE,KAAK,cAAc,KAAK,CAAC,iBAAiB,EAAE,EAAE,CAAC,EACtF,CAAC;QACD,MAAM,UAAU,GAAG,CAAC,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC;QACnE,MAAM,SAAS,GAAG,UAAU,CAAC,cAAc,KAAK,IAAI,MAAM,EAAE,CAAC,CAAC;QAC9D,IAAI,aAAa,GAAG,EAAE,CAAC;QACvB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACnD,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,aAAa,GAAG,GAAG,EAAE,CAAC,CAAC;IAChE,CAAC;AACH,CAAC;AAGD,MAAM,UAAU,KAAK,CAAC,GAAW;IAC/B,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC,CAAC;AACrC,CAAC;AAGD,MAAM,UAAU,UAAU,CAAC,CAAS;IAClC,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE,CAAC;QAC1B,IAAI,CAAC,GAAG,IAAI,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC;QACxC,CAAC;QACD,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC;YACd,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC;QACxC,CAAC;QACD,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC;IACzC,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAGD,MAAM,UAAU,UAAU,CACxB,GAAqC,EACrC,OAGC;IAED,IAAI,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAClC,IAAI,OAAO,EAAE,WAAW,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,OAAO,EAAE,iBAAiB,EAAE,CAAC;QAC/B,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,YAAY,IAAI,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;IAC1G,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAGD,MAAM,UAAU,UAAU,CACxB,MAAW,EACX,IAAY,EACZ,EAAE,MAAM,GAAG,KAAK,EAAE,OAAO,GAAG,EAAE,EAA2C;IAEzE,MAAM,EAAE,OAAO,EAAE,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QACpB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,IAAI,GAAG,MAAM,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE,CAAC;QAC1B,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAClD,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,2BAA2B,IAAI,GAAG,EAAE,MAAM,CAAC,CAAC;YACjD,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IAGD,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;QAClD,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,IAAI,CAAC,oCAAoC,IAAI,GAAG,EAAE,MAAM,CAAC,CAAC;YAC1D,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,UAAU,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE;YACnC,MAAM;YACN,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC;SACjC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,uBAAuB,CAAC,MAAgB,EAAE,UAAyB;IAC1E,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,IAAI,EAAE,MAAM;QACZ,WAAW,EAAE,UAAU,EAAE,WAAW;YAClC,CAAC,CAAC,GAAG,UAAU,CAAC,WAAW,iDAAiD;YAC5E,CAAC,CAAC,yDAAyD;KAC9D,CAAC;AACJ,CAAC;AAGD,SAAS,sBAAsB,CAC7B,MAAoB,EACpB,GAAW,EACX,MAAgB,EAChB,aAAkC,EAClC,gBAAwB,EACxB,OAAyB;IAEzB,MAAM,cAAc,GAAG,UAAU,CAAe,MAAM,EAAE,GAAG,EAAE;QAC3D,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK;KAChC,CAAC,CAAC;IAEH,IAAI,cAAc,EAAE,KAAK,EAAE,CAAC;QAE1B,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC;YACxB,IAAI,EAAE,QAAQ;YAEd,QAAQ,EAAE,CAAC,aAAa,CAAC,YAAY,CAAC;YACtC,UAAU,EAAE;gBACV,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE,uBAAuB,CAAC,MAAM,CAAC;aAC9D;SACF,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IACd,CAAC;SAAM,IAAI,OAAO,cAAc,KAAK,QAAQ,IAAI,MAAM,IAAI,cAAc,IAAI,cAAc,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAE9G,IAAI,CAAC,cAAc,CAAC,UAAU,EAAE,CAAC;YAC/B,cAAc,CAAC,UAAU,GAAG,EAAE,CAAC;QACjC,CAAC;QAGD,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC;YAC7B,cAAc,CAAC,QAAQ,GAAG,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;QACzD,CAAC;aAAM,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE,CAAC;YACzE,cAAc,CAAC,QAAQ,CAAC,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;QAC3D,CAAC;QAGD,cAAc,CAAC,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,GAAG,uBAAuB,CAC7E,MAAM,EACN,cAAc,CAAC,UAAU,CAAC,aAAa,CAAC,YAAY,CAAiB,CACtE,CAAC;QAEF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CACF,8FAA8F,GAAG,OAAO,MAAM,CAAC,IAAI,CACjH,IAAI,CACL,oBAAoB,gBAAgB,GAAG,EACxC,OAAO,CAAC,MAAM,CACf,CAAC;IAEF,OAAO,KAAK,CAAC;AACf,CAAC;AAKD,MAAM,UAAU,kBAAkB,CAAC,MAAgB,EAAE,OAAyB;IAE5E,MAAM,OAAO,GAAwC,EAAE,CAAC;IAGxD,MAAM,WAAW,GAAa,EAAE,CAAC;IAGjC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,aAAa,GAAG,GAAG,EAAE,aAAgD,CAAC;QAC5E,IAAI,CAAC,aAAa,EAAE,YAAY,EAAE,CAAC;YACjC,OAAO;QACT,CAAC;QAGD,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QAE5B,OAAO,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC;QAI7B,IAAI,CAAC,GAAG,EAAE,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7C,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAuC,GAAG,CAAC,KAAK,CAAC;QAC5D,MAAM,OAAO,GAAiC,EAAE,CAAC;QAGjD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBAEnB,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;gBAEzC,IAAI,KAAK,EAAE,CAAC;oBACV,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;wBACxB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;oBAC3C,CAAC;yBAAM,CAAC;wBACN,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,GAAG,KAAK,CAAC;oBACtC,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAGD,IAAI,aAAa,CAAC,OAAO,EAAE,CAAC;YAC1B,KAAK,MAAM,WAAW,IAAI,aAAa,CAAC,OAAO,EAAE,CAAC;gBAChD,MAAM,SAAS,GAAG,aAAa,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;gBACrD,IAAI,CAAC,SAAS,EAAE,CAAC;oBACf,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC;oBAEjC,OAAO,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;gBACvC,CAAC;gBAED,OAAO,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;YAChD,CAAC;QACH,CAAC;QAED,KAAK,MAAM,CAAC,SAAS,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;YACzE,IAAI,WAAW,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;gBACpC,SAAS;YACX,CAAC;YAED,IAAI,CAAC,QAAQ,IAAI,CAAC,OAAO,EAAE,CAAC;gBAC1B,SAAS;YACX,CAAC;YAMD,MAAM,YAAY,GAAG,OAAO,IAAI,CAAC,QAAS,CAAC,CAAC;YAE5C,IACE,sBAAsB,CAAC,MAAiC,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,EAAE,OAAO,CAAC,EAC/G,CAAC;gBACD,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;IAKH,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;YACtC,OAAO;QACT,CAAC;QAED,KAAK,MAAM,IAAI,IAAK,GAAW,CAAC,KAAK,EAAE,CAAC;YACtC,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBACnB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;oBACxB,OAAO;gBACT,CAAC;gBAED,MAAM,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;gBAC5B,MAAM,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACzC,MAAM,YAAY,GAAa,EAAE,CAAC;gBAElC,IAAI,aAAa,CAAC,OAAO,EAAE,CAAC;oBAC1B,KAAK,MAAM,WAAW,IAAI,aAAa,CAAC,OAAO,EAAE,CAAC;wBAChD,IAAI,aAAa,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,GAAG,EAAE,CAAC;4BAC/C,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;wBACjC,CAAC;oBACH,CAAC;oBAED,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;wBAC5B,IACE,sBAAsB,CACpB,MAAiC,EACjC,GAAG,EACH,YAAY,EACZ,aAAa,EACb,IAAI,CAAC,IAAI,EACT,OAAO,CACR,EACD,CAAC;4BACD,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;wBACxB,CAAC;oBACH,CAAC;gBACH,CAAC;gBAED,OAAO,CAAC,GAAG,CAAC,GAAG;oBACb,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC;iBACtB,CAAC;YACJ,CAAC;iBAAM,IAAI,IAAI,CAAC,aAAa,EAAE,YAAY,EAAE,CAAC;gBAC5C,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;YACvD,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;AAClC,CAAC;AAGD,MAAM,UAAU,IAAI,CAClB,GAAY,EACZ,EAAuE,EACvE,OAA4B,EAAE;IAE9B,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACpC,OAAO;IACT,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACpC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QACnC,CAAC;QACD,OAAO;IACT,CAAC;IACD,EAAE,CAAC,GAA8B,EAAE,IAAI,CAAC,CAAC;IACzC,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACjC,IAAI,CAAE,GAA+B,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IAChE,CAAC;AACH,CAAC;AAGD,MAAM,UAAU,IAAI,CAAC,GAAW,EAAE,MAAM,GAAG,KAAK;IAC9C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC,CAAC;IACvC,CAAC;AACH,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/components-object.d.ts b/package/dist/transform/components-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..7eeae8a73e573f1d51ce8cd199e26d82b9dd79bf +--- /dev/null ++++ b/package/dist/transform/components-object.d.ts +@@ -0,0 +1,4 @@ ++import ts from "typescript"; ++import type { ComponentsObject, GlobalContext } from "../types.js"; ++export default function transformComponentsObject(componentsObject: ComponentsObject, ctx: GlobalContext): ts.Node[]; ++export declare function singularizeComponentKey(key: `x-${string}` | "schemas" | "responses" | "parameters" | "requestBodies" | "headers" | "pathItems"): string; +diff --git a/package/dist/transform/components-object.js b/package/dist/transform/components-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..04e66ecb5918e3dba848e73061cdb4f601611bed +--- /dev/null ++++ b/package/dist/transform/components-object.js +@@ -0,0 +1,87 @@ ++import ts from "typescript"; ++import * as changeCase from "change-case"; ++import { performance } from "node:perf_hooks"; ++import { NEVER, QUESTION_TOKEN, addJSDocComment, tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef, debug, getEntries } from "../lib/utils.js"; ++import transformHeaderObject from "./header-object.js"; ++import transformParameterObject from "./parameter-object.js"; ++import transformPathItemObject from "./path-item-object.js"; ++import transformRequestBodyObject from "./request-body-object.js"; ++import transformResponseObject from "./response-object.js"; ++import transformSchemaObject from "./schema-object.js"; ++const transformers = { ++ schemas: transformSchemaObject, ++ responses: transformResponseObject, ++ parameters: transformParameterObject, ++ requestBodies: transformRequestBodyObject, ++ headers: transformHeaderObject, ++ pathItems: transformPathItemObject, ++}; ++export default function transformComponentsObject(componentsObject, ctx) { ++ const type = []; ++ const rootTypeAliases = {}; ++ for (const key of Object.keys(transformers)) { ++ const componentT = performance.now(); ++ const items = []; ++ if (componentsObject[key]) { ++ for (const [name, item] of getEntries(componentsObject[key], ctx)) { ++ let subType = transformers[key](item, { ++ path: createRef(["components", key, name]), ++ schema: item, ++ ctx, ++ }); ++ let hasQuestionToken = false; ++ if (ctx.transform) { ++ const result = ctx.transform(item, { ++ path: createRef(["components", key, name]), ++ schema: item, ++ ctx, ++ }); ++ if (result) { ++ if ("schema" in result) { ++ subType = result.schema; ++ hasQuestionToken = result.questionToken; ++ } ++ else { ++ subType = result; ++ } ++ } ++ } ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: ctx.immutable }), tsPropertyIndex(name), hasQuestionToken ? QUESTION_TOKEN : undefined, subType); ++ addJSDocComment(item, property); ++ items.push(property); ++ if (ctx.rootTypes) { ++ const componentKey = changeCase.pascalCase(singularizeComponentKey(key)); ++ let aliasName = `${componentKey}${changeCase.pascalCase(name)}`; ++ let conflictCounter = 1; ++ while (rootTypeAliases[aliasName] !== undefined) { ++ conflictCounter++; ++ aliasName = `${componentKey}${changeCase.pascalCase(name)}_${conflictCounter}`; ++ } ++ const ref = ts.factory.createTypeReferenceNode(`components['${key}']['${name}']`); ++ if (ctx.rootTypesNoSchemaPrefix && key === "schemas") { ++ aliasName = aliasName.replace(componentKey, ""); ++ } ++ const typeAlias = ts.factory.createTypeAliasDeclaration(tsModifiers({ export: true }), aliasName, undefined, ref); ++ rootTypeAliases[aliasName] = typeAlias; ++ } ++ } ++ } ++ type.push(ts.factory.createPropertySignature(undefined, tsPropertyIndex(key), undefined, items.length ? ts.factory.createTypeLiteralNode(items) : NEVER)); ++ debug(`Transformed components → ${key}`, "ts", performance.now() - componentT); ++ } ++ let rootTypes = []; ++ if (ctx.rootTypes) { ++ rootTypes = Object.keys(rootTypeAliases).map((k) => rootTypeAliases[k]); ++ } ++ return [ts.factory.createTypeLiteralNode(type), ...rootTypes]; ++} ++export function singularizeComponentKey(key) { ++ switch (key) { ++ case "requestBodies": ++ return "requestBody"; ++ default: ++ return key.slice(0, -1); ++ } ++} ++//# sourceMappingURL=components-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/components-object.js.map b/package/dist/transform/components-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..abcb4f3dc37b3df73a738e988e6104a07f0d74c6 +--- /dev/null ++++ b/package/dist/transform/components-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"components-object.js","sourceRoot":"","sources":["../../src/transform/components-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,KAAK,UAAU,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpG,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE/D,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AACvD,OAAO,wBAAwB,MAAM,uBAAuB,CAAC;AAC7D,OAAO,uBAAuB,MAAM,uBAAuB,CAAC;AAC5D,OAAO,0BAA0B,MAAM,0BAA0B,CAAC;AAClE,OAAO,uBAAuB,MAAM,sBAAsB,CAAC;AAC3D,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AAIvD,MAAM,YAAY,GAA2F;IAC3G,OAAO,EAAE,qBAAqB;IAC9B,SAAS,EAAE,uBAAuB;IAClC,UAAU,EAAE,wBAAwB;IACpC,aAAa,EAAE,0BAA0B;IACzC,OAAO,EAAE,qBAAqB;IAC9B,SAAS,EAAE,uBAAuB;CACnC,CAAC;AAMF,MAAM,CAAC,OAAO,UAAU,yBAAyB,CAAC,gBAAkC,EAAE,GAAkB;IACtG,MAAM,IAAI,GAAqB,EAAE,CAAC;IAClC,MAAM,eAAe,GAA+C,EAAE,CAAC;IACvE,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAA0B,EAAE,CAAC;QACrE,MAAM,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QAErC,MAAM,KAAK,GAAqB,EAAE,CAAC;QACnC,IAAI,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC;YAC1B,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,UAAU,CAAe,gBAAgB,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;gBAChF,IAAI,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE;oBACpC,IAAI,EAAE,SAAS,CAAC,CAAC,YAAY,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;oBAC1C,MAAM,EAAE,IAAI;oBACZ,GAAG;iBACJ,CAAC,CAAC;gBAEH,IAAI,gBAAgB,GAAG,KAAK,CAAC;gBAC7B,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;oBAClB,MAAM,MAAM,GAAG,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE;wBACjC,IAAI,EAAE,SAAS,CAAC,CAAC,YAAY,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;wBAC1C,MAAM,EAAE,IAAI;wBACZ,GAAG;qBACJ,CAAC,CAAC;oBACH,IAAI,MAAM,EAAE,CAAC;wBACX,IAAI,QAAQ,IAAI,MAAM,EAAE,CAAC;4BACvB,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;4BACxB,gBAAgB,GAAG,MAAM,CAAC,aAAa,CAAC;wBAC1C,CAAC;6BAAM,CAAC;4BACN,OAAO,GAAG,MAAM,CAAC;wBACnB,CAAC;oBACH,CAAC;gBACH,CAAC;gBAED,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,EACxC,eAAe,CAAC,IAAI,CAAC,EACrB,gBAAgB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,EAC7C,OAAO,CAC5B,CAAC;gBACF,eAAe,CAAC,IAAsB,EAAE,QAAQ,CAAC,CAAC;gBAClD,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBAErB,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;oBAClB,MAAM,YAAY,GAAG,UAAU,CAAC,UAAU,CAAC,uBAAuB,CAAC,GAAG,CAAC,CAAC,CAAC;oBACzE,IAAI,SAAS,GAAG,GAAG,YAAY,GAAG,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;oBAGhE,IAAI,eAAe,GAAG,CAAC,CAAC;oBAExB,OAAO,eAAe,CAAC,SAAS,CAAC,KAAK,SAAS,EAAE,CAAC;wBAChD,eAAe,EAAE,CAAC;wBAClB,SAAS,GAAG,GAAG,YAAY,GAAG,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,eAAe,EAAE,CAAC;oBACjF,CAAC;oBACD,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,eAAe,GAAG,OAAO,IAAI,IAAI,CAAC,CAAC;oBAClF,IAAI,GAAG,CAAC,uBAAuB,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;wBACrD,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;oBAClD,CAAC;oBACD,MAAM,SAAS,GAAG,EAAE,CAAC,OAAO,CAAC,0BAA0B,CAChC,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAC7B,SAAS,EACT,SAAS,EACT,GAAG,CACzB,CAAC;oBACF,eAAe,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;gBACzC,CAAC;YACH,CAAC;QACH,CAAC;QACD,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,GAAG,CAAC,EACpB,SAAS,EACT,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CACnF,CACF,CAAC;QAEF,KAAK,CAAC,4BAA4B,GAAG,EAAE,EAAE,IAAI,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,UAAU,CAAC,CAAC;IACjF,CAAC;IAGD,IAAI,SAAS,GAA8B,EAAE,CAAC;IAC9C,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;QAClB,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,EAAE,GAAG,SAAS,CAAC,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,GAAuG;IAEvG,QAAQ,GAAG,EAAE,CAAC;QAEZ,KAAK,eAAe;YAClB,OAAO,aAAa,CAAC;QAEvB;YACE,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC5B,CAAC;AACH,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/header-object.d.ts b/package/dist/transform/header-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..4a7b606cffec8e127812d30cde2640e6dc8a469f +--- /dev/null ++++ b/package/dist/transform/header-object.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { HeaderObject, TransformNodeOptions } from "../types.js"; ++export default function transformHeaderObject(headerObject: HeaderObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/header-object.js b/package/dist/transform/header-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..c74c1eb5922fceb4f93936510aa8c7c681e252b1 +--- /dev/null ++++ b/package/dist/transform/header-object.js +@@ -0,0 +1,32 @@ ++import { escapePointer } from "@redocly/openapi-core/lib/ref-utils.js"; ++import ts from "typescript"; ++import { addJSDocComment, tsModifiers, tsPropertyIndex, UNKNOWN } from "../lib/ts.js"; ++import { getEntries } from "../lib/utils.js"; ++import transformMediaTypeObject from "./media-type-object.js"; ++import transformSchemaObject from "./schema-object.js"; ++export default function transformHeaderObject(headerObject, options) { ++ if (headerObject.schema) { ++ return transformSchemaObject(headerObject.schema, options); ++ } ++ if (headerObject.content) { ++ const type = []; ++ for (const [contentType, mediaTypeObject] of getEntries(headerObject.content ?? {}, options.ctx)) { ++ const nextPath = `${options.path ?? "#"}/${escapePointer(contentType)}`; ++ const mediaType = "$ref" in mediaTypeObject ++ ? transformSchemaObject(mediaTypeObject, { ++ ...options, ++ path: nextPath, ++ }) ++ : transformMediaTypeObject(mediaTypeObject, { ++ ...options, ++ path: nextPath, ++ }); ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(contentType), undefined, mediaType); ++ addJSDocComment(mediaTypeObject, property); ++ type.push(property); ++ } ++ return ts.factory.createTypeLiteralNode(type); ++ } ++ return UNKNOWN; ++} ++//# sourceMappingURL=header-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/header-object.js.map b/package/dist/transform/header-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..eda3d1b9001db80a6c45ef27ebb629b825b0b88c +--- /dev/null ++++ b/package/dist/transform/header-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"header-object.js","sourceRoot":"","sources":["../../src/transform/header-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAC;AACvE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACtF,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,wBAAwB,MAAM,wBAAwB,CAAC;AAC9D,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AAMvD,MAAM,CAAC,OAAO,UAAU,qBAAqB,CAAC,YAA0B,EAAE,OAA6B;IACrG,IAAI,YAAY,CAAC,MAAM,EAAE,CAAC;QACxB,OAAO,qBAAqB,CAAC,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAED,IAAI,YAAY,CAAC,OAAO,EAAE,CAAC;QACzB,MAAM,IAAI,GAAqB,EAAE,CAAC;QAClC,KAAK,MAAM,CAAC,WAAW,EAAE,eAAe,CAAC,IAAI,UAAU,CAAC,YAAY,CAAC,OAAO,IAAI,EAAE,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACjG,MAAM,QAAQ,GAAG,GAAG,OAAO,CAAC,IAAI,IAAI,GAAG,IAAI,aAAa,CAAC,WAAW,CAAC,EAAE,CAAC;YACxE,MAAM,SAAS,GACb,MAAM,IAAI,eAAe;gBACvB,CAAC,CAAC,qBAAqB,CAAC,eAAe,EAAE;oBACrC,GAAG,OAAO;oBACV,IAAI,EAAE,QAAQ;iBACf,CAAC;gBACJ,CAAC,CAAC,wBAAwB,CAAC,eAAe,EAAE;oBACxC,GAAG,OAAO;oBACV,IAAI,EAAE,QAAQ;iBACf,CAAC,CAAC;YACT,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,WAAW,CAAC,EAC5B,SAAS,EACT,SAAS,CAC9B,CAAC;YACF,eAAe,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC;YAC3C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACtB,CAAC;QACD,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/index.d.ts b/package/dist/transform/index.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..818da4cad15a26059d44d6b36680623ebe90abd0 +--- /dev/null ++++ b/package/dist/transform/index.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { GlobalContext, OpenAPI3 } from "../types.js"; ++export default function transformSchema(schema: OpenAPI3, ctx: GlobalContext): ts.Node[]; +diff --git a/package/dist/transform/index.js b/package/dist/transform/index.js +new file mode 100644 +index 0000000000000000000000000000000000000000..2fb6e8d80aee60b2b921f0e7d08d66a8cb27679f +--- /dev/null ++++ b/package/dist/transform/index.js +@@ -0,0 +1,69 @@ ++import ts from "typescript"; ++import { performance } from "node:perf_hooks"; ++import { NEVER, STRING, stringToAST, tsModifiers, tsRecord } from "../lib/ts.js"; ++import { createRef, debug } from "../lib/utils.js"; ++import transformComponentsObject from "./components-object.js"; ++import transformPathsObject from "./paths-object.js"; ++import transformSchemaObject from "./schema-object.js"; ++import transformWebhooksObject from "./webhooks-object.js"; ++import makeApiPathsEnum from "./paths-enum.js"; ++const transformers = { ++ paths: transformPathsObject, ++ webhooks: transformWebhooksObject, ++ components: transformComponentsObject, ++ $defs: (node, options) => transformSchemaObject(node, { path: createRef(["$defs"]), ctx: options, schema: node }), ++}; ++export default function transformSchema(schema, ctx) { ++ const type = []; ++ if (ctx.inject) { ++ const injectNodes = stringToAST(ctx.inject); ++ type.push(...injectNodes); ++ } ++ for (const root of Object.keys(transformers)) { ++ const emptyObj = ts.factory.createTypeAliasDeclaration(tsModifiers({ export: true }), root, undefined, tsRecord(STRING, NEVER)); ++ if (schema[root] && typeof schema[root] === "object") { ++ const rootT = performance.now(); ++ const subTypes = [].concat(transformers[root](schema[root], ctx)); ++ for (const subType of subTypes) { ++ if (ts.isTypeNode(subType)) { ++ if (subType.members?.length) { ++ type.push(ctx.exportType ++ ? ts.factory.createTypeAliasDeclaration(tsModifiers({ export: true }), root, undefined, subType) ++ : ts.factory.createInterfaceDeclaration(tsModifiers({ export: true }), root, undefined, undefined, subType.members)); ++ debug(`${root} done`, "ts", performance.now() - rootT); ++ } ++ else { ++ type.push(emptyObj); ++ debug(`${root} done (skipped)`, "ts", 0); ++ } ++ } ++ else if (ts.isTypeAliasDeclaration(subType)) { ++ type.push(subType); ++ } ++ else { ++ type.push(emptyObj); ++ debug(`${root} done (skipped)`, "ts", 0); ++ } ++ } ++ } ++ else { ++ type.push(emptyObj); ++ debug(`${root} done (skipped)`, "ts", 0); ++ } ++ } ++ let hasOperations = false; ++ for (const injectedType of ctx.injectFooter) { ++ if (!hasOperations && injectedType?.name?.escapedText === "operations") { ++ hasOperations = true; ++ } ++ type.push(injectedType); ++ } ++ if (!hasOperations) { ++ type.push(ts.factory.createTypeAliasDeclaration(tsModifiers({ export: true }), "operations", undefined, tsRecord(STRING, NEVER))); ++ } ++ if (ctx.makePathsEnum && schema.paths) { ++ type.push(makeApiPathsEnum(schema.paths)); ++ } ++ return type; ++} ++//# sourceMappingURL=index.js.map +\ No newline at end of file +diff --git a/package/dist/transform/index.js.map b/package/dist/transform/index.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..997cbe79a2f99383f848bf1b41b291ddd1669d12 +--- /dev/null ++++ b/package/dist/transform/index.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/transform/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuD,MAAM,YAAY,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,yBAAyB,MAAM,wBAAwB,CAAC;AAC/D,OAAO,oBAAoB,MAAM,mBAAmB,CAAC;AACrD,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AACvD,OAAO,uBAAuB,MAAM,sBAAsB,CAAC;AAC3D,OAAO,gBAAgB,MAAM,iBAAiB,CAAC;AAI/C,MAAM,YAAY,GAAyF;IACzG,KAAK,EAAE,oBAAoB;IAC3B,QAAQ,EAAE,uBAAuB;IACjC,UAAU,EAAE,yBAAyB;IACrC,KAAK,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;CAClH,CAAC;AAEF,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,MAAgB,EAAE,GAAkB;IAC1E,MAAM,IAAI,GAAc,EAAE,CAAC;IAE3B,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;QACf,MAAM,WAAW,GAAG,WAAW,CAAC,GAAG,CAAC,MAAM,CAAc,CAAC;QACzD,IAAI,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC;IAC5B,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAuB,EAAE,CAAC;QACnE,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,0BAA0B,CAC/B,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAC7B,IAAI,EACJ,SAAS,EACT,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,CAC7C,CAAC;QAEF,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,QAAQ,EAAE,CAAC;YACrD,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;YAChC,MAAM,QAAQ,GAAI,EAAgB,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;YACjF,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;gBAC/B,IAAI,EAAE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;oBAC3B,IAAK,OAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;wBACpD,IAAI,CAAC,IAAI,CACP,GAAG,CAAC,UAAU;4BACZ,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,0BAA0B,CACd,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAC7B,IAAI,EACJ,SAAS,EACT,OAAO,CAC7B;4BACH,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,0BAA0B,CACb,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAC7B,IAAI,EACJ,SAAS,EACT,SAAS,EACR,OAA2B,CAAC,OAAO,CAC3D,CACN,CAAC;wBACF,KAAK,CAAC,GAAG,IAAI,OAAO,EAAE,IAAI,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC;oBACzD,CAAC;yBAAM,CAAC;wBACN,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;wBACpB,KAAK,CAAC,GAAG,IAAI,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;oBAC3C,CAAC;gBACH,CAAC;qBAAM,IAAI,EAAE,CAAC,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;oBAC9C,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBACrB,CAAC;qBAAM,CAAC;oBACN,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;oBACpB,KAAK,CAAC,GAAG,IAAI,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;gBAC3C,CAAC;YACH,CAAC;QACH,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YACpB,KAAK,CAAC,GAAG,IAAI,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;IAGD,IAAI,aAAa,GAAG,KAAK,CAAC;IAC1B,KAAK,MAAM,YAAY,IAAI,GAAG,CAAC,YAAY,EAAE,CAAC;QAC5C,IAAI,CAAC,aAAa,IAAK,YAAqC,EAAE,IAAI,EAAE,WAAW,KAAK,YAAY,EAAE,CAAC;YACjG,aAAa,GAAG,IAAI,CAAC;QACvB,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IAC1B,CAAC;IACD,IAAI,CAAC,aAAa,EAAE,CAAC;QAEnB,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,0BAA0B,CACd,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAC7B,YAAY,EACZ,SAAS,EACT,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,CAC7C,CACF,CAAC;IACJ,CAAC;IAED,IAAI,GAAG,CAAC,aAAa,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QACtC,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/media-type-object.d.ts b/package/dist/transform/media-type-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..6d1cd36633da88911320975d8bf3e2655bdd4c7e +--- /dev/null ++++ b/package/dist/transform/media-type-object.d.ts +@@ -0,0 +1,3 @@ ++import type ts from "typescript"; ++import type { MediaTypeObject, TransformNodeOptions } from "../types.js"; ++export default function transformMediaTypeObject(mediaTypeObject: MediaTypeObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/media-type-object.js b/package/dist/transform/media-type-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..8e983d83f07206fdaaf69e8aa38e1f5181b15fb8 +--- /dev/null ++++ b/package/dist/transform/media-type-object.js +@@ -0,0 +1,9 @@ ++import { UNKNOWN } from "../lib/ts.js"; ++import transformSchemaObject from "./schema-object.js"; ++export default function transformMediaTypeObject(mediaTypeObject, options) { ++ if (!mediaTypeObject.schema) { ++ return UNKNOWN; ++ } ++ return transformSchemaObject(mediaTypeObject.schema, options); ++} ++//# sourceMappingURL=media-type-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/media-type-object.js.map b/package/dist/transform/media-type-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..f4f95f7c44f8e94b4f99afcc2908caf6ba66d407 +--- /dev/null ++++ b/package/dist/transform/media-type-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"media-type-object.js","sourceRoot":"","sources":["../../src/transform/media-type-object.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AAMvD,MAAM,CAAC,OAAO,UAAU,wBAAwB,CAC9C,eAAgC,EAChC,OAA6B;IAE7B,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE,CAAC;QAC5B,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,qBAAqB,CAAC,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAChE,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/operation-object.d.ts b/package/dist/transform/operation-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..49953102780c120f77165776ddfaacc71716b386 +--- /dev/null ++++ b/package/dist/transform/operation-object.d.ts +@@ -0,0 +1,4 @@ ++import ts from "typescript"; ++import type { OperationObject, TransformNodeOptions } from "../types.js"; ++export default function transformOperationObject(operationObject: OperationObject, options: TransformNodeOptions): ts.TypeElement[]; ++export declare function injectOperationObject(operationId: string, operationObject: OperationObject, options: TransformNodeOptions): void; +diff --git a/package/dist/transform/operation-object.js b/package/dist/transform/operation-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..d4203a0792594fbea2ae9a6edd30989e9d696819 +--- /dev/null ++++ b/package/dist/transform/operation-object.js +@@ -0,0 +1,44 @@ ++import ts from "typescript"; ++import { NEVER, QUESTION_TOKEN, addJSDocComment, oapiRef, tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef } from "../lib/utils.js"; ++import { transformParametersArray } from "./parameters-array.js"; ++import transformRequestBodyObject from "./request-body-object.js"; ++import transformResponsesObject from "./responses-object.js"; ++export default function transformOperationObject(operationObject, options) { ++ const type = []; ++ type.push(...transformParametersArray(operationObject.parameters ?? [], options)); ++ if (operationObject.requestBody) { ++ const requestBodyType = "$ref" in operationObject.requestBody ++ ? oapiRef(operationObject.requestBody.$ref) ++ : transformRequestBodyObject(operationObject.requestBody, { ++ ...options, ++ path: createRef([options.path, "requestBody"]), ++ }); ++ const required = !!("$ref" in operationObject.requestBody ++ ? options.ctx.resolve(operationObject.requestBody.$ref) ++ : operationObject.requestBody)?.required; ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex("requestBody"), required ? undefined : QUESTION_TOKEN, requestBodyType); ++ addJSDocComment(operationObject.requestBody, property); ++ type.push(property); ++ } ++ else { ++ type.push(ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex("requestBody"), QUESTION_TOKEN, NEVER)); ++ } ++ type.push(ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex("responses"), undefined, transformResponsesObject(operationObject.responses ?? {}, options))); ++ return type; ++} ++export function injectOperationObject(operationId, operationObject, options) { ++ let operations = options.ctx.injectFooter.find((node) => ts.isInterfaceDeclaration(node) && node.name.text === "operations"); ++ if (!operations) { ++ operations = ts.factory.createInterfaceDeclaration(tsModifiers({ ++ export: true, ++ }), ts.factory.createIdentifier("operations"), undefined, undefined, []); ++ options.ctx.injectFooter.push(operations); ++ } ++ const type = transformOperationObject(operationObject, options); ++ operations.members = ts.factory.createNodeArray([ ++ ...operations.members, ++ ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(operationId), undefined, ts.factory.createTypeLiteralNode(type)), ++ ]); ++} ++//# sourceMappingURL=operation-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/operation-object.js.map b/package/dist/transform/operation-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..e347d2d374dc4a308bd1d74a3f3b9b5c242bb9bf +--- /dev/null ++++ b/package/dist/transform/operation-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"operation-object.js","sourceRoot":"","sources":["../../src/transform/operation-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC7G,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,0BAA0B,MAAM,0BAA0B,CAAC;AAClE,OAAO,wBAAwB,MAAM,uBAAuB,CAAC;AAM7D,MAAM,CAAC,OAAO,UAAU,wBAAwB,CAC9C,eAAgC,EAChC,OAA6B;IAE7B,MAAM,IAAI,GAAqB,EAAE,CAAC;IAGlC,IAAI,CAAC,IAAI,CAAC,GAAG,wBAAwB,CAAC,eAAe,CAAC,UAAU,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAGlF,IAAI,eAAe,CAAC,WAAW,EAAE,CAAC;QAChC,MAAM,eAAe,GACnB,MAAM,IAAI,eAAe,CAAC,WAAW;YACnC,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;YAC3C,CAAC,CAAC,0BAA0B,CAAC,eAAe,CAAC,WAAW,EAAE;gBACtD,GAAG,OAAO;gBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;aAC/C,CAAC,CAAC;QACT,MAAM,QAAQ,GAAG,CAAC,CAAC,CACjB,MAAM,IAAI,eAAe,CAAC,WAAW;YACnC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAoB,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;YAC1E,CAAC,CAAC,eAAe,CAAC,WAAW,CAChC,EAAE,QAAQ,CAAC;QACZ,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,aAAa,CAAC,EAC9B,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,cAAc,EACrC,eAAe,CACpC,CAAC;QACF,eAAe,CAAC,eAAe,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;QACvD,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;SAAM,CAAC;QACN,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,aAAa,CAAC,EAC9B,cAAc,EACd,KAAK,CAC1B,CACF,CAAC;IACJ,CAAC;IAGD,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,WAAW,CAAC,EAC5B,SAAS,EACT,wBAAwB,CAAC,eAAe,CAAC,SAAS,IAAI,EAAE,EAAE,OAAO,CAAC,CACvF,CACF,CAAC;IAEF,OAAO,IAAI,CAAC;AACd,CAAC;AAGD,MAAM,UAAU,qBAAqB,CACnC,WAAmB,EACnB,eAAgC,EAChC,OAA6B;IAG7B,IAAI,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAC5C,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,sBAAsB,CAAC,IAAI,CAAC,IAAK,IAAgC,CAAC,IAAI,CAAC,IAAI,KAAK,YAAY,CACpE,CAAC;IACxC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,UAAU,GAAG,EAAE,CAAC,OAAO,CAAC,0BAA0B,CAC1B,WAAW,CAAC;YAChC,MAAM,EAAE,IAAI;SAEb,CAAC,EACoB,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,YAAY,CAAC,EACzC,SAAS,EACT,SAAS,EACT,EAAE,CACzB,CAAC;QACF,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC5C,CAAC;IAGD,MAAM,IAAI,GAAG,wBAAwB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAC;IAEhE,UAAU,CAAC,OAAO,GAAG,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC;QAC9C,GAAG,UAAU,CAAC,OAAO;QACrB,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,WAAW,CAAC,EAC5B,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAC3D;KACF,CAAC,CAAC;AACL,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/parameter-object.d.ts b/package/dist/transform/parameter-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..bf6ee2436c3886b5decf5d321689eedb393877c2 +--- /dev/null ++++ b/package/dist/transform/parameter-object.d.ts +@@ -0,0 +1,3 @@ ++import type ts from "typescript"; ++import type { ParameterObject, TransformNodeOptions } from "../types.js"; ++export default function transformParameterObject(parameterObject: ParameterObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/parameter-object.js b/package/dist/transform/parameter-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..112fb125abd03c0d7d2b5cda42bf0db5a49f8389 +--- /dev/null ++++ b/package/dist/transform/parameter-object.js +@@ -0,0 +1,6 @@ ++import { STRING } from "../lib/ts.js"; ++import transformSchemaObject from "./schema-object.js"; ++export default function transformParameterObject(parameterObject, options) { ++ return parameterObject.schema ? transformSchemaObject(parameterObject.schema, options) : STRING; ++} ++//# sourceMappingURL=parameter-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/parameter-object.js.map b/package/dist/transform/parameter-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..21b286390ff2a6f81b4306e79278b8d874ab64ca +--- /dev/null ++++ b/package/dist/transform/parameter-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"parameter-object.js","sourceRoot":"","sources":["../../src/transform/parameter-object.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AAMvD,MAAM,CAAC,OAAO,UAAU,wBAAwB,CAC9C,eAAgC,EAChC,OAA6B;IAE7B,OAAO,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,qBAAqB,CAAC,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AAClG,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/parameters-array.d.ts b/package/dist/transform/parameters-array.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..a6d3d1d26639986155678becb40899e753312ba7 +--- /dev/null ++++ b/package/dist/transform/parameters-array.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { ParameterObject, ReferenceObject, TransformNodeOptions } from "../types.js"; ++export declare function transformParametersArray(parametersArray: (ParameterObject | ReferenceObject)[], options: TransformNodeOptions): ts.TypeElement[]; +diff --git a/package/dist/transform/parameters-array.js b/package/dist/transform/parameters-array.js +new file mode 100644 +index 0000000000000000000000000000000000000000..ed51d2f32c7fb3ae1bf48edb534beeac22526574 +--- /dev/null ++++ b/package/dist/transform/parameters-array.js +@@ -0,0 +1,80 @@ ++import ts from "typescript"; ++import { NEVER, QUESTION_TOKEN, addJSDocComment, oapiRef, tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef } from "../lib/utils.js"; ++import transformParameterObject from "./parameter-object.js"; ++const PATH_PARAM_RE = /\{([^}]+)\}/g; ++function createPathParameter(paramName) { ++ return { ++ name: paramName, ++ in: "path", ++ required: true, ++ schema: { type: "string" }, ++ }; ++} ++function extractPathParamsFromUrl(path) { ++ const params = []; ++ const matches = path.match(PATH_PARAM_RE); ++ if (matches) { ++ for (const match of matches) { ++ const paramName = match.slice(1, -1); ++ params.push(createPathParameter(paramName)); ++ } ++ } ++ return params; ++} ++export function transformParametersArray(parametersArray, options) { ++ const type = []; ++ const workingParameters = [...parametersArray]; ++ if (options.ctx.generatePathParams && options.path) { ++ const pathString = Array.isArray(options.path) ? options.path[0] : options.path; ++ if (typeof pathString === "string") { ++ const pathParams = extractPathParamsFromUrl(pathString); ++ for (const param of pathParams) { ++ const exists = workingParameters.some((p) => { ++ const resolved = "$ref" in p ? options.ctx.resolve(p.$ref) : p; ++ return resolved?.in === "path" && resolved?.name === param.name; ++ }); ++ if (!exists) { ++ workingParameters.push(param); ++ } ++ } ++ } ++ } ++ const paramType = []; ++ for (const paramIn of ["query", "header", "path", "cookie"]) { ++ const paramLocType = []; ++ let operationParameters = workingParameters.map((param) => ({ ++ original: param, ++ resolved: "$ref" in param ? options.ctx.resolve(param.$ref) : param, ++ })); ++ if (options.ctx.alphabetize) { ++ operationParameters.sort((a, b) => (a.resolved?.name ?? "").localeCompare(b.resolved?.name ?? "")); ++ } ++ if (options.ctx.excludeDeprecated) { ++ operationParameters = operationParameters.filter(({ resolved }) => !resolved?.deprecated && !resolved?.schema?.deprecated); ++ } ++ for (const { original, resolved } of operationParameters) { ++ if (resolved?.in !== paramIn) { ++ continue; ++ } ++ let optional = undefined; ++ if (paramIn !== "path" && !resolved.required) { ++ optional = QUESTION_TOKEN; ++ } ++ const subType = "$ref" in original ++ ? oapiRef(original.$ref) ++ : transformParameterObject(resolved, { ++ ...options, ++ path: createRef([options.path, "parameters", resolved.in, resolved.name]), ++ }); ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(resolved?.name), optional, subType); ++ addJSDocComment(resolved, property); ++ paramLocType.push(property); ++ } ++ const allOptional = paramLocType.every((node) => !!node.questionToken); ++ paramType.push(ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(paramIn), allOptional || !paramLocType.length ? QUESTION_TOKEN : undefined, paramLocType.length ? ts.factory.createTypeLiteralNode(paramLocType) : NEVER)); ++ } ++ type.push(ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex("parameters"), !paramType.length ? QUESTION_TOKEN : undefined, paramType.length ? ts.factory.createTypeLiteralNode(paramType) : NEVER)); ++ return type; ++} ++//# sourceMappingURL=parameters-array.js.map +\ No newline at end of file +diff --git a/package/dist/transform/parameters-array.js.map b/package/dist/transform/parameters-array.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..2defd352db5e597a9354aab71896037d1df89627 +--- /dev/null ++++ b/package/dist/transform/parameters-array.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"parameters-array.js","sourceRoot":"","sources":["../../src/transform/parameters-array.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC7G,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,wBAAwB,MAAM,uBAAuB,CAAC;AAG7D,MAAM,aAAa,GAAG,cAAc,CAAC;AAKrC,SAAS,mBAAmB,CAAC,SAAiB;IAC5C,OAAO;QACL,IAAI,EAAE,SAAS;QACf,EAAE,EAAE,MAAM;QACV,QAAQ,EAAE,IAAI;QACd,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAC3B,CAAC;AACJ,CAAC;AAKD,SAAS,wBAAwB,CAAC,IAAY;IAC5C,MAAM,MAAM,GAAsB,EAAE,CAAC;IACrC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IAC1C,IAAI,OAAO,EAAE,CAAC;QACZ,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC5B,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YACrC,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAKD,MAAM,UAAU,wBAAwB,CACtC,eAAsD,EACtD,OAA6B;IAE7B,MAAM,IAAI,GAAqB,EAAE,CAAC;IAGlC,MAAM,iBAAiB,GAAG,CAAC,GAAG,eAAe,CAAC,CAAC;IAG/C,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACnD,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;QAChF,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE,CAAC;YACnC,MAAM,UAAU,GAAG,wBAAwB,CAAC,UAAU,CAAC,CAAC;YAExD,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;gBAC/B,MAAM,MAAM,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;oBAC1C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAkB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAChF,OAAO,QAAQ,EAAE,EAAE,KAAK,MAAM,IAAI,QAAQ,EAAE,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC;gBAClE,CAAC,CAAC,CAAC;gBACH,IAAI,CAAC,MAAM,EAAE,CAAC;oBACZ,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBAChC,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAGD,MAAM,SAAS,GAAqB,EAAE,CAAC;IACvC,KAAK,MAAM,OAAO,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAA4B,EAAE,CAAC;QACvF,MAAM,YAAY,GAAqB,EAAE,CAAC;QAC1C,IAAI,mBAAmB,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC1D,QAAQ,EAAE,KAAK;YACf,QAAQ,EAAE,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAkB,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK;SACrF,CAAC,CAAC,CAAC;QAGJ,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC;YAC5B,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;QACrG,CAAC;QACD,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,CAAC;YAClC,mBAAmB,GAAG,mBAAmB,CAAC,MAAM,CAC9C,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC,QAAQ,EAAE,UAAU,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CACzE,CAAC;QACJ,CAAC;QACD,KAAK,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,mBAAmB,EAAE,CAAC;YACzD,IAAI,QAAQ,EAAE,EAAE,KAAK,OAAO,EAAE,CAAC;gBAC7B,SAAS;YACX,CAAC;YACD,IAAI,QAAQ,GAAiC,SAAS,CAAC;YACvD,IAAI,OAAO,KAAK,MAAM,IAAI,CAAE,QAA4B,CAAC,QAAQ,EAAE,CAAC;gBAClE,QAAQ,GAAG,cAAc,CAAC;YAC5B,CAAC;YACD,MAAM,OAAO,GACX,MAAM,IAAI,QAAQ;gBAChB,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACxB,CAAC,CAAC,wBAAwB,CAAC,QAA2B,EAAE;oBACpD,GAAG,OAAO;oBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;iBAC1E,CAAC,CAAC;YACT,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,QAAQ,EAAE,IAAI,CAAC,EAC/B,QAAQ,EACR,OAAO,CAC5B,CAAC;YACF,eAAe,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YACpC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9B,CAAC;QACD,MAAM,WAAW,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QACvE,SAAS,CAAC,IAAI,CACZ,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,OAAO,CAAC,EACxB,WAAW,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,EAChE,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CACjG,CACF,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,YAAY,CAAC,EAC7B,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,EAC9C,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAC3F,CACF,CAAC;IAEF,OAAO,IAAI,CAAC;AACd,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/path-item-object.d.ts b/package/dist/transform/path-item-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..e330caebe2df3f6120883d9ce78d14eb16ccfb06 +--- /dev/null ++++ b/package/dist/transform/path-item-object.d.ts +@@ -0,0 +1,4 @@ ++import ts from "typescript"; ++import type { PathItemObject, TransformNodeOptions } from "../types.js"; ++export type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace"; ++export default function transformPathItemObject(pathItem: PathItemObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/path-item-object.js b/package/dist/transform/path-item-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..b51258b816192f3c357de5dcf5e4aeb401516f98 +--- /dev/null ++++ b/package/dist/transform/path-item-object.js +@@ -0,0 +1,51 @@ ++import ts from "typescript"; ++import { NEVER, QUESTION_TOKEN, addJSDocComment, oapiRef, tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef } from "../lib/utils.js"; ++import transformOperationObject, { injectOperationObject } from "./operation-object.js"; ++import { transformParametersArray } from "./parameters-array.js"; ++export default function transformPathItemObject(pathItem, options) { ++ const type = []; ++ type.push(...transformParametersArray(pathItem.parameters ?? [], { ++ ...options, ++ path: createRef([options.path, "parameters"]), ++ })); ++ for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) { ++ const operationObject = pathItem[method]; ++ if (!operationObject || ++ (options.ctx.excludeDeprecated && ++ ("$ref" in operationObject ? options.ctx.resolve(operationObject.$ref) : operationObject) ++ ?.deprecated)) { ++ type.push(ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(method), QUESTION_TOKEN, NEVER)); ++ continue; ++ } ++ const keyedParameters = {}; ++ if (!("$ref" in operationObject)) { ++ for (const parameter of [...(pathItem.parameters ?? []), ...(operationObject.parameters ?? [])]) { ++ const name = "$ref" in parameter ++ ? `${options.ctx.resolve(parameter.$ref)?.in}-${options.ctx.resolve(parameter.$ref)?.name}` ++ : `${parameter.in}-${parameter.name}`; ++ if (name) { ++ keyedParameters[name] = parameter; ++ } ++ } ++ } ++ let operationType; ++ if ("$ref" in operationObject) { ++ operationType = oapiRef(operationObject.$ref); ++ } ++ else if (operationObject.operationId) { ++ const operationId = operationObject.operationId.replace(HASH_RE, "/"); ++ operationType = oapiRef(createRef(["operations", operationId])); ++ injectOperationObject(operationId, { ...operationObject, parameters: Object.values(keyedParameters) }, { ...options, path: createRef([options.path, method]) }); ++ } ++ else { ++ operationType = ts.factory.createTypeLiteralNode(transformOperationObject({ ...operationObject, parameters: Object.values(keyedParameters) }, { ...options, path: createRef([options.path, method]) })); ++ } ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(method), undefined, operationType); ++ addJSDocComment(operationObject, property); ++ type.push(property); ++ } ++ return ts.factory.createTypeLiteralNode(type); ++} ++const HASH_RE = /#/g; ++//# sourceMappingURL=path-item-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/path-item-object.js.map b/package/dist/transform/path-item-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..157372e89af06f4867b30e0b4be12849b155aebc +--- /dev/null ++++ b/package/dist/transform/path-item-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"path-item-object.js","sourceRoot":"","sources":["../../src/transform/path-item-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC7G,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAQ5C,OAAO,wBAAwB,EAAE,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACxF,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAQjE,MAAM,CAAC,OAAO,UAAU,uBAAuB,CAAC,QAAwB,EAAE,OAA6B;IACrG,MAAM,IAAI,GAAqB,EAAE,CAAC;IAGlC,IAAI,CAAC,IAAI,CACP,GAAG,wBAAwB,CAAC,QAAQ,CAAC,UAAU,IAAI,EAAE,EAAE;QACrD,GAAG,OAAO;QACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;KAC9C,CAAC,CACH,CAAC;IAGF,KAAK,MAAM,MAAM,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAa,EAAE,CAAC;QACvG,MAAM,eAAe,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzC,IACE,CAAC,eAAe;YAChB,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB;gBAC5B,CAAC,MAAM,IAAI,eAAe,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAkB,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC;oBACxG,EAAE,UAAU,CAAC,EACjB,CAAC;YACD,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,MAAM,CAAC,EACvB,cAAc,EACd,KAAK,CAC1B,CACF,CAAC;YACF,SAAS;QACX,CAAC;QAGD,MAAM,eAAe,GAAsD,EAAE,CAAC;QAC9E,IAAI,CAAC,CAAC,MAAM,IAAI,eAAe,CAAC,EAAE,CAAC;YAEjC,KAAK,MAAM,SAAS,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,eAAe,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;gBAEhG,MAAM,IAAI,GACR,MAAM,IAAI,SAAS;oBACjB,CAAC,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,CAAkB,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,CAAkB,SAAS,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE;oBAC7H,CAAC,CAAC,GAAG,SAAS,CAAC,EAAE,IAAI,SAAS,CAAC,IAAI,EAAE,CAAC;gBAC1C,IAAI,IAAI,EAAE,CAAC;oBACT,eAAe,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;gBACpC,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,aAA0B,CAAC;QAC/B,IAAI,MAAM,IAAI,eAAe,EAAE,CAAC;YAC9B,aAAa,GAAG,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;QAChD,CAAC;aAEI,IAAI,eAAe,CAAC,WAAW,EAAE,CAAC;YAErC,MAAM,WAAW,GAAG,eAAe,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YACtE,aAAa,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;YAChE,qBAAqB,CACnB,WAAW,EACX,EAAE,GAAG,eAAe,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,EAClE,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,EAAE,CACxD,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,aAAa,GAAG,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAC9C,wBAAwB,CACtB,EAAE,GAAG,eAAe,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAAE,EAClE,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,EAAE,CACxD,CACF,CAAC;QACJ,CAAC;QACD,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,MAAM,CAAC,EACvB,SAAS,EACT,aAAa,CAClC,CAAC;QACF,eAAe,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;IAED,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,OAAO,GAAG,IAAI,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/paths-enum.d.ts b/package/dist/transform/paths-enum.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..700e7bb6076fc7a0b94980adc003fd2e25109611 +--- /dev/null ++++ b/package/dist/transform/paths-enum.d.ts +@@ -0,0 +1,3 @@ ++import type ts from "typescript"; ++import type { PathsObject } from "../types.js"; ++export default function makeApiPathsEnum(pathsObject: PathsObject): ts.EnumDeclaration; +diff --git a/package/dist/transform/paths-enum.js b/package/dist/transform/paths-enum.js +new file mode 100644 +index 0000000000000000000000000000000000000000..d4a3362d33bd35430a062245bff721703b65f81f +--- /dev/null ++++ b/package/dist/transform/paths-enum.js +@@ -0,0 +1,35 @@ ++import { tsEnum } from "../lib/ts.js"; ++import { getEntries } from "../lib/utils.js"; ++export default function makeApiPathsEnum(pathsObject) { ++ const enumKeys = []; ++ const enumMetaData = []; ++ for (const [url, pathItemObject] of getEntries(pathsObject)) { ++ for (const [method, operation] of Object.entries(pathItemObject)) { ++ if (!["get", "put", "post", "delete", "options", "head", "patch", "trace"].includes(method)) { ++ continue; ++ } ++ let pathName; ++ if (operation.operationId) { ++ pathName = operation.operationId; ++ } ++ else { ++ pathName = (method + url) ++ .split("/") ++ .map((part) => { ++ const capitalised = part.charAt(0).toUpperCase() + part.slice(1); ++ return capitalised.replace(/{.*}|:.*|[^a-zA-Z\d_]+/, ""); ++ }) ++ .join(""); ++ } ++ const adaptedUrl = url.replace(/{(\w+)}/g, ":$1"); ++ enumKeys.push(adaptedUrl); ++ enumMetaData.push({ ++ name: pathName, ++ }); ++ } ++ } ++ return tsEnum("ApiPaths", enumKeys, enumMetaData, { ++ export: true, ++ }); ++} ++//# sourceMappingURL=paths-enum.js.map +\ No newline at end of file +diff --git a/package/dist/transform/paths-enum.js.map b/package/dist/transform/paths-enum.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..507e308ddc3d0e11ba544a125e938a34596ea48e +--- /dev/null ++++ b/package/dist/transform/paths-enum.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"paths-enum.js","sourceRoot":"","sources":["../../src/transform/paths-enum.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAG7C,MAAM,CAAC,OAAO,UAAU,gBAAgB,CAAC,WAAwB;IAC/D,MAAM,QAAQ,GAAG,EAAE,CAAC;IACpB,MAAM,YAAY,GAAG,EAAE,CAAC;IAExB,KAAK,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;QAC5D,KAAK,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC;YACjE,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;gBAC5F,SAAS;YACX,CAAC;YAGD,IAAI,QAAgB,CAAC;YACrB,IAAI,SAAS,CAAC,WAAW,EAAE,CAAC;gBAC1B,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC;YACnC,CAAC;iBAAM,CAAC;gBAEN,QAAQ,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC;qBACtB,KAAK,CAAC,GAAG,CAAC;qBACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;oBACZ,MAAM,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;oBAIjE,OAAO,WAAW,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,CAAC;gBAC3D,CAAC,CAAC;qBACD,IAAI,CAAC,EAAE,CAAC,CAAC;YACd,CAAC;YAGD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;YAElD,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC1B,YAAY,CAAC,IAAI,CAAC;gBAChB,IAAI,EAAE,QAAQ;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC,UAAU,EAAE,QAAQ,EAAE,YAAY,EAAE;QAChD,MAAM,EAAE,IAAI;KACb,CAAC,CAAC;AACL,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/paths-object.d.ts b/package/dist/transform/paths-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..b623adf4d5c7da9b46f4371e7072ba85802724ad +--- /dev/null ++++ b/package/dist/transform/paths-object.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { GlobalContext, PathsObject } from "../types.js"; ++export default function transformPathsObject(pathsObject: PathsObject, ctx: GlobalContext): ts.TypeNode; +diff --git a/package/dist/transform/paths-object.js b/package/dist/transform/paths-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..32afe59ed21f0794b10599979872e037f5e5c063 +--- /dev/null ++++ b/package/dist/transform/paths-object.js +@@ -0,0 +1,86 @@ ++import ts from "typescript"; ++import { performance } from "node:perf_hooks"; ++import { addJSDocComment, oapiRef, stringToAST, tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef, debug, getEntries } from "../lib/utils.js"; ++import transformPathItemObject from "./path-item-object.js"; ++const PATH_PARAM_RE = /\{[^}]+\}/g; ++export default function transformPathsObject(pathsObject, ctx) { ++ const type = []; ++ for (const [url, pathItemObject] of getEntries(pathsObject, ctx)) { ++ if (!pathItemObject || typeof pathItemObject !== "object") { ++ continue; ++ } ++ const pathT = performance.now(); ++ if ("$ref" in pathItemObject) { ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: ctx.immutable }), tsPropertyIndex(url), undefined, oapiRef(pathItemObject.$ref)); ++ addJSDocComment(pathItemObject, property); ++ type.push(property); ++ } ++ else { ++ const pathItemType = transformPathItemObject(pathItemObject, { ++ path: createRef(["paths", url]), ++ ctx, ++ }); ++ if (ctx.pathParamsAsTypes && url.includes("{")) { ++ const pathParams = extractPathParams(pathItemObject, ctx); ++ const matches = url.match(PATH_PARAM_RE); ++ let rawPath = `\`${url}\``; ++ if (matches) { ++ for (const match of matches) { ++ const paramName = match.slice(1, -1); ++ const param = pathParams[paramName]; ++ switch (param?.schema?.type) { ++ case "number": ++ case "integer": ++ rawPath = rawPath.replace(match, "${number}"); ++ break; ++ case "boolean": ++ rawPath = rawPath.replace(match, "${boolean}"); ++ break; ++ default: ++ rawPath = rawPath.replace(match, "${string}"); ++ break; ++ } ++ } ++ const pathType = stringToAST(rawPath)[0]?.expression; ++ if (pathType) { ++ type.push(ts.factory.createIndexSignature(tsModifiers({ readonly: ctx.immutable }), [ ++ ts.factory.createParameterDeclaration(undefined, undefined, "path", undefined, pathType, undefined), ++ ], pathItemType)); ++ continue; ++ } ++ } ++ } ++ type.push(ts.factory.createPropertySignature(tsModifiers({ readonly: ctx.immutable }), tsPropertyIndex(url), undefined, pathItemType)); ++ debug(`Transformed path "${url}"`, "ts", performance.now() - pathT); ++ } ++ } ++ return ts.factory.createTypeLiteralNode(type); ++} ++function extractPathParams(pathItemObject, ctx) { ++ const params = {}; ++ for (const p of pathItemObject.parameters ?? []) { ++ const resolved = "$ref" in p && p.$ref ? ctx.resolve(p.$ref) : p; ++ if (resolved && resolved.in === "path") { ++ params[resolved.name] = resolved; ++ } ++ } ++ for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) { ++ if (!(method in pathItemObject)) { ++ continue; ++ } ++ const resolvedMethod = pathItemObject[method].$ref ++ ? ctx.resolve(pathItemObject[method].$ref) ++ : pathItemObject[method]; ++ if (resolvedMethod?.parameters) { ++ for (const p of resolvedMethod.parameters) { ++ const resolvedParam = "$ref" in p && p.$ref ? ctx.resolve(p.$ref) : p; ++ if (resolvedParam && resolvedParam.in === "path") { ++ params[resolvedParam.name] = resolvedParam; ++ } ++ } ++ } ++ } ++ return params; ++} ++//# sourceMappingURL=paths-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/paths-object.js.map b/package/dist/transform/paths-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..9cc98a29a66c074ea496518bbe22404ce1d71068 +--- /dev/null ++++ b/package/dist/transform/paths-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"paths-object.js","sourceRoot":"","sources":["../../src/transform/paths-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAS/D,OAAO,uBAAwC,MAAM,uBAAuB,CAAC;AAE7E,MAAM,aAAa,GAAG,YAAY,CAAC;AAMnC,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAAC,WAAwB,EAAE,GAAkB;IACvF,MAAM,IAAI,GAAqB,EAAE,CAAC;IAClC,KAAK,MAAM,CAAC,GAAG,EAAE,cAAc,CAAC,IAAI,UAAU,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC;QACjE,IAAI,CAAC,cAAc,IAAI,OAAO,cAAc,KAAK,QAAQ,EAAE,CAAC;YAC1D,SAAS;QACX,CAAC;QAED,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;QAGhC,IAAI,MAAM,IAAI,cAAc,EAAE,CAAC;YAC7B,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,EACxC,eAAe,CAAC,GAAG,CAAC,EACpB,SAAS,EACT,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,CACjD,CAAC;YACF,eAAe,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;YAC1C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACtB,CAAC;aAAM,CAAC;YACN,MAAM,YAAY,GAAG,uBAAuB,CAAC,cAAc,EAAE;gBAC3D,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;gBAC/B,GAAG;aACJ,CAAC,CAAC;YAGH,IAAI,GAAG,CAAC,iBAAiB,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC/C,MAAM,UAAU,GAAG,iBAAiB,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;gBAC1D,MAAM,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;gBACzC,IAAI,OAAO,GAAG,KAAK,GAAG,IAAI,CAAC;gBAC3B,IAAI,OAAO,EAAE,CAAC;oBACZ,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;wBAC5B,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;wBACrC,MAAM,KAAK,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;wBACpC,QAAQ,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;4BAC5B,KAAK,QAAQ,CAAC;4BACd,KAAK,SAAS;gCACZ,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;gCAC9C,MAAM;4BACR,KAAK,SAAS;gCACZ,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;gCAC/C,MAAM;4BACR;gCACE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;gCAC9C,MAAM;wBACV,CAAC;oBACH,CAAC;oBAGD,MAAM,QAAQ,GAAI,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAS,EAAE,UAAU,CAAC;oBAC9D,IAAI,QAAQ,EAAE,CAAC;wBACb,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,oBAAoB,CACT,WAAW,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,EACxC;4BAClB,EAAE,CAAC,OAAO,CAAC,0BAA0B,CACd,SAAS,EACT,SAAS,EACT,MAAM,EACN,SAAS,EACT,QAAQ,EACR,SAAS,CAC/B;yBACF,EACmB,YAAY,CACjC,CACF,CAAC;wBACF,SAAS;oBACX,CAAC;gBACH,CAAC;YACH,CAAC;YAED,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,EACxC,eAAe,CAAC,GAAG,CAAC,EACpB,SAAS,EACT,YAAY,CACjC,CACF,CAAC;YAEF,KAAK,CAAC,qBAAqB,GAAG,GAAG,EAAE,IAAI,EAAE,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC;AAED,SAAS,iBAAiB,CAAC,cAA8B,EAAE,GAAkB;IAC3E,MAAM,MAAM,GAAoC,EAAE,CAAC;IACnD,KAAK,MAAM,CAAC,IAAI,cAAc,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;QAChD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAkB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAE,CAAqB,CAAC;QACvG,IAAI,QAAQ,IAAI,QAAQ,CAAC,EAAE,KAAK,MAAM,EAAE,CAAC;YACvC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC;QACnC,CAAC;IACH,CAAC;IACD,KAAK,MAAM,MAAM,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAa,EAAE,CAAC;QACvG,IAAI,CAAC,CAAC,MAAM,IAAI,cAAc,CAAC,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,cAAc,GAAI,cAAc,CAAC,MAAM,CAAqB,CAAC,IAAI;YACrE,CAAC,CAAC,GAAG,CAAC,OAAO,CAAmB,cAAc,CAAC,MAAM,CAAqB,CAAC,IAAI,CAAC;YAChF,CAAC,CAAE,cAAc,CAAC,MAAM,CAAqB,CAAC;QAChD,IAAI,cAAc,EAAE,UAAU,EAAE,CAAC;YAC/B,KAAK,MAAM,CAAC,IAAI,cAAc,CAAC,UAAU,EAAE,CAAC;gBAC1C,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAkB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAE,CAAqB,CAAC;gBAC5G,IAAI,aAAa,IAAI,aAAa,CAAC,EAAE,KAAK,MAAM,EAAE,CAAC;oBACjD,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC;gBAC7C,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/request-body-object.d.ts b/package/dist/transform/request-body-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..78ba3e87926b34a1f9f32c3184cccd7924b3c257 +--- /dev/null ++++ b/package/dist/transform/request-body-object.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { RequestBodyObject, TransformNodeOptions } from "../types.js"; ++export default function transformRequestBodyObject(requestBodyObject: RequestBodyObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/request-body-object.js b/package/dist/transform/request-body-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..71b18fe99525aec345cf8b47842466d498944f95 +--- /dev/null ++++ b/package/dist/transform/request-body-object.js +@@ -0,0 +1,32 @@ ++import ts from "typescript"; ++import { NEVER, QUESTION_TOKEN, addJSDocComment, tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef, getEntries } from "../lib/utils.js"; ++import transformMediaTypeObject from "./media-type-object.js"; ++import transformSchemaObject from "./schema-object.js"; ++export default function transformRequestBodyObject(requestBodyObject, options) { ++ const type = []; ++ for (const [contentType, mediaTypeObject] of getEntries(requestBodyObject.content ?? {}, options.ctx)) { ++ const nextPath = createRef([options.path, contentType]); ++ const mediaType = "$ref" in mediaTypeObject ++ ? transformSchemaObject(mediaTypeObject, { ++ ...options, ++ path: nextPath, ++ }) ++ : transformMediaTypeObject(mediaTypeObject, { ++ ...options, ++ path: nextPath, ++ }); ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(contentType), undefined, mediaType); ++ addJSDocComment(mediaTypeObject, property); ++ type.push(property); ++ } ++ return ts.factory.createTypeLiteralNode([ ++ ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex("content"), undefined, ts.factory.createTypeLiteralNode(type.length ++ ? type ++ : ++ [ ++ ts.factory.createPropertySignature(undefined, tsPropertyIndex("*/*"), QUESTION_TOKEN, NEVER), ++ ])), ++ ]); ++} ++//# sourceMappingURL=request-body-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/request-body-object.js.map b/package/dist/transform/request-body-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..d258b8f890fa6bfc7c04c14402069809df8b9839 +--- /dev/null ++++ b/package/dist/transform/request-body-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"request-body-object.js","sourceRoot":"","sources":["../../src/transform/request-body-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpG,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAExD,OAAO,wBAAwB,MAAM,wBAAwB,CAAC;AAC9D,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AAMvD,MAAM,CAAC,OAAO,UAAU,0BAA0B,CAChD,iBAAoC,EACpC,OAA6B;IAE7B,MAAM,IAAI,GAAqB,EAAE,CAAC;IAClC,KAAK,MAAM,CAAC,WAAW,EAAE,eAAe,CAAC,IAAI,UAAU,CAAC,iBAAiB,CAAC,OAAO,IAAI,EAAE,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACtG,MAAM,QAAQ,GAAG,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC;QACxD,MAAM,SAAS,GACb,MAAM,IAAI,eAAe;YACvB,CAAC,CAAC,qBAAqB,CAAC,eAAe,EAAE;gBACrC,GAAG,OAAO;gBACV,IAAI,EAAE,QAAQ;aACf,CAAC;YACJ,CAAC,CAAC,wBAAwB,CAAC,eAAe,EAAE;gBACxC,GAAG,OAAO;gBACV,IAAI,EAAE,QAAQ;aACf,CAAC,CAAC;QACT,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,WAAW,CAAC,EAC5B,SAAS,EACT,SAAS,CAC9B,CAAC;QACF,eAAe,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;IAED,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC;QACtC,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,SAAS,CAAC,EAC1B,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAClD,IAAI,CAAC,MAAM;YACT,CAAC,CAAC,IAAI;YACN,CAAC;gBACC;oBACE,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,KAAK,CAAC,EACtB,cAAc,EACd,KAAK,CAC1B;iBACF,CACN,CACF;KACF,CAAC,CAAC;AACL,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/response-object.d.ts b/package/dist/transform/response-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..a285ccf966cfabe6a3a2c5e26bdc29dd004803b5 +--- /dev/null ++++ b/package/dist/transform/response-object.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { ResponseObject, TransformNodeOptions } from "../types.js"; ++export default function transformResponseObject(responseObject: ResponseObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/response-object.js b/package/dist/transform/response-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..d16bb7ad730656f4d632c286aec7a830ed6eedf4 +--- /dev/null ++++ b/package/dist/transform/response-object.js +@@ -0,0 +1,45 @@ ++import ts from "typescript"; ++import { NEVER, QUESTION_TOKEN, STRING, UNKNOWN, addJSDocComment, oapiRef, tsModifiers, tsPropertyIndex, } from "../lib/ts.js"; ++import { createRef, getEntries } from "../lib/utils.js"; ++import transformHeaderObject from "./header-object.js"; ++import transformMediaTypeObject from "./media-type-object.js"; ++export default function transformResponseObject(responseObject, options) { ++ const type = []; ++ const headersObject = []; ++ if (responseObject.headers) { ++ for (const [name, headerObject] of getEntries(responseObject.headers, options.ctx)) { ++ const optional = "$ref" in headerObject || headerObject.required ? undefined : QUESTION_TOKEN; ++ const subType = "$ref" in headerObject ++ ? oapiRef(headerObject.$ref) ++ : transformHeaderObject(headerObject, { ++ ...options, ++ path: createRef([options.path, "headers", name]), ++ }); ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(name), optional, subType); ++ addJSDocComment(headerObject, property); ++ headersObject.push(property); ++ } ++ } ++ headersObject.push(ts.factory.createIndexSignature(tsModifiers({ readonly: options.ctx.immutable }), [ ++ ts.factory.createParameterDeclaration(undefined, undefined, ts.factory.createIdentifier("name"), undefined, STRING), ++ ], UNKNOWN)); ++ type.push(ts.factory.createPropertySignature(undefined, tsPropertyIndex("headers"), undefined, ts.factory.createTypeLiteralNode(headersObject))); ++ const contentObject = []; ++ if (responseObject.content) { ++ for (const [contentType, mediaTypeObject] of getEntries(responseObject.content ?? {}, options.ctx)) { ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(contentType), undefined, transformMediaTypeObject(mediaTypeObject, { ++ ...options, ++ path: createRef([options.path, "content", contentType]), ++ })); ++ contentObject.push(property); ++ } ++ } ++ if (contentObject.length) { ++ type.push(ts.factory.createPropertySignature(undefined, tsPropertyIndex("content"), undefined, ts.factory.createTypeLiteralNode(contentObject))); ++ } ++ else { ++ type.push(ts.factory.createPropertySignature(undefined, tsPropertyIndex("content"), QUESTION_TOKEN, NEVER)); ++ } ++ return ts.factory.createTypeLiteralNode(type); ++} ++//# sourceMappingURL=response-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/response-object.js.map b/package/dist/transform/response-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..c097c23d02649a25b59a7a261670e55dbc3e0811 +--- /dev/null ++++ b/package/dist/transform/response-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"response-object.js","sourceRoot":"","sources":["../../src/transform/response-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EACL,KAAK,EACL,cAAc,EACd,MAAM,EACN,OAAO,EACP,eAAe,EACf,OAAO,EACP,WAAW,EACX,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAExD,OAAO,qBAAqB,MAAM,oBAAoB,CAAC;AACvD,OAAO,wBAAwB,MAAM,wBAAwB,CAAC;AAM9D,MAAM,CAAC,OAAO,UAAU,uBAAuB,CAC7C,cAA8B,EAC9B,OAA6B;IAE7B,MAAM,IAAI,GAAqB,EAAE,CAAC;IAGlC,MAAM,aAAa,GAAqB,EAAE,CAAC;IAC3C,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;QAC3B,KAAK,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,IAAI,UAAU,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACnF,MAAM,QAAQ,GAAG,MAAM,IAAI,YAAY,IAAI,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC;YAC9F,MAAM,OAAO,GACX,MAAM,IAAI,YAAY;gBACpB,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC;gBAC5B,CAAC,CAAC,qBAAqB,CAAC,YAAY,EAAE;oBAClC,GAAG,OAAO;oBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;iBACjD,CAAC,CAAC;YACT,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,IAAI,CAAC,EACrB,QAAQ,EACR,OAAO,CAC5B,CAAC;YACF,eAAe,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;YACxC,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IAED,aAAa,CAAC,IAAI,CAChB,EAAE,CAAC,OAAO,CAAC,oBAAoB,CACT,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EACnD;QACf,EAAE,CAAC,OAAO,CAAC,0BAA0B,CACd,SAAS,EACT,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,EACnC,SAAS,EACT,MAAM,CAC5B;KACF,EACmB,OAAO,CAC5B,CACF,CAAC;IACF,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,SAAS,CAAC,EAC1B,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,aAAa,CAAC,CACpE,CACF,CAAC;IAGF,MAAM,aAAa,GAAqB,EAAE,CAAC;IAC3C,IAAI,cAAc,CAAC,OAAO,EAAE,CAAC;QAC3B,KAAK,MAAM,CAAC,WAAW,EAAE,eAAe,CAAC,IAAI,UAAU,CAAC,cAAc,CAAC,OAAO,IAAI,EAAE,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YACnG,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,WAAW,CAAC,EAC5B,SAAS,EACT,wBAAwB,CAAC,eAAe,EAAE;gBAC5D,GAAG,OAAO;gBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;aACxD,CAAC,CACH,CAAC;YACF,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IACD,IAAI,aAAa,CAAC,MAAM,EAAE,CAAC;QACzB,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,SAAS,CAAC,EAC1B,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,aAAa,CAAC,CACpE,CACF,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,SAAS,CAAC,EAC1B,cAAc,EACd,KAAK,CAC1B,CACF,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/responses-object.d.ts b/package/dist/transform/responses-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..858eb915359176fcfacbfa143d594301e3fefe75 +--- /dev/null ++++ b/package/dist/transform/responses-object.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { ResponsesObject, TransformNodeOptions } from "../types.js"; ++export default function transformResponsesObject(responsesObject: ResponsesObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/responses-object.js b/package/dist/transform/responses-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..750b9d4b7e219096fea6b19a6f9ab1a6e1384d41 +--- /dev/null ++++ b/package/dist/transform/responses-object.js +@@ -0,0 +1,20 @@ ++import ts from "typescript"; ++import { NEVER, addJSDocComment, tsModifiers, oapiRef, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef, getEntries } from "../lib/utils.js"; ++import transformResponseObject from "./response-object.js"; ++export default function transformResponsesObject(responsesObject, options) { ++ const type = []; ++ for (const [responseCode, responseObject] of getEntries(responsesObject, options.ctx)) { ++ const responseType = "$ref" in responseObject ++ ? oapiRef(responseObject.$ref) ++ : transformResponseObject(responseObject, { ++ ...options, ++ path: createRef([options.path, "responses", responseCode]), ++ }); ++ const property = ts.factory.createPropertySignature(tsModifiers({ readonly: options.ctx.immutable }), tsPropertyIndex(responseCode), undefined, responseType); ++ addJSDocComment(responseObject, property); ++ type.push(property); ++ } ++ return type.length ? ts.factory.createTypeLiteralNode(type) : NEVER; ++} ++//# sourceMappingURL=responses-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/responses-object.js.map b/package/dist/transform/responses-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..9b7ebcec5ebbf4f420ac57c8010e9d0989f21b56 +--- /dev/null ++++ b/package/dist/transform/responses-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"responses-object.js","sourceRoot":"","sources":["../../src/transform/responses-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC7F,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAExD,OAAO,uBAAuB,MAAM,sBAAsB,CAAC;AAM3D,MAAM,CAAC,OAAO,UAAU,wBAAwB,CAC9C,eAAgC,EAChC,OAA6B;IAE7B,MAAM,IAAI,GAAqB,EAAE,CAAC;IAElC,KAAK,MAAM,CAAC,YAAY,EAAE,cAAc,CAAC,IAAI,UAAU,CAAC,eAAe,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACtF,MAAM,YAAY,GAChB,MAAM,IAAI,cAAc;YACtB,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC;YAC9B,CAAC,CAAC,uBAAuB,CAAC,cAAc,EAAE;gBACtC,GAAG,OAAO;gBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC;aAC3D,CAAC,CAAC;QACT,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,EAChD,eAAe,CAAC,YAAY,CAAC,EAC7B,SAAS,EACT,YAAY,CACjC,CAAC;QACF,eAAe,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC;IAED,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AACtE,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/schema-object.d.ts b/package/dist/transform/schema-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..3ed4d3e2191184a9c5338f8163a894b91dc4a5a6 +--- /dev/null ++++ b/package/dist/transform/schema-object.d.ts +@@ -0,0 +1,4 @@ ++import ts from "typescript"; ++import type { ReferenceObject, SchemaObject, TransformNodeOptions } from "../types.js"; ++export default function transformSchemaObject(schemaObject: SchemaObject | ReferenceObject, options: TransformNodeOptions): ts.TypeNode; ++export declare function transformSchemaObjectWithComposition(schemaObject: SchemaObject | ReferenceObject, options: TransformNodeOptions): ts.TypeNode; +diff --git a/package/dist/transform/schema-object.js b/package/dist/transform/schema-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..10d3271239348b81ea21763c56af076dd9077076 +--- /dev/null ++++ b/package/dist/transform/schema-object.js +@@ -0,0 +1,363 @@ ++import { parseRef } from "@redocly/openapi-core/lib/ref-utils.js"; ++import ts from "typescript"; ++import { BOOLEAN, NEVER, NULL, NUMBER, QUESTION_TOKEN, STRING, UNDEFINED, UNKNOWN, addJSDocComment, oapiRef, tsArrayLiteralExpression, tsEnum, tsIntersection, tsIsPrimitive, tsLiteral, tsModifiers, tsNullable, tsPropertyIndex, tsRecord, tsUnion, tsWithRequired, } from "../lib/ts.js"; ++import { createDiscriminatorProperty, createRef, getEntries } from "../lib/utils.js"; ++export default function transformSchemaObject(schemaObject, options) { ++ const type = transformSchemaObjectWithComposition(schemaObject, options); ++ if (typeof options.ctx.postTransform === "function") { ++ const postTransformResult = options.ctx.postTransform(type, options); ++ if (postTransformResult) { ++ return postTransformResult; ++ } ++ } ++ return type; ++} ++export function transformSchemaObjectWithComposition(schemaObject, options) { ++ if (!schemaObject) { ++ return NEVER; ++ } ++ if (schemaObject === true) { ++ return UNKNOWN; ++ } ++ if (Array.isArray(schemaObject) || typeof schemaObject !== "object") { ++ throw new Error(`Expected SchemaObject, received ${Array.isArray(schemaObject) ? "Array" : typeof schemaObject} at ${options.path}`); ++ } ++ if ("$ref" in schemaObject) { ++ return oapiRef(schemaObject.$ref); ++ } ++ if (schemaObject.const !== null && schemaObject.const !== undefined) { ++ return tsLiteral(schemaObject.const); ++ } ++ if (Array.isArray(schemaObject.enum) && ++ (!("type" in schemaObject) || schemaObject.type !== "object") && ++ !("properties" in schemaObject) && ++ !("additionalProperties" in schemaObject)) { ++ if (options.ctx.enum && ++ schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number" || v === null)) { ++ let enumName = parseRef(options.path ?? "").pointer.join("/"); ++ enumName = enumName.replace("components/schemas", ""); ++ const metadata = schemaObject.enum.map((_, i) => ({ ++ name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], ++ description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i], ++ })); ++ let hasNull = false; ++ const validSchemaEnums = schemaObject.enum.filter((enumValue) => { ++ if (enumValue === null) { ++ hasNull = true; ++ return false; ++ } ++ return true; ++ }); ++ const enumType = tsEnum(enumName, validSchemaEnums, metadata, { ++ shouldCache: options.ctx.dedupeEnums, ++ export: true, ++ }); ++ if (!options.ctx.injectFooter.includes(enumType)) { ++ options.ctx.injectFooter.push(enumType); ++ } ++ const ref = ts.factory.createTypeReferenceNode(enumType.name); ++ return hasNull ? tsUnion([ref, NULL]) : ref; ++ } ++ const enumType = schemaObject.enum.map(tsLiteral); ++ if (((Array.isArray(schemaObject.type) && schemaObject.type.includes("null")) || schemaObject.nullable) && ++ !schemaObject.default) { ++ enumType.push(NULL); ++ } ++ const unionType = tsUnion(enumType); ++ if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { ++ let enumValuesVariableName = parseRef(options.path ?? "").pointer.join("/"); ++ enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); ++ enumValuesVariableName = `${enumValuesVariableName}Values`; ++ const enumValuesArray = tsArrayLiteralExpression(enumValuesVariableName, oapiRef(options.path ?? ""), schemaObject.enum, { ++ export: true, ++ readonly: true, ++ injectFooter: options.ctx.injectFooter, ++ }); ++ options.ctx.injectFooter.push(enumValuesArray); ++ } ++ return unionType; ++ } ++ function collectUnionCompositions(items) { ++ const output = []; ++ for (const item of items) { ++ output.push(transformSchemaObject(item, options)); ++ } ++ return output; ++ } ++ function collectAllOfCompositions(items, required) { ++ const output = []; ++ for (const item of items) { ++ let itemType; ++ if ("$ref" in item) { ++ itemType = transformSchemaObject(item, options); ++ const resolved = options.ctx.resolve(item.$ref); ++ if (resolved && ++ typeof resolved === "object" && ++ "properties" in resolved && ++ !options.ctx.discriminators.refsHandled.includes(item.$ref)) { ++ const validRequired = (required ?? []).filter((key) => !!resolved.properties?.[key]); ++ if (validRequired.length) { ++ itemType = tsWithRequired(itemType, validRequired, options.ctx.injectFooter); ++ } ++ } ++ } ++ else { ++ const itemRequired = [...(required ?? [])]; ++ if (typeof item === "object" && Array.isArray(item.required)) { ++ itemRequired.push(...item.required); ++ } ++ itemType = transformSchemaObject({ ...item, required: itemRequired }, options); ++ } ++ output.push(itemType); ++ } ++ return output; ++ } ++ let finalType = undefined; ++ const coreObjectType = transformSchemaObjectCore(schemaObject, options); ++ const allOfType = collectAllOfCompositions(schemaObject.allOf ?? [], schemaObject.required); ++ if (coreObjectType || allOfType.length) { ++ const allOf = allOfType.length ? tsIntersection(allOfType) : undefined; ++ finalType = tsIntersection([...(coreObjectType ? [coreObjectType] : []), ...(allOf ? [allOf] : [])]); ++ } ++ const anyOfType = collectUnionCompositions(schemaObject.anyOf ?? []); ++ if (anyOfType.length) { ++ finalType = tsUnion([...(finalType ? [finalType] : []), ...anyOfType]); ++ } ++ const oneOfType = collectUnionCompositions(schemaObject.oneOf || ++ ("type" in schemaObject && ++ schemaObject.type === "object" && ++ schemaObject.enum) || ++ []); ++ if (oneOfType.length) { ++ if (oneOfType.every(tsIsPrimitive)) { ++ finalType = tsUnion([...(finalType ? [finalType] : []), ...oneOfType]); ++ } ++ else { ++ finalType = tsIntersection([...(finalType ? [finalType] : []), tsUnion(oneOfType)]); ++ } ++ } ++ if (!finalType) { ++ if ("type" in schemaObject) { ++ finalType = tsRecord(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER); ++ } ++ else { ++ finalType = UNKNOWN; ++ } ++ } ++ if (finalType !== UNKNOWN && schemaObject.nullable && !schemaObject.default) { ++ finalType = tsNullable([finalType]); ++ } ++ return finalType; ++} ++function transformSchemaObjectCore(schemaObject, options) { ++ if ("type" in schemaObject && schemaObject.type) { ++ if (typeof options.ctx.transform === "function") { ++ const result = options.ctx.transform(schemaObject, options); ++ if (result && typeof result === "object") { ++ if ("schema" in result) { ++ if (result.questionToken) { ++ return ts.factory.createUnionTypeNode([result.schema, UNDEFINED]); ++ } ++ else { ++ return result.schema; ++ } ++ } ++ else { ++ return result; ++ } ++ } ++ } ++ if (schemaObject.type === "null") { ++ return NULL; ++ } ++ if (schemaObject.type === "string") { ++ return STRING; ++ } ++ if (schemaObject.type === "number" || schemaObject.type === "integer") { ++ return NUMBER; ++ } ++ if (schemaObject.type === "boolean") { ++ return BOOLEAN; ++ } ++ if (schemaObject.type === "array") { ++ let itemType = UNKNOWN; ++ if (schemaObject.prefixItems || Array.isArray(schemaObject.items)) { ++ const prefixItems = schemaObject.prefixItems ?? schemaObject.items; ++ itemType = ts.factory.createTupleTypeNode(prefixItems.map((item) => transformSchemaObject(item, options))); ++ } ++ else if (schemaObject.items) { ++ if ("type" in schemaObject.items && schemaObject.items.type === "array") { ++ itemType = ts.factory.createArrayTypeNode(transformSchemaObject(schemaObject.items, options)); ++ } ++ else { ++ itemType = transformSchemaObject(schemaObject.items, options); ++ } ++ } ++ const min = typeof schemaObject.minItems === "number" && schemaObject.minItems >= 0 ? schemaObject.minItems : 0; ++ const max = typeof schemaObject.maxItems === "number" && schemaObject.maxItems >= 0 && min <= schemaObject.maxItems ++ ? schemaObject.maxItems ++ : undefined; ++ const estimateCodeSize = typeof max !== "number" ? min : (max * (max + 1) - min * (min - 1)) / 2; ++ if (options.ctx.arrayLength && ++ (min !== 0 || max !== undefined) && ++ estimateCodeSize < 30) { ++ if (min === max) { ++ const elements = []; ++ for (let i = 0; i < min; i++) { ++ elements.push(itemType); ++ } ++ return tsUnion([ts.factory.createTupleTypeNode(elements)]); ++ } ++ else if (schemaObject.maxItems > 0) { ++ const members = []; ++ for (let i = 0; i <= (max ?? 0) - min; i++) { ++ const elements = []; ++ for (let j = min; j < i + min; j++) { ++ elements.push(itemType); ++ } ++ members.push(ts.factory.createTupleTypeNode(elements)); ++ } ++ return tsUnion(members); ++ } ++ else { ++ const elements = []; ++ for (let i = 0; i < min; i++) { ++ elements.push(itemType); ++ } ++ elements.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(itemType))); ++ return ts.factory.createTupleTypeNode(elements); ++ } ++ } ++ const finalType = ts.isTupleTypeNode(itemType) || ts.isArrayTypeNode(itemType) ++ ? itemType ++ : ts.factory.createArrayTypeNode(itemType); ++ return options.ctx.immutable ++ ? ts.factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, finalType) ++ : finalType; ++ } ++ if (Array.isArray(schemaObject.type) && !Array.isArray(schemaObject)) { ++ const uniqueTypes = []; ++ if (Array.isArray(schemaObject.oneOf)) { ++ for (const t of schemaObject.type) { ++ if ((t === "boolean" || t === "string" || t === "number" || t === "integer" || t === "null") && ++ schemaObject.oneOf.find((o) => typeof o === "object" && "type" in o && o.type === t)) { ++ continue; ++ } ++ uniqueTypes.push(t === "null" || t === null ++ ? NULL ++ : transformSchemaObject({ ...schemaObject, type: t, oneOf: undefined }, options)); ++ } ++ } ++ else { ++ for (const t of schemaObject.type) { ++ if (t === "null" || t === null) { ++ if (!schemaObject.default) { ++ uniqueTypes.push(NULL); ++ } ++ } ++ else { ++ uniqueTypes.push(transformSchemaObject({ ...schemaObject, type: t }, options)); ++ } ++ } ++ } ++ return tsUnion(uniqueTypes); ++ } ++ } ++ const coreObjectType = []; ++ for (const k of ["allOf", "anyOf"]) { ++ if (!schemaObject[k]) { ++ continue; ++ } ++ const discriminator = !schemaObject.discriminator && ++ !options.ctx.discriminators.refsHandled.includes(options.path ?? "") && ++ options.ctx.discriminators.objects[options.path ?? ""]; ++ if (discriminator) { ++ coreObjectType.unshift(createDiscriminatorProperty(discriminator, { ++ path: options.path ?? "", ++ readonly: options.ctx.immutable, ++ })); ++ break; ++ } ++ } ++ if (("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject.properties).length) || ++ ("additionalProperties" in schemaObject && schemaObject.additionalProperties) || ++ ("$defs" in schemaObject && schemaObject.$defs)) { ++ if (Object.keys(schemaObject.properties ?? {}).length) { ++ for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) { ++ if (typeof v !== "object" || Array.isArray(v)) { ++ throw new Error(`${options.path}: invalid property ${k}. Expected Schema Object, got ${Array.isArray(v) ? "Array" : typeof v}`); ++ } ++ if (options.ctx.excludeDeprecated) { ++ const resolved = "$ref" in v ? options.ctx.resolve(v.$ref) : v; ++ if (resolved?.deprecated) { ++ continue; ++ } ++ } ++ let optional = schemaObject.required?.includes(k) || ++ (schemaObject.required === undefined && options.ctx.propertiesRequiredByDefault) || ++ ("default" in v && ++ options.ctx.defaultNonNullable && ++ !options.path?.includes("parameters") && ++ !options.path?.includes("requestBody") && ++ !options.path?.includes("requestBodies")) ++ ? undefined ++ : QUESTION_TOKEN; ++ let type = "$ref" in v ++ ? oapiRef(v.$ref) ++ : transformSchemaObject(v, { ++ ...options, ++ path: createRef([options.path, k]), ++ }); ++ if (typeof options.ctx.transform === "function") { ++ const result = options.ctx.transform(v, options); ++ if (result && typeof result === "object") { ++ if ("schema" in result) { ++ type = result.schema; ++ optional = result.questionToken ? QUESTION_TOKEN : optional; ++ } ++ else { ++ type = result; ++ } ++ } ++ } ++ const property = ts.factory.createPropertySignature(tsModifiers({ ++ readonly: options.ctx.immutable || ("readOnly" in v && !!v.readOnly), ++ }), tsPropertyIndex(k), optional, type); ++ addJSDocComment(v, property); ++ coreObjectType.push(property); ++ } ++ } ++ if (schemaObject.$defs && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { ++ const defKeys = []; ++ for (const [k, v] of Object.entries(schemaObject.$defs)) { ++ const property = ts.factory.createPropertySignature(tsModifiers({ ++ readonly: options.ctx.immutable || ("readonly" in v && !!v.readOnly), ++ }), tsPropertyIndex(k), undefined, transformSchemaObject(v, { ++ ...options, ++ path: createRef([options.path, "$defs", k]), ++ })); ++ addJSDocComment(v, property); ++ defKeys.push(property); ++ } ++ coreObjectType.push(ts.factory.createPropertySignature(undefined, tsPropertyIndex("$defs"), undefined, ts.factory.createTypeLiteralNode(defKeys))); ++ } ++ if (schemaObject.additionalProperties || options.ctx.additionalProperties) { ++ const hasExplicitAdditionalProperties = typeof schemaObject.additionalProperties === "object" && Object.keys(schemaObject.additionalProperties).length; ++ const addlType = hasExplicitAdditionalProperties ++ ? transformSchemaObject(schemaObject.additionalProperties, options) ++ : UNKNOWN; ++ return tsIntersection([ ++ ...(coreObjectType.length ? [ts.factory.createTypeLiteralNode(coreObjectType)] : []), ++ ts.factory.createTypeLiteralNode([ ++ ts.factory.createIndexSignature(tsModifiers({ ++ readonly: options.ctx.immutable, ++ }), [ ++ ts.factory.createParameterDeclaration(undefined, undefined, ts.factory.createIdentifier("key"), undefined, STRING), ++ ], addlType), ++ ]), ++ ]); ++ } ++ } ++ return coreObjectType.length ? ts.factory.createTypeLiteralNode(coreObjectType) : undefined; ++} ++//# sourceMappingURL=schema-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/schema-object.js.map b/package/dist/transform/schema-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..fbe11e11385076d2f4f0cf2e54fc616eec061420 +--- /dev/null ++++ b/package/dist/transform/schema-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"schema-object.js","sourceRoot":"","sources":["../../src/transform/schema-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EACL,OAAO,EACP,KAAK,EACL,IAAI,EACJ,MAAM,EACN,cAAc,EACd,MAAM,EACN,SAAS,EACT,OAAO,EACP,eAAe,EACf,OAAO,EACP,wBAAwB,EACxB,MAAM,EACN,cAAc,EACd,aAAa,EACb,SAAS,EACT,WAAW,EACX,UAAU,EACV,eAAe,EACf,QAAQ,EACR,OAAO,EACP,cAAc,GACf,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAOrF,MAAM,CAAC,OAAO,UAAU,qBAAqB,CAC3C,YAA4C,EAC5C,OAA6B;IAE7B,MAAM,IAAI,GAAG,oCAAoC,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IACzE,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,KAAK,UAAU,EAAE,CAAC;QACpD,MAAM,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACrE,IAAI,mBAAmB,EAAE,CAAC;YACxB,OAAO,mBAAmB,CAAC;QAC7B,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAKD,MAAM,UAAU,oCAAoC,CAClD,YAA4C,EAC5C,OAA6B;IAO7B,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAK,YAAwB,KAAK,IAAI,EAAE,CAAC;QACvC,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,OAAO,YAAY,KAAK,QAAQ,EAAE,CAAC;QACpE,MAAM,IAAI,KAAK,CACb,mCAAmC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,YAAY,OAAO,OAAO,CAAC,IAAI,EAAE,CACpH,CAAC;IACJ,CAAC;IAKD,IAAI,MAAM,IAAI,YAAY,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAKD,IAAI,YAAY,CAAC,KAAK,KAAK,IAAI,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;QACpE,OAAO,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;IACvC,CAAC;IAMD,IACE,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC;QAChC,CAAC,CAAC,CAAC,MAAM,IAAI,YAAY,CAAC,IAAI,YAAY,CAAC,IAAI,KAAK,QAAQ,CAAC;QAC7D,CAAC,CAAC,YAAY,IAAI,YAAY,CAAC;QAC/B,CAAC,CAAC,sBAAsB,IAAI,YAAY,CAAC,EACzC,CAAC;QAED,IACE,OAAO,CAAC,GAAG,CAAC,IAAI;YAChB,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAC,EAC5F,CAAC;YACD,IAAI,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAE9D,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;YACtD,MAAM,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;gBAChD,IAAI,EAAE,YAAY,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAC;gBAC9E,WAAW,EAAE,YAAY,CAAC,qBAAqB,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,oBAAoB,CAAC,EAAE,CAAC,CAAC,CAAC;aACjG,CAAC,CAAC,CAAC;YAGJ,IAAI,OAAO,GAAG,KAAK,CAAC;YACpB,MAAM,gBAAgB,GAAG,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE;gBAC9D,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;oBACvB,OAAO,GAAG,IAAI,CAAC;oBACf,OAAO,KAAK,CAAC;gBACf,CAAC;gBAED,OAAO,IAAI,CAAC;YACd,CAAC,CAAC,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,EAAE,gBAAuC,EAAE,QAAQ,EAAE;gBACnF,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW;gBACpC,MAAM,EAAE,IAAI;aAEb,CAAC,CAAC;YACH,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACjD,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC1C,CAAC;YACD,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;YAC9D,OAAO,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;QAC9C,CAAC;QACD,MAAM,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAClD,IACE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,YAAY,CAAC,QAAQ,CAAC;YACnG,CAAC,YAAY,CAAC,OAAO,EACrB,CAAC;YACD,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;QAED,MAAM,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;QAGpC,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,QAAQ,CAAC,EAAE,CAAC;YAC7G,IAAI,sBAAsB,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAE5E,sBAAsB,GAAG,sBAAsB,CAAC,OAAO,CAAC,oBAAoB,EAAE,EAAE,CAAC,CAAC;YAClF,sBAAsB,GAAG,GAAG,sBAAsB,QAAQ,CAAC;YAE3D,MAAM,eAAe,GAAG,wBAAwB,CAC9C,sBAAsB,EACtB,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,EAC3B,YAAY,CAAC,IAA2B,EACxC;gBACE,MAAM,EAAE,IAAI;gBACZ,QAAQ,EAAE,IAAI;gBACd,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY;aACvC,CACF,CAAC;YAEF,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QACjD,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAOD,SAAS,wBAAwB,CAAC,KAAyC;QACzE,MAAM,MAAM,GAAkB,EAAE,CAAC;QACjC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;QACpD,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAGD,SAAS,wBAAwB,CAAC,KAAyC,EAAE,QAAmB;QAC9F,MAAM,MAAM,GAAkB,EAAE,CAAC;QACjC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,QAAqB,CAAC;YAG1B,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;gBACnB,QAAQ,GAAG,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;gBAEhD,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,CAAe,IAAI,CAAC,IAAI,CAAC,CAAC;gBAG9D,IACE,QAAQ;oBACR,OAAO,QAAQ,KAAK,QAAQ;oBAC5B,YAAY,IAAI,QAAQ;oBAExB,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAC3D,CAAC;oBAED,MAAM,aAAa,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;oBACrF,IAAI,aAAa,CAAC,MAAM,EAAE,CAAC;wBACzB,QAAQ,GAAG,cAAc,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;oBAC/E,CAAC;gBACH,CAAC;YACH,CAAC;iBAEI,CAAC;gBACJ,MAAM,YAAY,GAAG,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC,CAAC;gBAC3C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;oBAC7D,YAAY,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;gBACtC,CAAC;gBACD,QAAQ,GAAG,qBAAqB,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,YAAY,EAAE,EAAE,OAAO,CAAC,CAAC;YACjF,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAGD,IAAI,SAAS,GAA4B,SAAS,CAAC;IAGnD,MAAM,cAAc,GAAG,yBAAyB,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;IACxE,MAAM,SAAS,GAAG,wBAAwB,CAAC,YAAY,CAAC,KAAK,IAAI,EAAE,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC5F,IAAI,cAAc,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QACvC,MAAM,KAAK,GAA4B,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAChG,SAAS,GAAG,cAAc,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACvG,CAAC;IAGD,MAAM,SAAS,GAAG,wBAAwB,CAAC,YAAY,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;IACrE,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QACrB,SAAS,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC;IACzE,CAAC;IAED,MAAM,SAAS,GAAG,wBAAwB,CACxC,YAAY,CAAC,KAAK;QAChB,CAAC,MAAM,IAAI,YAAY;YACrB,YAAY,CAAC,IAAI,KAAK,QAAQ;YAC7B,YAAY,CAAC,IAA2C,CAAC;QAC5D,EAAE,CACL,CAAC;IACF,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QAErB,IAAI,SAAS,CAAC,KAAK,CAAC,aAAa,CAAC,EAAE,CAAC;YACnC,SAAS,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC;QACzE,CAAC;aAAM,CAAC;YACN,SAAS,GAAG,cAAc,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACtF,CAAC;IACH,CAAC;IAGD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,IAAI,MAAM,IAAI,YAAY,EAAE,CAAC;YAC3B,SAAS,GAAG,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QAClF,CAAC;aAAM,CAAC;YACN,SAAS,GAAG,OAAO,CAAC;QACtB,CAAC;IACH,CAAC;IAED,IAAI,SAAS,KAAK,OAAO,IAAI,YAAY,CAAC,QAAQ,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;QAC5E,SAAS,GAAG,UAAU,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAKD,SAAS,yBAAyB,CAAC,YAA0B,EAAE,OAA6B;IAC1F,IAAI,MAAM,IAAI,YAAY,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;QAChD,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,KAAK,UAAU,EAAE,CAAC;YAChD,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;YAC5D,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;gBACzC,IAAI,QAAQ,IAAI,MAAM,EAAE,CAAC;oBACvB,IAAI,MAAM,CAAC,aAAa,EAAE,CAAC;wBACzB,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;oBACpE,CAAC;yBAAM,CAAC;wBACN,OAAO,MAAM,CAAC,MAAM,CAAC;oBACvB,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,OAAO,MAAM,CAAC;gBAChB,CAAC;YACH,CAAC;QACH,CAAC;QAID,IAAI,YAAY,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACjC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,YAAY,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YACnC,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,YAAY,CAAC,IAAI,KAAK,QAAQ,IAAI,YAAY,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACtE,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,YAAY,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACpC,OAAO,OAAO,CAAC;QACjB,CAAC;QAGD,IAAI,YAAY,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAElC,IAAI,QAAQ,GAAgB,OAAO,CAAC;YAEpC,IAAI,YAAY,CAAC,WAAW,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;gBAClE,MAAM,WAAW,GAAG,YAAY,CAAC,WAAW,IAAK,YAAY,CAAC,KAA4C,CAAC;gBAC3G,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;YAC7G,CAAC;iBAEI,IAAI,YAAY,CAAC,KAAK,EAAE,CAAC;gBAC5B,IAAI,MAAM,IAAI,YAAY,CAAC,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;oBACxE,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,qBAAqB,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;gBAChG,CAAC;qBAAM,CAAC;oBACN,QAAQ,GAAG,qBAAqB,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;gBAChE,CAAC;YACH,CAAC;YAED,MAAM,GAAG,GACP,OAAO,YAAY,CAAC,QAAQ,KAAK,QAAQ,IAAI,YAAY,CAAC,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;YACtG,MAAM,GAAG,GACP,OAAO,YAAY,CAAC,QAAQ,KAAK,QAAQ,IAAI,YAAY,CAAC,QAAQ,IAAI,CAAC,IAAI,GAAG,IAAI,YAAY,CAAC,QAAQ;gBACrG,CAAC,CAAC,YAAY,CAAC,QAAQ;gBACvB,CAAC,CAAC,SAAS,CAAC;YAChB,MAAM,gBAAgB,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YACjG,IACE,OAAO,CAAC,GAAG,CAAC,WAAW;gBACvB,CAAC,GAAG,KAAK,CAAC,IAAI,GAAG,KAAK,SAAS,CAAC;gBAChC,gBAAgB,GAAG,EAAE,EACrB,CAAC;gBACD,IAAI,GAAG,KAAK,GAAG,EAAE,CAAC;oBAChB,MAAM,QAAQ,GAAkB,EAAE,CAAC;oBACnC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;wBAC7B,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;oBAC1B,CAAC;oBACD,OAAO,OAAO,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;gBAC7D,CAAC;qBAAM,IAAK,YAAY,CAAC,QAAmB,GAAG,CAAC,EAAE,CAAC;oBAEjD,MAAM,OAAO,GAAkB,EAAE,CAAC;oBAElC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;wBAC3C,MAAM,QAAQ,GAAkB,EAAE,CAAC;wBACnC,KAAK,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;4BACnC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;wBAC1B,CAAC;wBACD,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC,CAAC;oBACzD,CAAC;oBACD,OAAO,OAAO,CAAC,OAAO,CAAC,CAAC;gBAC1B,CAAC;qBAEI,CAAC;oBACJ,MAAM,QAAQ,GAAkB,EAAE,CAAC;oBACnC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;wBAC7B,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;oBAC1B,CAAC;oBACD,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;oBACvF,OAAO,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;gBAClD,CAAC;YACH,CAAC;YAED,MAAM,SAAS,GACb,EAAE,CAAC,eAAe,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,eAAe,CAAC,QAAQ,CAAC;gBAC1D,CAAC,CAAC,QAAQ;gBACV,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;YAE/C,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS;gBAC1B,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,CAAC,UAAU,CAAC,eAAe,EAAE,SAAS,CAAC;gBAC7E,CAAC,CAAC,SAAS,CAAC;QAChB,CAAC;QAGD,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,CAAC;YAErE,MAAM,WAAW,GAAkB,EAAE,CAAC;YACtC,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;gBACtC,KAAK,MAAM,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;oBAClC,IACE,CAAC,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,MAAM,CAAC;wBACxF,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,EACpF,CAAC;wBACD,SAAS;oBACX,CAAC;oBACD,WAAW,CAAC,IAAI,CACd,CAAC,KAAK,MAAM,IAAI,CAAC,KAAK,IAAI;wBACxB,CAAC,CAAC,IAAI;wBACN,CAAC,CAAC,qBAAqB,CACnB,EAAE,GAAG,YAAY,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAkB,EAC9D,OAAO,CACR,CACN,CAAC;gBACJ,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,KAAK,MAAM,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;oBAClC,IAAI,CAAC,KAAK,MAAM,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;wBAC/B,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;4BAC1B,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;wBACzB,CAAC;oBACH,CAAC;yBAAM,CAAC;wBACN,WAAW,CAAC,IAAI,CAAC,qBAAqB,CAAC,EAAE,GAAG,YAAY,EAAE,IAAI,EAAE,CAAC,EAAkB,EAAE,OAAO,CAAC,CAAC,CAAC;oBACjG,CAAC;gBACH,CAAC;YACH,CAAC;YACD,OAAO,OAAO,CAAC,WAAW,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;IAGD,MAAM,cAAc,GAAqB,EAAE,CAAC;IAG5C,KAAK,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAU,EAAE,CAAC;QAC5C,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YACrB,SAAS;QACX,CAAC;QAMD,MAAM,aAAa,GACjB,CAAC,YAAY,CAAC,aAAa;YAC3B,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;YACpE,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;QACzD,IAAI,aAAa,EAAE,CAAC;YAClB,cAAc,CAAC,OAAO,CACpB,2BAA2B,CAAC,aAAa,EAAE;gBACzC,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,EAAE;gBACxB,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS;aAChC,CAAC,CACH,CAAC;YACF,MAAM;QACR,CAAC;IACH,CAAC;IAED,IACE,CAAC,YAAY,IAAI,YAAY,IAAI,YAAY,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC;QACxG,CAAC,sBAAsB,IAAI,YAAY,IAAI,YAAY,CAAC,oBAAoB,CAAC;QAC7E,CAAC,OAAO,IAAI,YAAY,IAAI,YAAY,CAAC,KAAK,CAAC,EAC/C,CAAC;QAED,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC;YACtD,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,UAAU,CAAC,YAAY,CAAC,UAAU,IAAI,EAAE,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC5E,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;oBAC9C,MAAM,IAAI,KAAK,CACb,GAAG,OAAO,CAAC,IAAI,sBAAsB,CAAC,iCACpC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CACtC,EAAE,CACH,CAAC;gBACJ,CAAC;gBAGD,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,CAAC;oBAClC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAe,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC7E,IAAI,QAAQ,EAAE,UAAU,EAAE,CAAC;wBACzB,SAAS;oBACX,CAAC;gBACH,CAAC;gBACD,IAAI,QAAQ,GACV,YAAY,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;oBAClC,CAAC,YAAY,CAAC,QAAQ,KAAK,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC;oBAChF,CAAC,SAAS,IAAI,CAAC;wBACb,OAAO,CAAC,GAAG,CAAC,kBAAkB;wBAC9B,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,YAAY,CAAC;wBACrC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,aAAa,CAAC;wBACtC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,CAAC,CAAC;oBACzC,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC,cAAc,CAAC;gBACrB,IAAI,IAAI,GACN,MAAM,IAAI,CAAC;oBACT,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;oBACjB,CAAC,CAAC,qBAAqB,CAAC,CAAC,EAAE;wBACvB,GAAG,OAAO;wBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;qBACnC,CAAC,CAAC;gBAET,IAAI,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,KAAK,UAAU,EAAE,CAAC;oBAChD,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAiB,EAAE,OAAO,CAAC,CAAC;oBACjE,IAAI,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;wBACzC,IAAI,QAAQ,IAAI,MAAM,EAAE,CAAC;4BACvB,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC;4BACrB,QAAQ,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,QAAQ,CAAC;wBAC9D,CAAC;6BAAM,CAAC;4BACN,IAAI,GAAG,MAAM,CAAC;wBAChB,CAAC;oBACH,CAAC;gBACH,CAAC;gBAED,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC7B,WAAW,CAAC;oBAC9B,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;iBACrE,CAAC,EACkB,eAAe,CAAC,CAAC,CAAC,EAClB,QAAQ,EACR,IAAI,CACzB,CAAC;gBACF,eAAe,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;gBAC7B,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAChC,CAAC;QACH,CAAC;QAGD,IAAI,YAAY,CAAC,KAAK,IAAI,OAAO,YAAY,CAAC,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC;YAC3G,MAAM,OAAO,GAAqB,EAAE,CAAC;YACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;gBACxD,MAAM,QAAQ,GAAG,EAAE,CAAC,OAAO,CAAC,uBAAuB,CAC9B,WAAW,CAAC;oBAC7B,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;iBACrE,CAAC,EACkB,eAAe,CAAC,CAAC,CAAC,EAClB,SAAS,EACT,qBAAqB,CAAC,CAAC,EAAE;oBAC3C,GAAG,OAAO;oBACV,IAAI,EAAE,SAAS,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;iBAC5C,CAAC,CACH,CAAC;gBACF,eAAe,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;gBAC7B,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YACzB,CAAC;YACD,cAAc,CAAC,IAAI,CACjB,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,SAAS,EACT,eAAe,CAAC,OAAO,CAAC,EACxB,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAC9D,CACF,CAAC;QACJ,CAAC;QAGD,IAAI,YAAY,CAAC,oBAAoB,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,CAAC;YAC1E,MAAM,+BAA+B,GACnC,OAAO,YAAY,CAAC,oBAAoB,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,oBAAoB,CAAC,CAAC,MAAM,CAAC;YACjH,MAAM,QAAQ,GAAG,+BAA+B;gBAC9C,CAAC,CAAC,qBAAqB,CAAC,YAAY,CAAC,oBAAoC,EAAE,OAAO,CAAC;gBACnF,CAAC,CAAC,OAAO,CAAC;YACZ,OAAO,cAAc,CAAC;gBACpB,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;gBACpF,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC;oBAC/B,EAAE,CAAC,OAAO,CAAC,oBAAoB,CACZ,WAAW,CAAC;wBAC3B,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS;qBAChC,CAAC,EACe;wBACf,EAAE,CAAC,OAAO,CAAC,0BAA0B,CACd,SAAS,EACT,SAAS,EACT,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAClC,SAAS,EACT,MAAM,CAC5B;qBACF,EACgB,QAAQ,CAC1B;iBACF,CAAC;aACH,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9F,CAAC"} +\ No newline at end of file +diff --git a/package/dist/transform/webhooks-object.d.ts b/package/dist/transform/webhooks-object.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..12cd2a4868227e4c4ab4dae316ef193e00d52568 +--- /dev/null ++++ b/package/dist/transform/webhooks-object.d.ts +@@ -0,0 +1,3 @@ ++import ts from "typescript"; ++import type { GlobalContext, WebhooksObject } from "../types.js"; ++export default function transformWebhooksObject(webhooksObject: WebhooksObject, options: GlobalContext): ts.TypeNode; +diff --git a/package/dist/transform/webhooks-object.js b/package/dist/transform/webhooks-object.js +new file mode 100644 +index 0000000000000000000000000000000000000000..3f2848200b31d4858e1cc0b391511536b070cd8d +--- /dev/null ++++ b/package/dist/transform/webhooks-object.js +@@ -0,0 +1,17 @@ ++import ts from "typescript"; ++import { tsModifiers, tsPropertyIndex } from "../lib/ts.js"; ++import { createRef, getEntries } from "../lib/utils.js"; ++import transformPathItemObject from "./path-item-object.js"; ++export default function transformWebhooksObject(webhooksObject, options) { ++ const type = []; ++ for (const [name, pathItemObject] of getEntries(webhooksObject, options)) { ++ type.push(ts.factory.createPropertySignature(tsModifiers({ ++ readonly: options.immutable, ++ }), tsPropertyIndex(name), undefined, transformPathItemObject(pathItemObject, { ++ path: createRef(["webhooks", name]), ++ ctx: options, ++ }))); ++ } ++ return ts.factory.createTypeLiteralNode(type); ++} ++//# sourceMappingURL=webhooks-object.js.map +\ No newline at end of file +diff --git a/package/dist/transform/webhooks-object.js.map b/package/dist/transform/webhooks-object.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..e3c7c4f9663e5b14cbdf0072c8cd928f2d3b969f +--- /dev/null ++++ b/package/dist/transform/webhooks-object.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"webhooks-object.js","sourceRoot":"","sources":["../../src/transform/webhooks-object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAExD,OAAO,uBAAuB,MAAM,uBAAuB,CAAC;AAE5D,MAAM,CAAC,OAAO,UAAU,uBAAuB,CAAC,cAA8B,EAAE,OAAsB;IACpG,MAAM,IAAI,GAAqB,EAAE,CAAC;IAElC,KAAK,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,IAAI,UAAU,CAAC,cAAc,EAAE,OAAO,CAAC,EAAE,CAAC;QACzE,IAAI,CAAC,IAAI,CACP,EAAE,CAAC,OAAO,CAAC,uBAAuB,CACZ,WAAW,CAAC;YAC9B,QAAQ,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC,EACkB,eAAe,CAAC,IAAI,CAAC,EACrB,SAAS,EACT,uBAAuB,CAAC,cAAc,EAAE;YAC1D,IAAI,EAAE,SAAS,CAAC,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;YACnC,GAAG,EAAE,OAAO;SACb,CAAC,CACH,CACF,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;AAChD,CAAC"} +\ No newline at end of file +diff --git a/package/dist/types.d.ts b/package/dist/types.d.ts +new file mode 100644 +index 0000000000000000000000000000000000000000..c08afb1fda3b04cca96e9ff887a7f5336fa6b087 +--- /dev/null ++++ b/package/dist/types.d.ts +@@ -0,0 +1,372 @@ ++import type { Config as RedoclyConfig } from "@redocly/openapi-core"; ++import type { PathLike } from "node:fs"; ++import type ts from "typescript"; ++export interface Extensable { ++ [key: `x-${string}`]: any; ++} ++export interface OpenAPI3 extends Extensable { ++ openapi: string; ++ info: InfoObject; ++ jsonSchemaDialect?: string; ++ servers?: ServerObject[]; ++ paths?: PathsObject; ++ webhooks?: { ++ [id: string]: PathItemObject | ReferenceObject; ++ }; ++ components?: ComponentsObject; ++ security?: SecurityRequirementObject[]; ++ tags?: TagObject[]; ++ externalDocs?: ExternalDocumentationObject; ++ $defs?: $defs; ++} ++export interface InfoObject extends Extensable { ++ title: string; ++ summary?: string; ++ description?: string; ++ termsOfService?: string; ++ contact?: ContactObject; ++ license?: LicenseObject; ++ version: string; ++} ++export interface ContactObject extends Extensable { ++ name?: string; ++ url?: string; ++ email?: string; ++} ++export interface LicenseObject extends Extensable { ++ name: string; ++ identifier: string; ++ url: string; ++} ++export interface ServerObject extends Extensable { ++ url: string; ++ description: string; ++ variables: { ++ [name: string]: ServerVariableObject; ++ }; ++} ++export interface ServerVariableObject extends Extensable { ++ enum?: string[]; ++ default: string; ++ description?: string; ++} ++export interface ComponentsObject extends Extensable { ++ schemas?: Record; ++ responses?: Record; ++ parameters?: Record; ++ examples?: Record; ++ requestBodies?: Record; ++ headers?: Record; ++ securitySchemes?: Record; ++ links?: Record; ++ callbacks?: Record; ++ pathItems?: Record; ++} ++export interface PathsObject { ++ [pathname: string]: PathItemObject | ReferenceObject; ++} ++export interface WebhooksObject { ++ [name: string]: PathItemObject; ++} ++export interface PathItemObject extends Extensable { ++ get?: OperationObject | ReferenceObject; ++ put?: OperationObject | ReferenceObject; ++ post?: OperationObject | ReferenceObject; ++ delete?: OperationObject | ReferenceObject; ++ options?: OperationObject | ReferenceObject; ++ head?: OperationObject | ReferenceObject; ++ patch?: OperationObject | ReferenceObject; ++ trace?: OperationObject | ReferenceObject; ++ servers?: ServerObject[]; ++ parameters?: (ParameterObject | ReferenceObject)[]; ++} ++export interface OperationObject extends Extensable { ++ tags?: string[]; ++ summary?: string; ++ description?: string; ++ externalDocs?: ExternalDocumentationObject; ++ operationId?: string; ++ parameters?: (ParameterObject | ReferenceObject)[]; ++ requestBody?: RequestBodyObject | ReferenceObject; ++ responses?: ResponsesObject; ++ callbacks?: Record; ++ deprecated?: boolean; ++ security?: SecurityRequirementObject[]; ++ servers?: ServerObject[]; ++} ++export interface ExternalDocumentationObject extends Extensable { ++ description?: string; ++ url: string; ++} ++export interface ParameterObject extends Extensable { ++ name: string; ++ in: "query" | "header" | "path" | "cookie"; ++ description?: string; ++ required?: boolean; ++ deprecated?: boolean; ++ allowEmptyValue?: boolean; ++ style?: string; ++ explode?: boolean; ++ allowReserved?: boolean; ++ schema?: SchemaObject; ++ example?: any; ++ examples?: { ++ [name: string]: ExampleObject | ReferenceObject; ++ }; ++ content?: { ++ [contentType: string]: MediaTypeObject | ReferenceObject; ++ }; ++} ++export interface RequestBodyObject extends Extensable { ++ description?: string; ++ content: { ++ [contentType: string]: MediaTypeObject | ReferenceObject; ++ }; ++ required?: boolean; ++} ++export interface MediaTypeObject extends Extensable { ++ schema?: SchemaObject | ReferenceObject; ++ example?: any; ++ examples?: { ++ [name: string]: ExampleObject | ReferenceObject; ++ }; ++ encoding?: { ++ [propertyName: string]: EncodingObject; ++ }; ++} ++export interface EncodingObject extends Extensable { ++ contentType?: string; ++ headers?: { ++ [name: string]: HeaderObject | ReferenceObject; ++ }; ++ style?: string; ++ explode?: string; ++ allowReserved?: string; ++} ++export type ResponsesObject = { ++ [responseCode: string]: ResponseObject | ReferenceObject; ++} & { ++ default?: ResponseObject | ReferenceObject; ++}; ++export interface ResponseObject extends Extensable { ++ description: string; ++ headers?: { ++ [name: string]: HeaderObject | ReferenceObject; ++ }; ++ content?: { ++ [contentType: string]: MediaTypeObject; ++ }; ++ links?: { ++ [name: string]: LinkObject | ReferenceObject; ++ }; ++} ++export type CallbackObject = Record; ++export interface ExampleObject extends Extensable { ++ summary?: string; ++ description?: string; ++ value?: any; ++ externalValue?: string; ++} ++export interface LinkObject extends Extensable { ++ operationRef?: string; ++ operationId?: string; ++ parameters?: { ++ [name: string]: `$${string}`; ++ }; ++ requestBody?: `$${string}`; ++ description?: string; ++ server?: ServerObject; ++} ++export type HeaderObject = Omit; ++export interface TagObject extends Extensable { ++ name: string; ++ description?: string; ++ externalDocs?: ExternalDocumentationObject; ++} ++export interface ReferenceObject extends Extensable { ++ $ref: string; ++ summary?: string; ++ description?: string; ++} ++export type SchemaObject = { ++ discriminator?: DiscriminatorObject; ++ xml?: XMLObject; ++ externalDocs?: ExternalDocumentationObject; ++ example?: any; ++ title?: string; ++ description?: string; ++ $comment?: string; ++ deprecated?: boolean; ++ readOnly?: boolean; ++ writeOnly?: boolean; ++ enum?: unknown[]; ++ const?: unknown; ++ default?: unknown; ++ format?: string; ++ nullable?: boolean; ++ oneOf?: (SchemaObject | ReferenceObject)[]; ++ allOf?: (SchemaObject | ReferenceObject)[]; ++ anyOf?: (SchemaObject | ReferenceObject)[]; ++ required?: string[]; ++ [key: `x-${string}`]: any; ++} & (StringSubtype | NumberSubtype | IntegerSubtype | ArraySubtype | BooleanSubtype | NullSubtype | ObjectSubtype | { ++ type: ("string" | "number" | "integer" | "array" | "boolean" | "null" | "object")[]; ++}); ++export interface TransformObject { ++ schema: ts.TypeNode; ++ questionToken: boolean; ++} ++export interface StringSubtype { ++ type: "string" | ["string", "null"]; ++ enum?: (string | ReferenceObject)[]; ++} ++export interface NumberSubtype { ++ type: "number" | ["number", "null"]; ++ minimum?: number; ++ maximum?: number; ++ enum?: (number | ReferenceObject)[]; ++} ++export interface IntegerSubtype { ++ type: "integer" | ["integer", "null"]; ++ minimum?: number; ++ maximum?: number; ++ enum?: (number | ReferenceObject)[]; ++} ++export interface ArraySubtype { ++ type: "array" | ["array", "null"]; ++ prefixItems?: (SchemaObject | ReferenceObject)[]; ++ items?: SchemaObject | ReferenceObject | (SchemaObject | ReferenceObject)[]; ++ minItems?: number; ++ maxItems?: number; ++ enum?: (SchemaObject | ReferenceObject)[]; ++} ++export interface BooleanSubtype { ++ type: "boolean" | ["boolean", "null"]; ++ enum?: (boolean | ReferenceObject)[]; ++} ++export interface NullSubtype { ++ type: "null"; ++} ++export interface ObjectSubtype { ++ type: "object" | ["object", "null"]; ++ properties?: { ++ [name: string]: SchemaObject | ReferenceObject; ++ }; ++ additionalProperties?: boolean | Record | SchemaObject | ReferenceObject; ++ required?: string[]; ++ allOf?: (SchemaObject | ReferenceObject)[]; ++ anyOf?: (SchemaObject | ReferenceObject)[]; ++ enum?: (SchemaObject | ReferenceObject)[]; ++ $defs?: $defs; ++} ++export interface DiscriminatorObject { ++ propertyName: string; ++ mapping?: Record; ++ oneOf?: string[]; ++} ++export interface XMLObject extends Extensable { ++ name?: string; ++ namespace?: string; ++ prefix?: string; ++ attribute?: boolean; ++ wrapped?: boolean; ++} ++export type SecuritySchemeObject = { ++ description?: string; ++ [key: `x-${string}`]: any; ++} & ({ ++ type: "apiKey"; ++ name: string; ++ in: "query" | "header" | "cookie"; ++} | { ++ type: "http"; ++ scheme: string; ++ bearer?: string; ++} | { ++ type: "mutualTLS"; ++} | { ++ type: "oauth2"; ++ flows: OAuthFlowsObject; ++} | { ++ type: "openIdConnect"; ++ openIdConnectUrl: string; ++}); ++export interface OAuthFlowsObject extends Extensable { ++ implicit?: OAuthFlowObject; ++ password?: OAuthFlowObject; ++ clientCredentials?: OAuthFlowObject; ++ authorizationCode?: OAuthFlowObject; ++} ++export interface OAuthFlowObject extends Extensable { ++ authorizationUrl: string; ++ tokenUrl: string; ++ refreshUrl: string; ++ scopes: { ++ [name: string]: string; ++ }; ++} ++export type SecurityRequirementObject = { ++ [P in keyof ComponentsObject["securitySchemes"]]?: string[]; ++}; ++export interface OpenAPITSOptions { ++ additionalProperties?: boolean; ++ alphabetize?: boolean; ++ arrayLength?: boolean; ++ emptyObjectsUnknown?: boolean; ++ cwd?: PathLike; ++ defaultNonNullable?: boolean; ++ excludeDeprecated?: boolean; ++ transform?: (schemaObject: SchemaObject, options: TransformNodeOptions) => ts.TypeNode | TransformObject | undefined; ++ postTransform?: (type: ts.TypeNode, options: TransformNodeOptions) => ts.TypeNode | undefined; ++ immutable?: boolean; ++ silent?: boolean; ++ version?: number; ++ exportType?: boolean; ++ enum?: boolean; ++ enumValues?: boolean; ++ dedupeEnums?: boolean; ++ pathParamsAsTypes?: boolean; ++ propertiesRequiredByDefault?: boolean; ++ rootTypes?: boolean; ++ rootTypesNoSchemaPrefix?: boolean; ++ redocly?: RedoclyConfig; ++ inject?: string; ++ makePathsEnum?: boolean; ++ generatePathParams?: boolean; ++} ++export interface GlobalContext { ++ additionalProperties: boolean; ++ alphabetize: boolean; ++ arrayLength: boolean; ++ defaultNonNullable: boolean; ++ discriminators: { ++ objects: Record; ++ refsHandled: string[]; ++ }; ++ emptyObjectsUnknown: boolean; ++ enum: boolean; ++ enumValues: boolean; ++ dedupeEnums: boolean; ++ excludeDeprecated: boolean; ++ exportType: boolean; ++ immutable: boolean; ++ injectFooter: ts.Node[]; ++ pathParamsAsTypes: boolean; ++ postTransform: OpenAPITSOptions["postTransform"]; ++ propertiesRequiredByDefault: boolean; ++ rootTypes: boolean; ++ rootTypesNoSchemaPrefix: boolean; ++ redoc: RedoclyConfig; ++ silent: boolean; ++ transform: OpenAPITSOptions["transform"]; ++ resolve($ref: string): T | undefined; ++ inject?: string; ++ makePathsEnum: boolean; ++ generatePathParams: boolean; ++} ++export type $defs = Record; ++export interface TransformNodeOptions { ++ path?: string; ++ schema?: SchemaObject | ReferenceObject; ++ ctx: GlobalContext; ++} +diff --git a/package/dist/types.js b/package/dist/types.js +new file mode 100644 +index 0000000000000000000000000000000000000000..718fd38ae40c67ea23b242517cf9919f602c5a3e +--- /dev/null ++++ b/package/dist/types.js +@@ -0,0 +1,2 @@ ++export {}; ++//# sourceMappingURL=types.js.map +\ No newline at end of file +diff --git a/package/dist/types.js.map b/package/dist/types.js.map +new file mode 100644 +index 0000000000000000000000000000000000000000..c768b79002615c0e69cc6efdcad6a509c1abaaec +--- /dev/null ++++ b/package/dist/types.js.map +@@ -0,0 +1 @@ ++{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""} +\ No newline at end of file +diff --git a/package.json b/package.json +index 4893afdec25f506f62d44f64fe0861c411cb7fae..8da19442a2d78a8d9d0ac19cea4d16eeb64506f7 100644 +--- a/package.json ++++ b/package.json +@@ -49,6 +49,7 @@ + "ansi-colors": "^4.1.3", + "change-case": "^5.4.4", + "parse-json": "^8.3.0", ++ "scule": "^1.3.0", + "supports-color": "^10.2.2", + "yargs-parser": "^21.1.1" + }, +@@ -57,7 +58,7 @@ + "@types/js-yaml": "4.0.9", + "degit": "2.8.4", + "execa": "^9.6.1", +- "strip-ansi": "7.1.2", ++ "strip-ansi": "7.2.0", + "typescript": "^5.9.3", + "vite-node": "5.3.0" + }, +diff --git a/src/transform/schema-object.ts b/src/transform/schema-object.ts +index 58745d072e4c8362a5f979c9d02fa04ecd14345a..20196ea453b93a4a9a956c24dc8f343d8a89492d 100644 +--- a/src/transform/schema-object.ts ++++ b/src/transform/schema-object.ts +@@ -16,7 +16,6 @@ import { + tsLiteral, + tsModifiers, + tsNullable, +- tsOmit, + tsPropertyIndex, + tsRecord, + tsUnion, +@@ -94,112 +93,119 @@ export function transformSchemaObjectWithComposition( + if ( + Array.isArray(schemaObject.enum) && + (!("type" in schemaObject) || schemaObject.type !== "object") && +- !("properties" in schemaObject) && +- !("additionalProperties" in schemaObject) ++ !("properties" in schemaObject) + ) { +- // hoist enum to top level if string/number enum and option is enabled +- if (shouldTransformToTsEnum(options, schemaObject)) { +- let enumName = parseRef(options.path ?? "").pointer.join("/"); +- // allow #/components/schemas to have simpler names +- enumName = enumName.replace("components/schemas", ""); +- const metadata = schemaObject.enum.map((_, i) => ({ +- name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], +- description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i], +- })); +- +- // enums can contain null values, but dont want to output them +- let hasNull = false; +- const validSchemaEnums = schemaObject.enum.filter((enumValue) => { +- if (enumValue === null) { +- hasNull = true; +- return false; ++ const hasAdditionalProperties = "additionalProperties" in schemaObject && !!schemaObject.additionalProperties; ++ ++ if (!hasAdditionalProperties || (schemaObject.type === "string" && hasAdditionalProperties)) { ++ // hoist enum to top level if string/number enum and option is enabled ++ if (shouldTransformToTsEnum(options, schemaObject)) { ++ let enumName = parseRef(options.path ?? "").pointer.join("/"); ++ // allow #/components/schemas to have simpler names ++ enumName = enumName.replace("components/schemas", ""); ++ const metadata = schemaObject.enum.map((_, i) => ({ ++ name: schemaObject["x-enum-varnames"]?.[i] ?? schemaObject["x-enumNames"]?.[i], ++ description: schemaObject["x-enum-descriptions"]?.[i] ?? schemaObject["x-enumDescriptions"]?.[i], ++ })); ++ ++ // enums can contain null values, but dont want to output them ++ let hasNull = false; ++ const validSchemaEnums = schemaObject.enum.filter((enumValue) => { ++ if (enumValue === null) { ++ hasNull = true; ++ return false; ++ } ++ ++ return true; ++ }); ++ const enumType = tsEnum(enumName, validSchemaEnums as (string | number)[], metadata, { ++ shouldCache: options.ctx.dedupeEnums, ++ export: true, ++ // readonly: TS enum do not support the readonly modifier ++ }); ++ if (!options.ctx.injectFooter.includes(enumType)) { ++ options.ctx.injectFooter.push(enumType); + } ++ const ref = ts.factory.createTypeReferenceNode(enumType.name); + +- return true; +- }); +- const enumType = tsEnum(enumName, validSchemaEnums as (string | number)[], metadata, { +- shouldCache: options.ctx.dedupeEnums, +- export: true, +- // readonly: TS enum do not support the readonly modifier +- }); +- if (!options.ctx.injectFooter.includes(enumType)) { +- options.ctx.injectFooter.push(enumType); ++ const finalType: ts.TypeNode = hasNull ? tsUnion([ref, NULL]) : ref; ++ ++ return applyAdditionalPropertiesToEnum(hasAdditionalProperties, finalType, schemaObject); ++ } ++ ++ const enumType = schemaObject.enum.map(tsLiteral); ++ if ((Array.isArray(schemaObject.type) && schemaObject.type.includes("null")) || schemaObject.nullable) { ++ enumType.push(NULL); + } +- const ref = ts.factory.createTypeReferenceNode(enumType.name); +- return hasNull ? tsUnion([ref, NULL]) : ref; +- } +- const enumType = schemaObject.enum.map(tsLiteral); +- if ((Array.isArray(schemaObject.type) && schemaObject.type.includes("null")) || schemaObject.nullable) { +- enumType.push(NULL); +- } + +- const unionType = tsUnion(enumType); +- +- // hoist array with valid enum values to top level if string/number enum and option is enabled +- if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { +- const parsed = parseRef(options.path ?? ""); +- let enumValuesVariableName = parsed.pointer.join("/"); +- // allow #/components/schemas to have simpler names +- enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); +- enumValuesVariableName = `${enumValuesVariableName}Values`; +- +- // build a ref path for the type that ignores union indices (anyOf/oneOf) so +- // type references remain stable even when names include union positions +- const cleanedPointer: string[] = []; +- // Track ALL properties after a oneOf/anyOf that need Extract<> narrowing. +- // We apply Extract<> before EVERY property access after a union index because: +- // - When the property exists on ALL variants, Extract<> is a no-op (returns same type) +- // - When the property only exists on SOME variants, it correctly narrows the union +- // - When both variants have same property name but different inner schemas, +- // we still narrow at each level to handle nested unions correctly +- // This robust approach handles both simple and complex union structures. +- const extractProperties: string[] = []; +- for (let i = 0; i < parsed.pointer.length; i++) { +- // Example: #/paths/analytics/data/get/responses/400/content/application/json/anyOf/0/message +- const segment = parsed.pointer[i]; +- if ((segment === "anyOf" || segment === "oneOf") && i < parsed.pointer.length - 1) { +- const next = parsed.pointer[i + 1]; +- if (/^\d+$/.test(next)) { +- // If we encounter something like "anyOf/0", we want to skip that part of the path +- i++; +- // Collect ALL remaining segments after the union index. +- // Each one will be wrapped with Extract<> to safely narrow the type +- // at each level, handling both top-level and nested union variants. +- const remainingSegments = parsed.pointer.slice(i + 1); +- for (const seg of remainingSegments) { +- // Skip union keywords and indices, only add actual property names +- if (seg !== "anyOf" && seg !== "oneOf" && !/^\d+$/.test(seg)) { +- extractProperties.push(seg); ++ const unionType = applyAdditionalPropertiesToEnum(hasAdditionalProperties, tsUnion(enumType), schemaObject); ++ ++ // hoist array with valid enum values to top level if string/number enum and option is enabled ++ if (options.ctx.enumValues && schemaObject.enum.every((v) => typeof v === "string" || typeof v === "number")) { ++ const parsed = parseRef(options.path ?? ""); ++ let enumValuesVariableName = parsed.pointer.join("/"); ++ // allow #/components/schemas to have simpler names ++ enumValuesVariableName = enumValuesVariableName.replace("components/schemas", ""); ++ enumValuesVariableName = `${enumValuesVariableName}Values`; ++ ++ // build a ref path for the type that ignores union indices (anyOf/oneOf) so ++ // type references remain stable even when names include union positions ++ const cleanedPointer: string[] = []; ++ // Track ALL properties after a oneOf/anyOf that need Extract<> narrowing. ++ // We apply Extract<> before EVERY property access after a union index because: ++ // - When the property exists on ALL variants, Extract<> is a no-op (returns same type) ++ // - When the property only exists on SOME variants, it correctly narrows the union ++ // - When both variants have same property name but different inner schemas, ++ // we still narrow at each level to handle nested unions correctly ++ // This robust approach handles both simple and complex union structures. ++ const extractProperties: string[] = []; ++ for (let i = 0; i < parsed.pointer.length; i++) { ++ // Example: #/paths/analytics/data/get/responses/400/content/application/json/anyOf/0/message ++ const segment = parsed.pointer[i]; ++ if ((segment === "anyOf" || segment === "oneOf") && i < parsed.pointer.length - 1) { ++ const next = parsed.pointer[i + 1]; ++ if (/^\d+$/.test(next)) { ++ // If we encounter something like "anyOf/0", we want to skip that part of the path ++ i++; ++ // Collect ALL remaining segments after the union index. ++ // Each one will be wrapped with Extract<> to safely narrow the type ++ // at each level, handling both top-level and nested union variants. ++ const remainingSegments = parsed.pointer.slice(i + 1); ++ for (const seg of remainingSegments) { ++ // Skip union keywords and indices, only add actual property names ++ if (seg !== "anyOf" && seg !== "oneOf" && !/^\d+$/.test(seg)) { ++ extractProperties.push(seg); ++ } + } ++ continue; + } +- continue; + } ++ cleanedPointer.push(segment); + } +- cleanedPointer.push(segment); ++ const cleanedRefPath = createRef(cleanedPointer); ++ ++ const enumValuesArray = tsArrayLiteralExpression( ++ enumValuesVariableName, ++ // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type ++ fromAdditionalProperties ++ ? ts.factory.createIndexedAccessTypeNode( ++ oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }), ++ ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("string")), ++ ) ++ : oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }), ++ schemaObject.enum as (string | number)[], ++ { ++ export: true, ++ readonly: true, ++ injectFooter: options.ctx.injectFooter, ++ }, ++ ); ++ ++ options.ctx.injectFooter.push(enumValuesArray); + } +- const cleanedRefPath = createRef(cleanedPointer); +- +- const enumValuesArray = tsArrayLiteralExpression( +- enumValuesVariableName, +- // If fromAdditionalProperties is true we are dealing with a record type and we should append [string] to the generated type +- fromAdditionalProperties +- ? ts.factory.createIndexedAccessTypeNode( +- oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }), +- ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("string")), +- ) +- : oapiRef(cleanedRefPath, undefined, { deep: true, extractProperties }), +- schemaObject.enum as (string | number)[], +- { +- export: true, +- readonly: true, +- injectFooter: options.ctx.injectFooter, +- }, +- ); + +- options.ctx.injectFooter.push(enumValuesArray); ++ return unionType; + } +- +- return unionType; + } + + /** +@@ -258,13 +264,7 @@ export function transformSchemaObjectWithComposition( + itemType = transformSchemaObject({ ...item, required: itemRequired }, options); + } + +- const discriminator = +- ("$ref" in item && options.ctx.discriminators.objects[item.$ref]) || (item as any).discriminator; +- if (discriminator) { +- output.push(tsOmit(itemType, [discriminator.propertyName])); +- } else { +- output.push(itemType); +- } ++ output.push(itemType); + } + return output; + } +@@ -525,7 +525,7 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor + ("$defs" in schemaObject && schemaObject.$defs) + ) { + // properties +- if (Object.keys(schemaObject.properties ?? {}).length) { ++ if ("properties" in schemaObject && schemaObject.properties && Object.keys(schemaObject?.properties).length) { + for (const [k, v] of getEntries(schemaObject.properties ?? {}, options.ctx)) { + if ((typeof v !== "object" && typeof v !== "boolean") || Array.isArray(v)) { + throw new Error( +@@ -609,7 +609,7 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor + } + + // $defs +- if (schemaObject.$defs && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { ++ if ("$defs" in schemaObject && typeof schemaObject.$defs === "object" && Object.keys(schemaObject.$defs).length) { + const defKeys: ts.TypeElement[] = []; + for (const [k, v] of Object.entries(schemaObject.$defs)) { + const defReadOnly = "readOnly" in v && !!v.readOnly; +@@ -661,8 +661,9 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor + schemaObject.additionalProperties === true || + (typeof schemaObject.additionalProperties === "object" && + Object.keys(schemaObject.additionalProperties).length === 0); ++ const patternProperties = hasKey(schemaObject, "patternProperties") ? schemaObject.patternProperties : undefined; + const hasExplicitPatternProperties = +- typeof schemaObject.patternProperties === "object" && Object.keys(schemaObject.patternProperties).length; ++ typeof patternProperties === "object" && patternProperties !== null && Object.keys(patternProperties).length > 0; + const stringIndexTypes = []; + if (hasExplicitAdditionalProperties) { + stringIndexTypes.push(transformSchemaObject(schemaObject.additionalProperties as SchemaObject, options, true)); +@@ -670,8 +671,11 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor + if (hasImplicitAdditionalProperties || (!schemaObject.additionalProperties && options.ctx.additionalProperties)) { + stringIndexTypes.push(UNKNOWN); + } +- if (hasExplicitPatternProperties) { +- for (const [_, v] of getEntries(schemaObject.patternProperties ?? {}, options.ctx)) { ++ if (hasExplicitPatternProperties && patternProperties && typeof patternProperties === "object") { ++ for (const [_, v] of getEntries( ++ patternProperties as Record, ++ options.ctx, ++ )) { + stringIndexTypes.push(transformSchemaObject(v, options)); + } + } +@@ -717,6 +721,19 @@ function hasKey(possibleObject: unknown, key: K): possibleObje + return typeof possibleObject === "object" && possibleObject !== null && key in possibleObject; + } + ++function applyAdditionalPropertiesToEnum( ++ hasAdditionalProperties: boolean, ++ unionType: ts.TypeNode, ++ schemaObject: SchemaObject, ++) { ++ // If additionalProperties is true, add (string & {}) to the union ++ if (hasAdditionalProperties && schemaObject.type === "string") { ++ const stringAndEmptyObject = tsIntersection([STRING, ts.factory.createTypeLiteralNode([])]); ++ return tsUnion([unionType, stringAndEmptyObject]); ++ } ++ return unionType; ++} ++ + /** Wrap type with $Read or $Write marker when readWriteMarkers flag is enabled */ + function wrapWithReadWriteMarker( + type: ts.TypeNode, +diff --git a/src/types.ts b/src/types.ts +index 8a511e1e876827f1fa76316afe2fb34fe44dc653..d19185cc61a6ae7603fbbab300feb645e335c02a 100644 +--- a/src/types.ts ++++ b/src/types.ts +@@ -436,6 +436,7 @@ export type SchemaObject = { + const?: unknown; + default?: unknown; + format?: string; ++ additionalProperties?: boolean | Record | SchemaObject | ReferenceObject; + /** @deprecated in 3.1 (still valid for 3.0) */ + nullable?: boolean; + oneOf?: (SchemaObject | ReferenceObject)[]; diff --git a/api/client/javascript/pnpm-lock.yaml b/api/client/javascript/pnpm-lock.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e67b6e91628be83f289f862a7247eb3a57bce5fa --- /dev/null +++ b/api/client/javascript/pnpm-lock.yaml @@ -0,0 +1,3145 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +overrides: + vite@>=7.0.0 <=7.3.1: '>=7.3.2' + vite@>=7.1.0 <=7.3.1: '>=7.3.2' + +patchedDependencies: + openapi-typescript: + hash: 0e016926efaca4cd6909b2bf6c9b2f03eb66a5084b7bdbf10313eeee90793e01 + path: patches/openapi-typescript.patch + +importers: + + .: + dependencies: + openapi-fetch: + specifier: 0.17.0 + version: 0.17.0 + openapi-typescript-helpers: + specifier: 0.1.0 + version: 0.1.0 + devDependencies: + '@biomejs/biome': + specifier: 2.4.16 + version: 2.4.16 + '@fetch-mock/vitest': + specifier: 0.2.18 + version: 0.2.18(vitest@4.1.8(@types/node@25.9.2)(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))) + '@knighted/duel': + specifier: 4.1.0 + version: 4.1.0(typescript@5.9.3) + '@types/node': + specifier: 25.9.2 + version: 25.9.2 + '@types/node-fetch': + specifier: 2.6.13 + version: 2.6.13 + '@types/react': + specifier: 19.2.17 + version: 19.2.17 + fetch-mock: + specifier: 12.6.0 + version: 12.6.0 + openapi-typescript: + specifier: 7.13.0 + version: 7.13.0(patch_hash=0e016926efaca4cd6909b2bf6c9b2f03eb66a5084b7bdbf10313eeee90793e01)(typescript@5.9.3) + orval: + specifier: 8.15.0 + version: 8.15.0(prettier@3.8.3)(typescript@5.9.3) + prettier: + specifier: 3.8.3 + version: 3.8.3 + react: + specifier: 19.2.7 + version: 19.2.7 + rollup: + specifier: 4.61.1 + version: 4.61.1 + tslib: + specifier: 2.8.1 + version: 2.8.1 + tsx: + specifier: 4.22.4 + version: 4.22.4 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vitest: + specifier: 4.1.8 + version: 4.1.8(@types/node@25.9.2)(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) + zod: + specifier: 4.4.3 + version: 4.4.3 + +packages: + + '@babel/code-frame@7.29.0': + resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.28.5': + resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==} + engines: {node: '>=6.9.0'} + + '@biomejs/biome@2.4.16': + resolution: {integrity: sha512-x9ajFh1zChVybCiM3TN6OD4phAqLgtPZjFrZF+aTMYCPjwBO+k529TX7PPsAqtGNLeV4UgzwQnowEgS7bGmzcA==} + engines: {node: '>=14.21.3'} + hasBin: true + + '@biomejs/cli-darwin-arm64@2.4.16': + resolution: {integrity: sha512-wxPvu4XOA85YJk9ixSWUmq/QBHbid85BISbOAqqBM/5xQpPk9ayjk5375tOlSC0BeCwNSbPFafQBm+vBumXq0A==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [darwin] + + '@biomejs/cli-darwin-x64@2.4.16': + resolution: {integrity: sha512-xFCqGPwYusQJp4N4NJLi1XJiZqjwFdjhT+KqtNy+Ug3qgfczqnTa6MSDvxJF6TkuDLoYJItMapz6tAf7kCekFw==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [darwin] + + '@biomejs/cli-linux-arm64-musl@2.4.16': + resolution: {integrity: sha512-oYxnW0ARfJkr72ezzF2OR8N/rtkgLUQeYtF8cFhVswbknHxtTcmzSsanVJP8yQKnGpGpc2ck6c5zLvHahL6Cbg==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-arm64@2.4.16': + resolution: {integrity: sha512-2kFb4//jxfZaP6D+Rj5VkHkxgyD9EoRAVBEQb8PKRv+s4NO2zYNJKXFaJmK1CmhufJOWEfpHKaRbOja7qjmdhQ==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-linux-x64-musl@2.4.16': + resolution: {integrity: sha512-iHDS+MCM65DPqWGu+ECC3uoALyj2H7F4nVUPxIPjz/PIl94EUu+EDfGZDzFP+NY1EOPVt9NQvwFqq7HdMmowdg==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@biomejs/cli-linux-x64@2.4.16': + resolution: {integrity: sha512-NbcBbi/nJqn5baae6wqRXdS7Gadf2uRpehSh6vMSYpG8OhkXl/Xg8aorWrJ+9VWqAT5ml90alLvorkpMW0nBwQ==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@biomejs/cli-win32-arm64@2.4.16': + resolution: {integrity: sha512-0rgImMsNb5v/chhkIFe3wu7PEFClS6RBAYUijGL9UsYN3PanSaoK24HSSuSJb1pYbYYVjzAyZTl3gtjJ84BM8A==} + engines: {node: '>=14.21.3'} + cpu: [arm64] + os: [win32] + + '@biomejs/cli-win32-x64@2.4.16': + resolution: {integrity: sha512-Kp85jgoBHa05gix6UIRjfCDiUV3w/8VIdZ247VyyO2gEjaw12WEVhdIjlxp/AMzXxqxQwbxNTDVZ3Mwd2RG5rw==} + engines: {node: '>=14.21.3'} + cpu: [x64] + os: [win32] + + '@commander-js/extra-typings@14.0.0': + resolution: {integrity: sha512-hIn0ncNaJRLkZrxBIp5AsW/eXEHNKYQBh0aPdoUqNgD+Io3NIykQqpKFyKcuasZhicGaEZJX/JBSIkZ4e5x8Dg==} + peerDependencies: + commander: ~14.0.0 + + '@emnapi/core@1.10.0': + resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} + + '@emnapi/runtime@1.10.0': + resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + + '@emnapi/wasi-threads@1.2.1': + resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} + + '@esbuild/aix-ppc64@0.27.7': + resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.28.0': + resolution: {integrity: sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.27.7': + resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.28.0': + resolution: {integrity: sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.27.7': + resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.28.0': + resolution: {integrity: sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.27.7': + resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.28.0': + resolution: {integrity: sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.27.7': + resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.28.0': + resolution: {integrity: sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.7': + resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.0': + resolution: {integrity: sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.27.7': + resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.28.0': + resolution: {integrity: sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.7': + resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.0': + resolution: {integrity: sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.27.7': + resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.28.0': + resolution: {integrity: sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.27.7': + resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.28.0': + resolution: {integrity: sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.27.7': + resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.28.0': + resolution: {integrity: sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.27.7': + resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.28.0': + resolution: {integrity: sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.27.7': + resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.28.0': + resolution: {integrity: sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.27.7': + resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.28.0': + resolution: {integrity: sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.7': + resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.0': + resolution: {integrity: sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.27.7': + resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.28.0': + resolution: {integrity: sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.27.7': + resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.28.0': + resolution: {integrity: sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.27.7': + resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-arm64@0.28.0': + resolution: {integrity: sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.7': + resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.0': + resolution: {integrity: sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.27.7': + resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-arm64@0.28.0': + resolution: {integrity: sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.7': + resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.0': + resolution: {integrity: sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.27.7': + resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/openharmony-arm64@0.28.0': + resolution: {integrity: sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.27.7': + resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.28.0': + resolution: {integrity: sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.27.7': + resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.28.0': + resolution: {integrity: sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.27.7': + resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.28.0': + resolution: {integrity: sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.27.7': + resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.28.0': + resolution: {integrity: sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@fetch-mock/vitest@0.2.18': + resolution: {integrity: sha512-s2bG7/MSwVFun5gTzrkZzJSmcdSurTmxt5B+JA/4ALyx0Pfo1al0/MlZPBtZ358Kkjv9CpRlhpyLf6bt4OrtLQ==} + engines: {node: '>=18.11.0'} + peerDependencies: + vitest: '*' + + '@gerrit0/mini-shiki@3.23.0': + resolution: {integrity: sha512-bEMORlG0cqdjVyCEuU0cDQbORWX+kYCeo0kV1lbxF5bt4r7SID2l9bqsxJEM0zndaxpOUT7riCyIVEuqq/Ynxg==} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@knighted/duel@4.1.0': + resolution: {integrity: sha512-CwIa+6cOYRuV7eX5ytCud5MFM1UKeufDxWgYuu4inmarBGczD0UNKCs+KrtfkcRuVy3+iQkQzu6BxeCLktOiOg==} + engines: {node: '>=22.21.1 <23 || >=24 <25 || >=26 <27'} + hasBin: true + peerDependencies: + typescript: '>=5.5.0 <7' + typescript-next: npm:typescript@next + peerDependenciesMeta: + typescript-next: + optional: true + + '@knighted/module@1.6.0': + resolution: {integrity: sha512-TaAkdISZq9t2x1xBZycZgQK4dCnl7QNNYzR0heglE3B3UG5yWSj+iSaSIvgV/++uX+8WYTV5m/IVFwOZND+9yw==} + engines: {node: '>=22.21.1 <23 || >=24 <25 || >=26 <27'} + hasBin: true + + '@napi-rs/wasm-runtime@1.1.4': + resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==} + peerDependencies: + '@emnapi/core': ^1.7.1 + '@emnapi/runtime': ^1.7.1 + + '@orval/angular@8.15.0': + resolution: {integrity: sha512-aFArKav6FuZ7ZTm1GorkRLJKtHza3TSy04qcuNnb84qlJ83DHAhxoDVyBXQUmSYtwbc7ckzTveMofiA5v13wnw==} + + '@orval/axios@8.15.0': + resolution: {integrity: sha512-jdsEPvmxlmbQ9YVsLWmzxphN+x+xTYst6WmnnEfz/QMicOEzy1RzWp9YzmpHUT+EKs6pdYWrwagxph74R3qV9A==} + + '@orval/core@8.15.0': + resolution: {integrity: sha512-YcUZQWnCU/0Dzf1aISQ+XY7ghL248Ctfv++2Qyr4nUuZ2UWG3bdO1FAdDUGULYTDAgfb5B3iiJIYsxR0iDKk5A==} + peerDependencies: + '@faker-js/faker': '>=10' + peerDependenciesMeta: + '@faker-js/faker': + optional: true + + '@orval/effect@8.15.0': + resolution: {integrity: sha512-gF2P1tbe08KbBuEaLHtwliabs599qYvypzy8Aj6j+aRY4EiSCRNZYs1U7lQY52jZrvwqv2L0llQl4qkelkOMoA==} + + '@orval/fetch@8.15.0': + resolution: {integrity: sha512-EyTOblRIo6DtP80F1RzfgLIbsQRu0as8sbpU0Kd46Zj248SeWE/5if4cfrjFR1lzSL+9pDBaHlA2JA7BNu08Rg==} + + '@orval/hono@8.15.0': + resolution: {integrity: sha512-UhYn0Z+P/Fo3HmxIB5RcJnnhdTtSge7ewhenauJCooMF1yrQjlPyHsKIxmjolZjZIKae2igsZekz1tCVtKi26g==} + peerDependencies: + typescript: '>=5' + peerDependenciesMeta: + typescript: + optional: true + + '@orval/mcp@8.15.0': + resolution: {integrity: sha512-VwpBhIR/rD7o8XGs4bIOnXwAjpRrJTusBBUG50VOgAtPA88cM8WDPMND3Zt7Wr8iP8xZmzRBw105n9qhoQ5xUg==} + + '@orval/mock@8.15.0': + resolution: {integrity: sha512-PdIvn/y7u6ktoVEWLm9XrMdx4KPlsv0ww9Fl6H+ibL3yB1xX3JWe/e1YKlA1aDyGyBDTyDAdTWNJHoAtKnqEug==} + + '@orval/query@8.15.0': + resolution: {integrity: sha512-NmMiObzXCHFVj0fIDVT9xpBknmEXNl+N+1vpPnQc8H2XQ+XpbMMaf6MJKXriFV2QhiZ7myjLomofQEi1impwzg==} + + '@orval/solid-start@8.15.0': + resolution: {integrity: sha512-2lPvOp6WBJDEF51aZmuXZagUBmckrkyNFrlpJCAceCJaDhUT86H5f+6p1wdVgjsH672Hud7oHWoqlIf5XQyABg==} + + '@orval/swr@8.15.0': + resolution: {integrity: sha512-BEu6lQJzZdlVDLd2xppsrSj29EgHVD6owHhaldyIiz1HMezO895aNCsqoFbMK8rYgB4x+XemR40Wr+8ivNvP9A==} + + '@orval/zod@8.15.0': + resolution: {integrity: sha512-5970pTfgsqUtygNxoLVlL6dKAv31UogAkBCRfmgQPSzr4sMXKya2WhLl1ERSNYMr9A+iGBWVR5ZmYtPGhAaVDg==} + + '@oxc-parser/binding-android-arm-eabi@0.132.0': + resolution: {integrity: sha512-KrLaPWa5c9Y7LkW+rKkaUE3y7DBDrQtaf7rlsSDfv6KAHUjgzAIRA761Lrrp6//Yd/Rlie/yEOt9YENCoJnOcw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxc-parser/binding-android-arm64@0.132.0': + resolution: {integrity: sha512-SThDrSeamB/kG2+NxcJ5/wSLcV6dUqDknrPLqFYQ0ST/55mtBP4M7Q/f3QbubH6aAd11wpzZn/nwbVRSdobOpg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxc-parser/binding-darwin-arm64@0.132.0': + resolution: {integrity: sha512-Lc0f/TYoKBghE5/2Gsv7bLXk+TJZunx2Tf61X8hG4ARXdc8UYI26dCGccFSd1AyFbK3jfaNXtMnupggDbjPXdQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxc-parser/binding-darwin-x64@0.132.0': + resolution: {integrity: sha512-RG2eJIpf7C21z9HSSXFw1bTArdpKe7Y4fwcJTwRq1yCSe1vSavaN9GA1sm9KqzemTLAGVktQ+7qBTGp0vQeUZg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxc-parser/binding-freebsd-x64@0.132.0': + resolution: {integrity: sha512-wQIPntPLtJ8NcBpvKPbEv3NqzV6k8eP8tP/jE9Rg8HTg/j7urZGFSsTCPCW5k77Qfw2DM4vRvc9p3I4yq/Shvw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxc-parser/binding-linux-arm-gnueabihf@0.132.0': + resolution: {integrity: sha512-PixKEpeSe3yxQWqNyOCBALRYc72+Tj7ILDofUl3iXo25cVOzLA6jHUhmOINRtWIPh7dbUie3QNeabwaQpZTw6w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-parser/binding-linux-arm-musleabihf@0.132.0': + resolution: {integrity: sha512-sCR+DzGHlyHKnbA2z9zWjTUhIo8Sy0enJl4RDsBwPmkxYynPatpwOAWe8W5127SlW0boqUWHGtr1NWn5UwIhXQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-parser/binding-linux-arm64-gnu@0.132.0': + resolution: {integrity: sha512-sQBix5P2cW+IpzTcCwYxnh9yALrKSIkKJThspBvMGcygSMnbzkSvhN7SfuX1hvBk8y1XEChsdkU3ET0V5DmzUw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-arm64-musl@0.132.0': + resolution: {integrity: sha512-WozHg3Kc//8Sk756HXXgMbEAvqtG+Lzb9JOojwQzIGDtN78Az2dLttkb71akWYUF/8IgYfDSlfKh4Uot8is5Vw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-linux-ppc64-gnu@0.132.0': + resolution: {integrity: sha512-CmX/ulNBOEwWTyVRmcpYKAcAizW6+OjtLJgo7fXoL9OqQvjF4VER8tPomv44vwzfSCy1BHbsB0ZlZYzYJNj4cA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-riscv64-gnu@0.132.0': + resolution: {integrity: sha512-j9oQS+hM90SdhviNGWbPgT4+Rlq+ac++q/zjgwPD1mVHgxHzATvoRGtDx0sXGmFOQ9J9YkwAhYGb5MAHL6TAsA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-riscv64-musl@0.132.0': + resolution: {integrity: sha512-bLz+Xi+Agnfmd7kWPEsSVwCn2k4EyIalZkNBcQ0OGIv9rqn8VgCPLNd03tM9mKX/5TdlvDXalz0q71BIrOPNqg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-linux-s390x-gnu@0.132.0': + resolution: {integrity: sha512-U6t2qbJU0ypTfyj9QV3W1Y6mITDTL8ai/OR6NUn85vyHthOvobKWgXzU4tu0EskSzlpuVFz1g0jFGulDIUKHxQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-x64-gnu@0.132.0': + resolution: {integrity: sha512-WcEaSNHFk8yz5YFlQQAlhq6jOFmZBB/RKE7uzhyCIf+pF1Lmv9gUH4221mle2Gd9iHyWT3ySNph8yZgb1xYdWg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-x64-musl@0.132.0': + resolution: {integrity: sha512-iQrV4iJzQgRwK3BWRmQl1C3C6g3wYpXN2WLdQdyR+efoUnncdShZAVp9OgcojtlD3MDRbuOMGG3SjxF4fL4nlQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-openharmony-arm64@0.132.0': + resolution: {integrity: sha512-FWzmUGrZ6GUby4U7WIwcCtab6tdmlTO3xTRRKyb5kjIJVEiaUAT8animUG/nK8ZCA8gkRkPOTId4rl6uTqUmJQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxc-parser/binding-wasm32-wasi@0.132.0': + resolution: {integrity: sha512-TlbMppxJI5CjWDes0QaP6G3aneVg1yikBu5QYI+DUShF9WDL66ccgKFNNGmi/Wybtszw6hxwAvv76T4DaPKnHw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [wasm32] + + '@oxc-parser/binding-win32-arm64-msvc@0.132.0': + resolution: {integrity: sha512-RH/NbFjGKqdUAUi7Oh3LQPxUk2hsWFEEQ38HSnbRQT8QjBZFKqL1fMbmsB3N4jy/KPh9iX94+9dmkEMBBbambw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxc-parser/binding-win32-ia32-msvc@0.132.0': + resolution: {integrity: sha512-JUr4jQY9jxoIB/YTLXr6XofSi5xikj6p5/Ns1h0VOBDT0j1jKU+kMsv2xxv51RwnETcXpA1Yw/9oUAfcqfaqEA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxc-parser/binding-win32-x64-msvc@0.132.0': + resolution: {integrity: sha512-2dapgHpA5X8DSXF4AU36hJWYf6zP0tKjMXFRAZFBD62pkevW/uhFDXoFH9Y/3Fd2EtDrw5ByNnR1wVE9X9y0SQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@oxc-project/types@0.132.0': + resolution: {integrity: sha512-FESMOxil5Se014ui/Eq8fT5uHJo6nIRwH0PfJrZJXs6Gek3ZVFOrpUv3YIZT20m+extU98Hg1Ym72U58rlsxUQ==} + + '@redocly/ajv@8.11.2': + resolution: {integrity: sha512-io1JpnwtIcvojV7QKDUSIuMN/ikdOUd1ReEnUnMKGfDVridQZ31J0MmIuqwuRjWDZfmvr+Q0MqCcfHM2gTivOg==} + + '@redocly/config@0.22.0': + resolution: {integrity: sha512-gAy93Ddo01Z3bHuVdPWfCwzgfaYgMdaZPcfL7JZ7hWJoK9V0lXDbigTWkhiPFAaLWzbOJ+kbUQG1+XwIm0KRGQ==} + + '@redocly/openapi-core@1.34.11': + resolution: {integrity: sha512-V09ayfnb5GyysmvARbt+voFZAjGcf7hSYxOYxSkCc4fbH/DTfq5YWoec8cflvmHHqyIFbqvmGKmYFzqhr9zxDg==} + engines: {node: '>=18.17.0', npm: '>=9.5.0'} + + '@rollup/rollup-android-arm-eabi@4.61.1': + resolution: {integrity: sha512-JnBB8MdXj45cajvTuO5FmPlvFVJRQgvrz1uSEl3NwqFnReAPGwb8EanbGi4z2nRaqLzjJSv5/JmycoTKlRZxHA==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.61.1': + resolution: {integrity: sha512-Jx2g7iSjw4AOT0HDPHM9RV3GNjRXwybWtSFZiZAYUTjUwjVrYIwq3kBf+LnhqJlzXFAqTAh2F7IGI+O568exPw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.61.1': + resolution: {integrity: sha512-0F1L/Z3Eqv8mT2n3dCpeO8GcTvHvVqkP5/t6DMsn0KzhYVcg+s7Ncl5DS8qjKYEeio6Az0Gt6nyBORay5qIlCA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.61.1': + resolution: {integrity: sha512-qLttcH871ujY4YcVfUSShhOw+CsoTatYz8gRbHO7Bb92QH059/P0y5do1KMs41fY0BpD2x4AJH/gID0zFiqVKQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.61.1': + resolution: {integrity: sha512-fUI4RapGE0Oh3mb8mgfvC1O2nU1RpDZUKnDQm3xB1Ipg7C2wTs5Kstz7G2uWK99a8S2yTMq8/P4uycwNa0nJyw==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.61.1': + resolution: {integrity: sha512-H5YrdvJaDtI/U9/emrD4b++xkvp3y/JvOe4rizHbxvkyMfRS/CiRYdji+Pl8D0brEaNFWUh1drQxgAGIl6Xudw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.61.1': + resolution: {integrity: sha512-Q8CBCCQtDFrYtXoeUXSrnFXKOnyUhx6bz+SkL6A0E7V8kAiCJ5pamq1WtbfpVGhR5TSpXY6ak3avmDc5fHTyJA==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.61.1': + resolution: {integrity: sha512-nwnhk1581l0FBVellGcVCAT0Oi06onEA3WB53sf01VO3I0UPBkMH9sXONYME2K0ovXcNayJfNtHfm6mpJElatQ==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.61.1': + resolution: {integrity: sha512-x5Xr49hwt3hdW75UOZm3395YwwzPyauktslv29KpWL/T+vVAzoT3azLcTWv0eMciBNrx+DYjH4paehHoLpPvpg==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.61.1': + resolution: {integrity: sha512-unMS3H73DpaoPyyEVPjGKleM/s0mkmsauTENpw4INQY8y4+IuLNjkueQ5QCtC0D3N38Y38yhAU8OoZ20S2Tm6w==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.61.1': + resolution: {integrity: sha512-zNZzGRnAhwjFEYmvphJRV5XaQGjs62cCmeYYHUT//NbvEnHauw+I85nGG+SiVg5ld4GX8D1IbKIX+ozITQnhMQ==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.61.1': + resolution: {integrity: sha512-LdpWGL8X209B2SIvWjqlc8VZgM6PKfontSerGepuldQmHYrAOtnMCXeJkxXGbC+PPZVOuu5czJo7fNV6aeW8rQ==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.61.1': + resolution: {integrity: sha512-EC5kTtNaNGOmbMGqar8dvJy6y/hg99GAwjfBz++pxZhQATXGcRjd6c5en5wcbru0vkRmiMGsQKdMJOOf6sza4g==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.61.1': + resolution: {integrity: sha512-8hiwp6D4acEcNK78I4rP0/XtS1sknWIAMJBPdR4l6zUtyTm5KiTDr5bXmWt4foY7nAN7AThDHgkLIEZOWKbzWw==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.61.1': + resolution: {integrity: sha512-10dh/h/BqA7DuMPWSxkR8uks18FRwnwOEqr5zOTEl+NOwP/OMzKX8OFR/Of9xxDA7D5qef1Nzar5WDD2kCCr1g==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.61.1': + resolution: {integrity: sha512-YKJ5lg35DP17gcAOggnihe+APw9HLyj1Xn7gsmGumBJAUDa6NGXNixJzmkWLhcK9TOuuyQjdamzvJefkO7qHZQ==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.61.1': + resolution: {integrity: sha512-Mlil5G2Jj6a7B3LWGctg+XPL9vdXYuzCtNXfxOQ0nPjc2m6ueUktocPGH9bnAM0bNRKb/bAWTujUU7IJQdQA+g==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.61.1': + resolution: {integrity: sha512-bVWIOIk6pV01p4CdUbPP7CJ/434z+OooYjDuFcR+44N35YvKUC66G8MGnvcWx5mWKW3g61J+t74l3Kj15Kwn2Q==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.61.1': + resolution: {integrity: sha512-qy5pBvZbqNFheBz61R1rzsezjm0J7O2oNGoWtGoY89SZYLUfxAJTBAqDChqAIdB4rCiIbi9nF7yZ83GnNiLwSw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.61.1': + resolution: {integrity: sha512-E83TXjI4zm0+5f2qO+UOudaCYIhYwpJ5jq6YCZNIZ+6CbfhKrkAGezeiASBL9ElxAxFsRS9ZhESv8mfnj6TKeg==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.61.1': + resolution: {integrity: sha512-fbWnKqVkjrJN38vNe3ahkbk6iejS/3b0Nt7EEtPpE6RBacZcGXNKbzfHN3GUUlXOPghUg0j6XUGrtjX9z1sIvA==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.61.1': + resolution: {integrity: sha512-ArMl38iVAbk0New1ogihQNY6iphLi4ZaRsa037gUzv5yeKPY8TD3Dmy4x2RNC1VztU/uqm+G+/RwFrSka3Oy2g==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.61.1': + resolution: {integrity: sha512-0mYtjHS9ucAbcATycCNK9IGBk/cCe/ma7EmSLGZdsxnOA8cjRIyU04wDpVAD9NiOfLUR9KTxdiO53uOkherqjQ==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.61.1': + resolution: {integrity: sha512-gK1iCEPfpoSG9wfBihXxvBMi8ZfcWffYkEsC/Eih+iFENTaewvNcrEQ69lIOWYO5pePHKLHHO7nq5AILGO/HQQ==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.61.1': + resolution: {integrity: sha512-X+zaP2x+j4RXGfbp/seSoRHWnPxzApilDszisZxbYH5C/jTxFhCtDNdPGZb9lJyYPs24wGxruPF7Y+sIXt9Gzw==} + cpu: [x64] + os: [win32] + + '@scalar/helpers@0.8.1': + resolution: {integrity: sha512-yuiuBCadP5bjAnIv23QvifVN/NaMi9xBF6b8Wdk4QOzwzLPJmp699MAdf33J0A5i2qKcvnu32iz/VkEJmQRe5g==} + engines: {node: '>=22'} + + '@scalar/json-magic@0.12.15': + resolution: {integrity: sha512-ZYgdYZ0jSZXQeyhG2lJ20FjzvKsaDRXk4bPguF/Ytl2nGBh9a6RIIr9NvVy4zAD67a/ahm+xipXlfoR1KtB5fg==} + engines: {node: '>=22'} + + '@scalar/openapi-parser@0.28.6': + resolution: {integrity: sha512-gCl4r+rpmO+CKfwmmwI+GJVFhuNut7e6beUcD/xazanH4epkLT7V9ZgMv9YKbUBE73fkrOv6NJympeEGiU8aUw==} + engines: {node: '>=22'} + + '@scalar/openapi-types@0.8.0': + resolution: {integrity: sha512-WmaxVSfvY5K/TwcG2B2TU1WOe1As1uc2s7myswtP6dBlcjU3hM08SApxv/jmyGaCE8t4gO5BBhmHY4pDUfmr2g==} + engines: {node: '>=22'} + + '@scalar/openapi-types@0.9.1': + resolution: {integrity: sha512-gkGhSkxSzADaBiNg+ZAbJuwj+ZUmzP2Pg9CWZ7ZP+0fck2WjPeDDM7aAbouAm0aQQMF9xBjSPXSA9a/qTHYaTw==} + engines: {node: '>=22'} + + '@scalar/openapi-upgrader@0.2.9': + resolution: {integrity: sha512-D5b0rGLLZgmkO9mdW2j/ND1KBlH1u3RCpr87HPxv9P9ZSr6PtM5iLqFOJq0ACiaHjY2mikCrxgDmnUEhTzRpHQ==} + engines: {node: '>=22'} + + '@sec-ant/readable-stream@0.4.1': + resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==} + + '@shikijs/engine-oniguruma@3.23.0': + resolution: {integrity: sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==} + + '@shikijs/langs@3.23.0': + resolution: {integrity: sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg==} + + '@shikijs/themes@3.23.0': + resolution: {integrity: sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA==} + + '@shikijs/types@3.23.0': + resolution: {integrity: sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==} + + '@shikijs/vscode-textmate@10.0.2': + resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} + + '@sindresorhus/merge-streams@4.0.0': + resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==} + engines: {node: '>=18'} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@tybys/wasm-util@0.10.2': + resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/glob-to-regexp@0.4.4': + resolution: {integrity: sha512-nDKoaKJYbnn1MZxUY0cA1bPmmgZbg0cTq7Rh13d0KWYNOiKbqoR+2d89SnRPszGh7ROzSwZ/GOjZ4jPbmmZ6Eg==} + + '@types/hast@3.0.4': + resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==} + + '@types/node-fetch@2.6.13': + resolution: {integrity: sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==} + + '@types/node@25.9.2': + resolution: {integrity: sha512-G05zqtJhcDLb8uslf5EjCxXg9G1KQxiV8OS0R26IC//Eoyitzqe8z37I7cqvnZlrlSfgocQRfSn/AHBZJJFyGw==} + + '@types/normalize-package-data@2.4.4': + resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==} + + '@types/react@19.2.17': + resolution: {integrity: sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==} + + '@types/unist@3.0.3': + resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} + + '@vitest/expect@4.1.8': + resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==} + + '@vitest/mocker@4.1.8': + resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==} + peerDependencies: + msw: ^2.4.9 + vite: '>=7.3.2' + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.8': + resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==} + + '@vitest/runner@4.1.8': + resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==} + + '@vitest/snapshot@4.1.8': + resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==} + + '@vitest/spy@4.1.8': + resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==} + + '@vitest/utils@4.1.8': + resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==} + + acorn@8.16.0: + resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} + engines: {node: '>=0.4.0'} + hasBin: true + + agent-base@7.1.4: + resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} + engines: {node: '>= 14'} + + ajv-draft-04@1.0.0: + resolution: {integrity: sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==} + peerDependencies: + ajv: ^8.5.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv-formats@3.0.1: + resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} + + ansi-colors@4.1.3: + resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==} + engines: {node: '>=6'} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + brace-expansion@2.0.3: + resolution: {integrity: sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==} + + brace-expansion@5.0.6: + resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} + engines: {node: 18 || 20 || >=22} + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + + change-case@5.4.4: + resolution: {integrity: sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==} + + chokidar@5.0.0: + resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} + engines: {node: '>= 20.19.0'} + + colorette@1.4.0: + resolution: {integrity: sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==} + + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + + commander@14.0.3: + resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} + engines: {node: '>=20'} + + compare-versions@6.1.1: + resolution: {integrity: sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + enquirer@2.4.1: + resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==} + engines: {node: '>=8.6'} + + entities@4.5.0: + resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} + engines: {node: '>=0.12'} + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@2.1.0: + resolution: {integrity: sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==} + + es-object-atoms@1.1.1: + resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + esbuild@0.27.7: + resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} + engines: {node: '>=18'} + hasBin: true + + esbuild@0.28.0: + resolution: {integrity: sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + execa@9.6.1: + resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==} + engines: {node: ^18.19.0 || >=20.5.0} + + expect-type@1.3.0: + resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + engines: {node: '>=12.0.0'} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-uri@3.1.2: + resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fetch-mock@12.6.0: + resolution: {integrity: sha512-oAy0OqAvjAvduqCeWveBix7LLuDbARPqZZ8ERYtBcCURA3gy7EALA3XWq0tCNxsSg+RmmJqyaeeZlOCV9abv6w==} + engines: {node: '>=18.11.0'} + + figures@6.1.0: + resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==} + engines: {node: '>=18'} + + find-up-simple@1.0.1: + resolution: {integrity: sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ==} + engines: {node: '>=18'} + + find-up@8.0.0: + resolution: {integrity: sha512-JGG8pvDi2C+JxidYdIwQDyS/CgcrIdh18cvgxcBge3wSHRQOrooMD3GlFBcmMJAN9M42SAZjDp5zv1dglJjwww==} + engines: {node: '>=20'} + + form-data@4.0.4: + resolution: {integrity: sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==} + engines: {node: '>= 6'} + + fs-extra@11.3.5: + resolution: {integrity: sha512-eKpRKAovdpZtR1WopLHxlBWvAgPny3c4gX1G5Jhwmmw4XJj0ifSD5qB5TOo8hmA0wlRKDAOAhEE1yVPgs6Fgcg==} + engines: {node: '>=14.14'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + get-stream@9.0.1: + resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==} + engines: {node: '>=18'} + + get-tsconfig@4.14.0: + resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} + + glob-to-regexp@0.4.1: + resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + hasown@2.0.2: + resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} + engines: {node: '>= 0.4'} + + hosted-git-info@9.0.3: + resolution: {integrity: sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==} + engines: {node: ^20.17.0 || >=22.9.0} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + + human-signals@8.0.1: + resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==} + engines: {node: '>=18.18.0'} + + index-to-position@1.2.0: + resolution: {integrity: sha512-Yg7+ztRkqslMAS2iFaU+Oa4KTSidr63OsFGlOrJoW981kIYO3CGCS3wA95P1mUi/IVSJkn0D479KTJpVpvFNuw==} + engines: {node: '>=18'} + + is-plain-obj@4.1.0: + resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} + engines: {node: '>=12'} + + is-reference@3.0.3: + resolution: {integrity: sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==} + + is-stream@4.0.1: + resolution: {integrity: sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==} + engines: {node: '>=18'} + + is-unicode-supported@2.1.0: + resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} + engines: {node: '>=18'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jiti@2.7.0: + resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} + hasBin: true + + js-levenshtein@1.1.6: + resolution: {integrity: sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==} + engines: {node: '>=0.10.0'} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + + jsonfile@6.2.1: + resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} + + jsonpointer@5.0.1: + resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} + engines: {node: '>=0.10.0'} + + leven@4.1.0: + resolution: {integrity: sha512-KZ9W9nWDT7rF7Dazg8xyLHGLrmpgq2nVNFUckhqdW3szVP6YhCpp/RAnpmVExA9JvrMynjwSLVrEj3AepHR6ew==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + linkify-it@5.0.1: + resolution: {integrity: sha512-wVoTjP4Q6R0NW5hiZkVJaFZPWgtXfoGF+6LucL3/FtiNjmcHhYjEr5f1Kqjirc1nBW07J/ZuRFumqr2oqccEWg==} + + locate-path@8.0.0: + resolution: {integrity: sha512-XT9ewWAC43tiAV7xDAPflMkG0qOPn2QjHqlgX8FOqmWa/rxnyYDulF9T0F7tRy1u+TVTmK/M//6VIOye+2zDXg==} + engines: {node: '>=20'} + + lru-cache@11.5.1: + resolution: {integrity: sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==} + engines: {node: 20 || >=22} + + lunr@2.3.9: + resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + markdown-it@14.2.0: + resolution: {integrity: sha512-1TGiQiJVRQ3NPmZH6sx5Cfnmg6GQm9jvC1ch4TK511NjSJvjzKLzn5pPfZRNZkRPZP0HqCioSndqH8v2nRaWVQ==} + hasBin: true + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + mdurl@2.0.0: + resolution: {integrity: sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + + minimatch@5.1.9: + resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==} + engines: {node: '>=10'} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.12: + resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + normalize-package-data@8.0.0: + resolution: {integrity: sha512-RWk+PI433eESQ7ounYxIp67CYuVsS1uYSonX3kA6ps/3LWfjVQa/ptEg6Y3T6uAMq1mWpX9PQ+qx+QaHpsc7gQ==} + engines: {node: ^20.17.0 || >=22.9.0} + + npm-run-path@6.0.0: + resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} + engines: {node: '>=18'} + + obug@2.1.2: + resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==} + engines: {node: '>=12.20.0'} + + openapi-fetch@0.17.0: + resolution: {integrity: sha512-PsbZR1wAPcG91eEthKhN+Zn92FMHxv+/faECIwjXdxfTODGSGegYv0sc1Olz+HYPvKOuoXfp+0pA2XVt2cI0Ig==} + + openapi-typescript-helpers@0.1.0: + resolution: {integrity: sha512-OKTGPthhivLw/fHz6c3OPtg72vi86qaMlqbJuVJ23qOvQ+53uw1n7HdmkJFibloF7QEjDrDkzJiOJuockM/ljw==} + + openapi-typescript@7.13.0: + resolution: {integrity: sha512-EFP392gcqXS7ntPvbhBzbF8TyBA+baIYEm791Hy5YkjDYKTnk/Tn5OQeKm5BIZvJihpp8Zzr4hzx0Irde1LNGQ==} + hasBin: true + peerDependencies: + typescript: ^5.x + + orval@8.15.0: + resolution: {integrity: sha512-o4Sl2VLCP0Yu5wv5ubN477Fze8QDXSY0vwjB0U9z4Ew1YJrIAX/6D5hG2PsD8KIoZtLCgrDFj5t/otqmNJtBdw==} + engines: {node: '>=22.18.0'} + hasBin: true + peerDependencies: + prettier: '>=3.0.0' + peerDependenciesMeta: + prettier: + optional: true + + oxc-parser@0.132.0: + resolution: {integrity: sha512-+0LAPHaqtfQlvWdpaAa09SmOaZZgP8C552xosEkGJ4+ruEwP1Vgx+sqBgcBCNfR6KDCmagGOZTde8wmAvcI/Hg==} + engines: {node: ^20.19.0 || >=22.12.0} + + p-limit@4.0.0: + resolution: {integrity: sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + p-locate@6.0.0: + resolution: {integrity: sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + parse-json@8.3.0: + resolution: {integrity: sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ==} + engines: {node: '>=18'} + + parse-ms@4.0.0: + resolution: {integrity: sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==} + engines: {node: '>=18'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-key@4.0.0: + resolution: {integrity: sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==} + engines: {node: '>=12'} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + periscopic@4.0.3: + resolution: {integrity: sha512-iD/CnjEI6TJYwqLXmEVByEbT1RwUGSW3W51t/uWf+2Ag7FMHLqJ1XNhawGaXBf9/gZr+DhF3bTGLOw+03GJnzg==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.4: + resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} + engines: {node: '>=12'} + + pluralize@8.0.0: + resolution: {integrity: sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==} + engines: {node: '>=4'} + + postcss@8.5.15: + resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} + engines: {node: ^10 || ^12 || >=14} + + prettier@3.8.3: + resolution: {integrity: sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw==} + engines: {node: '>=14'} + hasBin: true + + pretty-ms@9.3.0: + resolution: {integrity: sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==} + engines: {node: '>=18'} + + punycode.js@2.3.1: + resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} + engines: {node: '>=6'} + + react@19.2.7: + resolution: {integrity: sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==} + engines: {node: '>=0.10.0'} + + read-package-up@12.0.0: + resolution: {integrity: sha512-Q5hMVBYur/eQNWDdbF4/Wqqr9Bjvtrw2kjGxxBbKLbx8bVCL8gcArjTy8zDUuLGQicftpMuU0riQNcAsbtOVsw==} + engines: {node: '>=20'} + + read-pkg@10.1.0: + resolution: {integrity: sha512-I8g2lArQiP78ll51UeMZojewtYgIRCKCWqZEgOO8c/uefTI+XDXvCSXu3+YNUaTNvZzobrL5+SqHjBrByRRTdg==} + engines: {node: '>=20'} + + readdirp@5.0.0: + resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==} + engines: {node: '>= 20.19.0'} + + regexparam@3.0.0: + resolution: {integrity: sha512-RSYAtP31mvYLkAHrOlh25pCNQ5hWnT106VukGaaFfuJrZFkGRX5GhUAdPqpSDXxOhA2c4akmRuplv1mRqnBn6Q==} + engines: {node: '>=8'} + + remeda@2.38.0: + resolution: {integrity: sha512-yhZjp7dd+L0NWS8gn4caKOHI6ALfbN3/2H5WNBCnFyzPYcG5vOw5b30FVpDFdQ+7Ui62QiCWKubJhG9Y5SqF5A==} + engines: {node: '>=18.0.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + rollup@4.61.1: + resolution: {integrity: sha512-I4KW6iuRpuu2uHBLraZ1wNZe0DP7lnRha+VJ9tNaYVaVgKhW0aI3h4RYnoRPeql0flHm/Co55b7snEDcOfOJrA==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + semver@7.8.2: + resolution: {integrity: sha512-c8jsqUZm3omBOI66G90z1Dyw5z622G8oLG+omfsHBJf3CWQTlOcwOjvOG6wtiNfW6anKm/eA39LMwMtMez2TiQ==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + spdx-correct@3.2.0: + resolution: {integrity: sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==} + + spdx-exceptions@2.5.0: + resolution: {integrity: sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==} + + spdx-expression-parse@3.0.1: + resolution: {integrity: sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==} + + spdx-license-ids@3.0.23: + resolution: {integrity: sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.1.0: + resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} + + string-argv@0.3.2: + resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==} + engines: {node: '>=0.6.19'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-final-newline@4.0.0: + resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==} + engines: {node: '>=18'} + + supports-color@10.2.2: + resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} + engines: {node: '>=18'} + + tagged-tag@1.0.0: + resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==} + engines: {node: '>=20'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.2.4: + resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.1.0: + resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} + engines: {node: '>=14.0.0'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + tsx@4.22.4: + resolution: {integrity: sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==} + engines: {node: '>=18.0.0'} + hasBin: true + + type-fest@4.41.0: + resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==} + engines: {node: '>=16'} + + type-fest@5.7.0: + resolution: {integrity: sha512-1URUxUqfHFM1c+zfSPsa3gnkO7Aq21qyH75SIduNYz4SzY964rn1X2vCMQaHSHhktiw+0kPa2iyb6PUpXqB6Vg==} + engines: {node: '>=20'} + + typedoc-plugin-coverage@4.0.3: + resolution: {integrity: sha512-baim3wyMkqpX7rBzL/6iZ7wzKJuSr9ffP16RHOsdTUNoHUZeXLIZHSUBtUhXmNHaUNRgfqdmKLBwyggbJjGdeQ==} + engines: {node: '>= 18'} + peerDependencies: + typedoc: 0.28.x + + typedoc-plugin-markdown@4.12.0: + resolution: {integrity: sha512-eJDEMAfxCmede22c/Jw7d0FA13ggAQv+KkwQYKYCdqI02cin6Rc9QRwbG/7XvvHWinuFejySnZVUWDtvGk3Vbg==} + engines: {node: '>= 18'} + peerDependencies: + typedoc: 0.28.x + + typedoc@0.28.19: + resolution: {integrity: sha512-wKh+lhdmMFivMlc6vRRcMGXeGEHGU2g8a2CkPTJjJlwRf1iXbimWIPcFolCqe4E0d/FRtGszpIrsp3WLpDB8Pw==} + engines: {node: '>= 18', pnpm: '>= 10'} + hasBin: true + peerDependencies: + typescript: 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + uc.micro@2.1.0: + resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==} + + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + + unicorn-magic@0.3.0: + resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==} + engines: {node: '>=18'} + + unicorn-magic@0.4.0: + resolution: {integrity: sha512-wH590V9VNgYH9g3lH9wWjTrUoKsjLF6sGLjhR4sH1LWpLmCOH0Zf7PukhDA8BiS7KHe4oPNkcTHqYkj7SOGUOw==} + engines: {node: '>=20'} + + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + uri-js-replace@1.0.1: + resolution: {integrity: sha512-W+C9NWNLFOoBI2QWDp4UT9pv65r2w5Cx+3sTYFvtMdDBxkKt1syCqsUdSFAChbEe1uK5TfS04wt/nGwmaeIQ0g==} + + validate-npm-package-license@3.0.4: + resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==} + + vite@7.3.1: + resolution: {integrity: sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + jiti: '>=1.21.0' + less: ^4.0.0 + lightningcss: ^1.21.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.8: + resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.8 + '@vitest/browser-preview': 4.1.8 + '@vitest/browser-webdriverio': 4.1.8 + '@vitest/coverage-istanbul': 4.1.8 + '@vitest/coverage-v8': 4.1.8 + '@vitest/ui': 4.1.8 + happy-dom: '*' + jsdom: '*' + vite: '>=7.3.2' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + yaml-ast-parser@0.0.43: + resolution: {integrity: sha512-2PTINUwsRqSd+s8XxKaJWQlUuEMHJQyEuh2edBbW8KNJz0SJPwUSD2zRWqezFEdN7IzAgeuYHFUCF7o8zRdZ0A==} + + yaml@2.9.0: + resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} + engines: {node: '>= 14.6'} + hasBin: true + + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yocto-queue@1.2.2: + resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} + engines: {node: '>=12.20'} + + yoctocolors@2.1.2: + resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==} + engines: {node: '>=18'} + + zimmerframe@1.1.4: + resolution: {integrity: sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==} + + zod@4.4.3: + resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} + +snapshots: + + '@babel/code-frame@7.29.0': + dependencies: + '@babel/helper-validator-identifier': 7.28.5 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/helper-validator-identifier@7.28.5': {} + + '@biomejs/biome@2.4.16': + optionalDependencies: + '@biomejs/cli-darwin-arm64': 2.4.16 + '@biomejs/cli-darwin-x64': 2.4.16 + '@biomejs/cli-linux-arm64': 2.4.16 + '@biomejs/cli-linux-arm64-musl': 2.4.16 + '@biomejs/cli-linux-x64': 2.4.16 + '@biomejs/cli-linux-x64-musl': 2.4.16 + '@biomejs/cli-win32-arm64': 2.4.16 + '@biomejs/cli-win32-x64': 2.4.16 + + '@biomejs/cli-darwin-arm64@2.4.16': + optional: true + + '@biomejs/cli-darwin-x64@2.4.16': + optional: true + + '@biomejs/cli-linux-arm64-musl@2.4.16': + optional: true + + '@biomejs/cli-linux-arm64@2.4.16': + optional: true + + '@biomejs/cli-linux-x64-musl@2.4.16': + optional: true + + '@biomejs/cli-linux-x64@2.4.16': + optional: true + + '@biomejs/cli-win32-arm64@2.4.16': + optional: true + + '@biomejs/cli-win32-x64@2.4.16': + optional: true + + '@commander-js/extra-typings@14.0.0(commander@14.0.3)': + dependencies: + commander: 14.0.3 + + '@emnapi/core@1.10.0': + dependencies: + '@emnapi/wasi-threads': 1.2.1 + tslib: 2.8.1 + optional: true + + '@emnapi/runtime@1.10.0': + dependencies: + tslib: 2.8.1 + optional: true + + '@emnapi/wasi-threads@1.2.1': + dependencies: + tslib: 2.8.1 + optional: true + + '@esbuild/aix-ppc64@0.27.7': + optional: true + + '@esbuild/aix-ppc64@0.28.0': + optional: true + + '@esbuild/android-arm64@0.27.7': + optional: true + + '@esbuild/android-arm64@0.28.0': + optional: true + + '@esbuild/android-arm@0.27.7': + optional: true + + '@esbuild/android-arm@0.28.0': + optional: true + + '@esbuild/android-x64@0.27.7': + optional: true + + '@esbuild/android-x64@0.28.0': + optional: true + + '@esbuild/darwin-arm64@0.27.7': + optional: true + + '@esbuild/darwin-arm64@0.28.0': + optional: true + + '@esbuild/darwin-x64@0.27.7': + optional: true + + '@esbuild/darwin-x64@0.28.0': + optional: true + + '@esbuild/freebsd-arm64@0.27.7': + optional: true + + '@esbuild/freebsd-arm64@0.28.0': + optional: true + + '@esbuild/freebsd-x64@0.27.7': + optional: true + + '@esbuild/freebsd-x64@0.28.0': + optional: true + + '@esbuild/linux-arm64@0.27.7': + optional: true + + '@esbuild/linux-arm64@0.28.0': + optional: true + + '@esbuild/linux-arm@0.27.7': + optional: true + + '@esbuild/linux-arm@0.28.0': + optional: true + + '@esbuild/linux-ia32@0.27.7': + optional: true + + '@esbuild/linux-ia32@0.28.0': + optional: true + + '@esbuild/linux-loong64@0.27.7': + optional: true + + '@esbuild/linux-loong64@0.28.0': + optional: true + + '@esbuild/linux-mips64el@0.27.7': + optional: true + + '@esbuild/linux-mips64el@0.28.0': + optional: true + + '@esbuild/linux-ppc64@0.27.7': + optional: true + + '@esbuild/linux-ppc64@0.28.0': + optional: true + + '@esbuild/linux-riscv64@0.27.7': + optional: true + + '@esbuild/linux-riscv64@0.28.0': + optional: true + + '@esbuild/linux-s390x@0.27.7': + optional: true + + '@esbuild/linux-s390x@0.28.0': + optional: true + + '@esbuild/linux-x64@0.27.7': + optional: true + + '@esbuild/linux-x64@0.28.0': + optional: true + + '@esbuild/netbsd-arm64@0.27.7': + optional: true + + '@esbuild/netbsd-arm64@0.28.0': + optional: true + + '@esbuild/netbsd-x64@0.27.7': + optional: true + + '@esbuild/netbsd-x64@0.28.0': + optional: true + + '@esbuild/openbsd-arm64@0.27.7': + optional: true + + '@esbuild/openbsd-arm64@0.28.0': + optional: true + + '@esbuild/openbsd-x64@0.27.7': + optional: true + + '@esbuild/openbsd-x64@0.28.0': + optional: true + + '@esbuild/openharmony-arm64@0.27.7': + optional: true + + '@esbuild/openharmony-arm64@0.28.0': + optional: true + + '@esbuild/sunos-x64@0.27.7': + optional: true + + '@esbuild/sunos-x64@0.28.0': + optional: true + + '@esbuild/win32-arm64@0.27.7': + optional: true + + '@esbuild/win32-arm64@0.28.0': + optional: true + + '@esbuild/win32-ia32@0.27.7': + optional: true + + '@esbuild/win32-ia32@0.28.0': + optional: true + + '@esbuild/win32-x64@0.27.7': + optional: true + + '@esbuild/win32-x64@0.28.0': + optional: true + + '@fetch-mock/vitest@0.2.18(vitest@4.1.8(@types/node@25.9.2)(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)))': + dependencies: + fetch-mock: 12.6.0 + vitest: 4.1.8(@types/node@25.9.2)(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) + + '@gerrit0/mini-shiki@3.23.0': + dependencies: + '@shikijs/engine-oniguruma': 3.23.0 + '@shikijs/langs': 3.23.0 + '@shikijs/themes': 3.23.0 + '@shikijs/types': 3.23.0 + '@shikijs/vscode-textmate': 10.0.2 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@knighted/duel@4.1.0(typescript@5.9.3)': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + '@knighted/module': 1.6.0 + find-up: 8.0.0 + get-tsconfig: 4.14.0 + magic-string: 0.30.21 + read-package-up: 12.0.0 + typescript: 5.9.3 + + '@knighted/module@1.6.0': + dependencies: + magic-string: 0.30.21 + oxc-parser: 0.132.0 + periscopic: 4.0.3 + + '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + dependencies: + '@emnapi/core': 1.10.0 + '@emnapi/runtime': 1.10.0 + '@tybys/wasm-util': 0.10.2 + optional: true + + '@orval/angular@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/axios@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/core@8.15.0(typescript@5.9.3)': + dependencies: + '@scalar/openapi-types': 0.8.0 + acorn: 8.16.0 + compare-versions: 6.1.1 + debug: 4.4.3(supports-color@10.2.2) + esbuild: 0.28.0 + esutils: 2.0.3 + fs-extra: 11.3.5 + jiti: 2.7.0 + remeda: 2.38.0 + tinyglobby: 0.2.17 + typedoc: 0.28.19(typescript@5.9.3) + transitivePeerDependencies: + - supports-color + - typescript + + '@orval/effect@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + remeda: 2.38.0 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/fetch@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + '@scalar/openapi-types': 0.8.0 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/hono@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + '@orval/zod': 8.15.0(typescript@5.9.3) + fs-extra: 11.3.5 + remeda: 2.38.0 + optionalDependencies: + typescript: 5.9.3 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + + '@orval/mcp@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + '@orval/fetch': 8.15.0(typescript@5.9.3) + '@orval/zod': 8.15.0(typescript@5.9.3) + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/mock@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + remeda: 2.38.0 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/query@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + '@orval/fetch': 8.15.0(typescript@5.9.3) + remeda: 2.38.0 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/solid-start@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + '@scalar/openapi-types': 0.8.0 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/swr@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + '@orval/fetch': 8.15.0(typescript@5.9.3) + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@orval/zod@8.15.0(typescript@5.9.3)': + dependencies: + '@orval/core': 8.15.0(typescript@5.9.3) + remeda: 2.38.0 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + '@oxc-parser/binding-android-arm-eabi@0.132.0': + optional: true + + '@oxc-parser/binding-android-arm64@0.132.0': + optional: true + + '@oxc-parser/binding-darwin-arm64@0.132.0': + optional: true + + '@oxc-parser/binding-darwin-x64@0.132.0': + optional: true + + '@oxc-parser/binding-freebsd-x64@0.132.0': + optional: true + + '@oxc-parser/binding-linux-arm-gnueabihf@0.132.0': + optional: true + + '@oxc-parser/binding-linux-arm-musleabihf@0.132.0': + optional: true + + '@oxc-parser/binding-linux-arm64-gnu@0.132.0': + optional: true + + '@oxc-parser/binding-linux-arm64-musl@0.132.0': + optional: true + + '@oxc-parser/binding-linux-ppc64-gnu@0.132.0': + optional: true + + '@oxc-parser/binding-linux-riscv64-gnu@0.132.0': + optional: true + + '@oxc-parser/binding-linux-riscv64-musl@0.132.0': + optional: true + + '@oxc-parser/binding-linux-s390x-gnu@0.132.0': + optional: true + + '@oxc-parser/binding-linux-x64-gnu@0.132.0': + optional: true + + '@oxc-parser/binding-linux-x64-musl@0.132.0': + optional: true + + '@oxc-parser/binding-openharmony-arm64@0.132.0': + optional: true + + '@oxc-parser/binding-wasm32-wasi@0.132.0': + dependencies: + '@emnapi/core': 1.10.0 + '@emnapi/runtime': 1.10.0 + '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + optional: true + + '@oxc-parser/binding-win32-arm64-msvc@0.132.0': + optional: true + + '@oxc-parser/binding-win32-ia32-msvc@0.132.0': + optional: true + + '@oxc-parser/binding-win32-x64-msvc@0.132.0': + optional: true + + '@oxc-project/types@0.132.0': {} + + '@redocly/ajv@8.11.2': + dependencies: + fast-deep-equal: 3.1.3 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + uri-js-replace: 1.0.1 + + '@redocly/config@0.22.0': {} + + '@redocly/openapi-core@1.34.11(supports-color@10.2.2)': + dependencies: + '@redocly/ajv': 8.11.2 + '@redocly/config': 0.22.0 + colorette: 1.4.0 + https-proxy-agent: 7.0.6(supports-color@10.2.2) + js-levenshtein: 1.1.6 + js-yaml: 4.1.1 + minimatch: 5.1.9 + pluralize: 8.0.0 + yaml-ast-parser: 0.0.43 + transitivePeerDependencies: + - supports-color + + '@rollup/rollup-android-arm-eabi@4.61.1': + optional: true + + '@rollup/rollup-android-arm64@4.61.1': + optional: true + + '@rollup/rollup-darwin-arm64@4.61.1': + optional: true + + '@rollup/rollup-darwin-x64@4.61.1': + optional: true + + '@rollup/rollup-freebsd-arm64@4.61.1': + optional: true + + '@rollup/rollup-freebsd-x64@4.61.1': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.61.1': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.61.1': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.61.1': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.61.1': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.61.1': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.61.1': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.61.1': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.61.1': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.61.1': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.61.1': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.61.1': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.61.1': + optional: true + + '@rollup/rollup-linux-x64-musl@4.61.1': + optional: true + + '@rollup/rollup-openbsd-x64@4.61.1': + optional: true + + '@rollup/rollup-openharmony-arm64@4.61.1': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.61.1': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.61.1': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.61.1': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.61.1': + optional: true + + '@scalar/helpers@0.8.1': {} + + '@scalar/json-magic@0.12.15': + dependencies: + '@scalar/helpers': 0.8.1 + pathe: 2.0.3 + yaml: 2.9.0 + + '@scalar/openapi-parser@0.28.6': + dependencies: + '@scalar/helpers': 0.8.1 + '@scalar/json-magic': 0.12.15 + '@scalar/openapi-types': 0.9.1 + '@scalar/openapi-upgrader': 0.2.9 + ajv: 8.20.0 + ajv-draft-04: 1.0.0(ajv@8.20.0) + ajv-formats: 3.0.1(ajv@8.20.0) + jsonpointer: 5.0.1 + leven: 4.1.0 + yaml: 2.9.0 + + '@scalar/openapi-types@0.8.0': {} + + '@scalar/openapi-types@0.9.1': {} + + '@scalar/openapi-upgrader@0.2.9': + dependencies: + '@scalar/openapi-types': 0.9.1 + + '@sec-ant/readable-stream@0.4.1': {} + + '@shikijs/engine-oniguruma@3.23.0': + dependencies: + '@shikijs/types': 3.23.0 + '@shikijs/vscode-textmate': 10.0.2 + + '@shikijs/langs@3.23.0': + dependencies: + '@shikijs/types': 3.23.0 + + '@shikijs/themes@3.23.0': + dependencies: + '@shikijs/types': 3.23.0 + + '@shikijs/types@3.23.0': + dependencies: + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.4 + + '@shikijs/vscode-textmate@10.0.2': {} + + '@sindresorhus/merge-streams@4.0.0': {} + + '@standard-schema/spec@1.1.0': {} + + '@tybys/wasm-util@0.10.2': + dependencies: + tslib: 2.8.1 + optional: true + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/glob-to-regexp@0.4.4': {} + + '@types/hast@3.0.4': + dependencies: + '@types/unist': 3.0.3 + + '@types/node-fetch@2.6.13': + dependencies: + '@types/node': 25.9.2 + form-data: 4.0.4 + + '@types/node@25.9.2': + dependencies: + undici-types: 7.24.6 + + '@types/normalize-package-data@2.4.4': {} + + '@types/react@19.2.17': + dependencies: + csstype: 3.2.3 + + '@types/unist@3.0.3': {} + + '@vitest/expect@4.1.8': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.8 + '@vitest/utils': 4.1.8 + chai: 6.2.2 + tinyrainbow: 3.1.0 + + '@vitest/mocker@4.1.8(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))': + dependencies: + '@vitest/spy': 4.1.8 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0) + + '@vitest/pretty-format@4.1.8': + dependencies: + tinyrainbow: 3.1.0 + + '@vitest/runner@4.1.8': + dependencies: + '@vitest/utils': 4.1.8 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.8': + dependencies: + '@vitest/pretty-format': 4.1.8 + '@vitest/utils': 4.1.8 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.8': {} + + '@vitest/utils@4.1.8': + dependencies: + '@vitest/pretty-format': 4.1.8 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.0 + + acorn@8.16.0: {} + + agent-base@7.1.4: {} + + ajv-draft-04@1.0.0(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv-formats@3.0.1(ajv@8.20.0): + optionalDependencies: + ajv: 8.20.0 + + ajv@8.20.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.2 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + + ansi-colors@4.1.3: {} + + ansi-regex@5.0.1: {} + + argparse@2.0.1: {} + + assertion-error@2.0.1: {} + + asynckit@0.4.0: {} + + balanced-match@1.0.2: {} + + balanced-match@4.0.4: {} + + brace-expansion@2.0.3: + dependencies: + balanced-match: 1.0.2 + + brace-expansion@5.0.6: + dependencies: + balanced-match: 4.0.4 + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + chai@6.2.2: {} + + change-case@5.4.4: {} + + chokidar@5.0.0: + dependencies: + readdirp: 5.0.0 + + colorette@1.4.0: {} + + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + + commander@14.0.3: {} + + compare-versions@6.1.1: {} + + convert-source-map@2.0.0: {} + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + csstype@3.2.3: {} + + debug@4.4.3(supports-color@10.2.2): + dependencies: + ms: 2.1.3 + optionalDependencies: + supports-color: 10.2.2 + + delayed-stream@1.0.0: {} + + dequal@2.0.3: {} + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + enquirer@2.4.1: + dependencies: + ansi-colors: 4.1.3 + strip-ansi: 6.0.1 + + entities@4.5.0: {} + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-module-lexer@2.1.0: {} + + es-object-atoms@1.1.1: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.2 + + esbuild@0.27.7: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.7 + '@esbuild/android-arm': 0.27.7 + '@esbuild/android-arm64': 0.27.7 + '@esbuild/android-x64': 0.27.7 + '@esbuild/darwin-arm64': 0.27.7 + '@esbuild/darwin-x64': 0.27.7 + '@esbuild/freebsd-arm64': 0.27.7 + '@esbuild/freebsd-x64': 0.27.7 + '@esbuild/linux-arm': 0.27.7 + '@esbuild/linux-arm64': 0.27.7 + '@esbuild/linux-ia32': 0.27.7 + '@esbuild/linux-loong64': 0.27.7 + '@esbuild/linux-mips64el': 0.27.7 + '@esbuild/linux-ppc64': 0.27.7 + '@esbuild/linux-riscv64': 0.27.7 + '@esbuild/linux-s390x': 0.27.7 + '@esbuild/linux-x64': 0.27.7 + '@esbuild/netbsd-arm64': 0.27.7 + '@esbuild/netbsd-x64': 0.27.7 + '@esbuild/openbsd-arm64': 0.27.7 + '@esbuild/openbsd-x64': 0.27.7 + '@esbuild/openharmony-arm64': 0.27.7 + '@esbuild/sunos-x64': 0.27.7 + '@esbuild/win32-arm64': 0.27.7 + '@esbuild/win32-ia32': 0.27.7 + '@esbuild/win32-x64': 0.27.7 + + esbuild@0.28.0: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.0 + '@esbuild/android-arm': 0.28.0 + '@esbuild/android-arm64': 0.28.0 + '@esbuild/android-x64': 0.28.0 + '@esbuild/darwin-arm64': 0.28.0 + '@esbuild/darwin-x64': 0.28.0 + '@esbuild/freebsd-arm64': 0.28.0 + '@esbuild/freebsd-x64': 0.28.0 + '@esbuild/linux-arm': 0.28.0 + '@esbuild/linux-arm64': 0.28.0 + '@esbuild/linux-ia32': 0.28.0 + '@esbuild/linux-loong64': 0.28.0 + '@esbuild/linux-mips64el': 0.28.0 + '@esbuild/linux-ppc64': 0.28.0 + '@esbuild/linux-riscv64': 0.28.0 + '@esbuild/linux-s390x': 0.28.0 + '@esbuild/linux-x64': 0.28.0 + '@esbuild/netbsd-arm64': 0.28.0 + '@esbuild/netbsd-x64': 0.28.0 + '@esbuild/openbsd-arm64': 0.28.0 + '@esbuild/openbsd-x64': 0.28.0 + '@esbuild/openharmony-arm64': 0.28.0 + '@esbuild/sunos-x64': 0.28.0 + '@esbuild/win32-arm64': 0.28.0 + '@esbuild/win32-ia32': 0.28.0 + '@esbuild/win32-x64': 0.28.0 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + esutils@2.0.3: {} + + execa@9.6.1: + dependencies: + '@sindresorhus/merge-streams': 4.0.0 + cross-spawn: 7.0.6 + figures: 6.1.0 + get-stream: 9.0.1 + human-signals: 8.0.1 + is-plain-obj: 4.1.0 + is-stream: 4.0.1 + npm-run-path: 6.0.0 + pretty-ms: 9.3.0 + signal-exit: 4.1.0 + strip-final-newline: 4.0.0 + yoctocolors: 2.1.2 + + expect-type@1.3.0: {} + + fast-deep-equal@3.1.3: {} + + fast-uri@3.1.2: {} + + fdir@6.5.0(picomatch@4.0.4): + optionalDependencies: + picomatch: 4.0.4 + + fetch-mock@12.6.0: + dependencies: + '@types/glob-to-regexp': 0.4.4 + dequal: 2.0.3 + glob-to-regexp: 0.4.1 + regexparam: 3.0.0 + + figures@6.1.0: + dependencies: + is-unicode-supported: 2.1.0 + + find-up-simple@1.0.1: {} + + find-up@8.0.0: + dependencies: + locate-path: 8.0.0 + unicorn-magic: 0.3.0 + + form-data@4.0.4: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.2 + mime-types: 2.1.35 + + fs-extra@11.3.5: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.1 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.2 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.1 + + get-stream@9.0.1: + dependencies: + '@sec-ant/readable-stream': 0.4.1 + is-stream: 4.0.1 + + get-tsconfig@4.14.0: + dependencies: + resolve-pkg-maps: 1.0.0 + + glob-to-regexp@0.4.1: {} + + gopd@1.2.0: {} + + graceful-fs@4.2.11: {} + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + hasown@2.0.2: + dependencies: + function-bind: 1.1.2 + + hosted-git-info@9.0.3: + dependencies: + lru-cache: 11.5.1 + + https-proxy-agent@7.0.6(supports-color@10.2.2): + dependencies: + agent-base: 7.1.4 + debug: 4.4.3(supports-color@10.2.2) + transitivePeerDependencies: + - supports-color + + human-signals@8.0.1: {} + + index-to-position@1.2.0: {} + + is-plain-obj@4.1.0: {} + + is-reference@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + is-stream@4.0.1: {} + + is-unicode-supported@2.1.0: {} + + isexe@2.0.0: {} + + jiti@2.7.0: {} + + js-levenshtein@1.1.6: {} + + js-tokens@4.0.0: {} + + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + + json-schema-traverse@1.0.0: {} + + jsonfile@6.2.1: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + jsonpointer@5.0.1: {} + + leven@4.1.0: {} + + linkify-it@5.0.1: + dependencies: + uc.micro: 2.1.0 + + locate-path@8.0.0: + dependencies: + p-locate: 6.0.0 + + lru-cache@11.5.1: {} + + lunr@2.3.9: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + markdown-it@14.2.0: + dependencies: + argparse: 2.0.1 + entities: 4.5.0 + linkify-it: 5.0.1 + mdurl: 2.0.0 + punycode.js: 2.3.1 + uc.micro: 2.1.0 + + math-intrinsics@1.1.0: {} + + mdurl@2.0.0: {} + + mime-db@1.52.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + minimatch@10.2.5: + dependencies: + brace-expansion: 5.0.6 + + minimatch@5.1.9: + dependencies: + brace-expansion: 2.0.3 + + ms@2.1.3: {} + + nanoid@3.3.12: {} + + normalize-package-data@8.0.0: + dependencies: + hosted-git-info: 9.0.3 + semver: 7.8.2 + validate-npm-package-license: 3.0.4 + + npm-run-path@6.0.0: + dependencies: + path-key: 4.0.0 + unicorn-magic: 0.3.0 + + obug@2.1.2: {} + + openapi-fetch@0.17.0: + dependencies: + openapi-typescript-helpers: 0.1.0 + + openapi-typescript-helpers@0.1.0: {} + + openapi-typescript@7.13.0(patch_hash=0e016926efaca4cd6909b2bf6c9b2f03eb66a5084b7bdbf10313eeee90793e01)(typescript@5.9.3): + dependencies: + '@redocly/openapi-core': 1.34.11(supports-color@10.2.2) + ansi-colors: 4.1.3 + change-case: 5.4.4 + parse-json: 8.3.0 + supports-color: 10.2.2 + typescript: 5.9.3 + yargs-parser: 21.1.1 + + orval@8.15.0(prettier@3.8.3)(typescript@5.9.3): + dependencies: + '@commander-js/extra-typings': 14.0.0(commander@14.0.3) + '@orval/angular': 8.15.0(typescript@5.9.3) + '@orval/axios': 8.15.0(typescript@5.9.3) + '@orval/core': 8.15.0(typescript@5.9.3) + '@orval/effect': 8.15.0(typescript@5.9.3) + '@orval/fetch': 8.15.0(typescript@5.9.3) + '@orval/hono': 8.15.0(typescript@5.9.3) + '@orval/mcp': 8.15.0(typescript@5.9.3) + '@orval/mock': 8.15.0(typescript@5.9.3) + '@orval/query': 8.15.0(typescript@5.9.3) + '@orval/solid-start': 8.15.0(typescript@5.9.3) + '@orval/swr': 8.15.0(typescript@5.9.3) + '@orval/zod': 8.15.0(typescript@5.9.3) + '@scalar/json-magic': 0.12.15 + '@scalar/openapi-parser': 0.28.6 + '@scalar/openapi-types': 0.8.0 + chokidar: 5.0.0 + commander: 14.0.3 + enquirer: 2.4.1 + execa: 9.6.1 + find-up: 8.0.0 + fs-extra: 11.3.5 + get-tsconfig: 4.14.0 + jiti: 2.7.0 + js-yaml: 4.1.1 + remeda: 2.38.0 + string-argv: 0.3.2 + typedoc: 0.28.19(typescript@5.9.3) + typedoc-plugin-coverage: 4.0.3(typedoc@0.28.19(typescript@5.9.3)) + typedoc-plugin-markdown: 4.12.0(typedoc@0.28.19(typescript@5.9.3)) + optionalDependencies: + prettier: 3.8.3 + transitivePeerDependencies: + - '@faker-js/faker' + - supports-color + - typescript + + oxc-parser@0.132.0: + dependencies: + '@oxc-project/types': 0.132.0 + optionalDependencies: + '@oxc-parser/binding-android-arm-eabi': 0.132.0 + '@oxc-parser/binding-android-arm64': 0.132.0 + '@oxc-parser/binding-darwin-arm64': 0.132.0 + '@oxc-parser/binding-darwin-x64': 0.132.0 + '@oxc-parser/binding-freebsd-x64': 0.132.0 + '@oxc-parser/binding-linux-arm-gnueabihf': 0.132.0 + '@oxc-parser/binding-linux-arm-musleabihf': 0.132.0 + '@oxc-parser/binding-linux-arm64-gnu': 0.132.0 + '@oxc-parser/binding-linux-arm64-musl': 0.132.0 + '@oxc-parser/binding-linux-ppc64-gnu': 0.132.0 + '@oxc-parser/binding-linux-riscv64-gnu': 0.132.0 + '@oxc-parser/binding-linux-riscv64-musl': 0.132.0 + '@oxc-parser/binding-linux-s390x-gnu': 0.132.0 + '@oxc-parser/binding-linux-x64-gnu': 0.132.0 + '@oxc-parser/binding-linux-x64-musl': 0.132.0 + '@oxc-parser/binding-openharmony-arm64': 0.132.0 + '@oxc-parser/binding-wasm32-wasi': 0.132.0 + '@oxc-parser/binding-win32-arm64-msvc': 0.132.0 + '@oxc-parser/binding-win32-ia32-msvc': 0.132.0 + '@oxc-parser/binding-win32-x64-msvc': 0.132.0 + + p-limit@4.0.0: + dependencies: + yocto-queue: 1.2.2 + + p-locate@6.0.0: + dependencies: + p-limit: 4.0.0 + + parse-json@8.3.0: + dependencies: + '@babel/code-frame': 7.29.0 + index-to-position: 1.2.0 + type-fest: 4.41.0 + + parse-ms@4.0.0: {} + + path-key@3.1.1: {} + + path-key@4.0.0: {} + + pathe@2.0.3: {} + + periscopic@4.0.3: + dependencies: + '@types/estree': 1.0.9 + is-reference: 3.0.3 + zimmerframe: 1.1.4 + + picocolors@1.1.1: {} + + picomatch@4.0.4: {} + + pluralize@8.0.0: {} + + postcss@8.5.15: + dependencies: + nanoid: 3.3.12 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prettier@3.8.3: {} + + pretty-ms@9.3.0: + dependencies: + parse-ms: 4.0.0 + + punycode.js@2.3.1: {} + + react@19.2.7: {} + + read-package-up@12.0.0: + dependencies: + find-up-simple: 1.0.1 + read-pkg: 10.1.0 + type-fest: 5.7.0 + + read-pkg@10.1.0: + dependencies: + '@types/normalize-package-data': 2.4.4 + normalize-package-data: 8.0.0 + parse-json: 8.3.0 + type-fest: 5.7.0 + unicorn-magic: 0.4.0 + + readdirp@5.0.0: {} + + regexparam@3.0.0: {} + + remeda@2.38.0: {} + + require-from-string@2.0.2: {} + + resolve-pkg-maps@1.0.0: {} + + rollup@4.61.1: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.61.1 + '@rollup/rollup-android-arm64': 4.61.1 + '@rollup/rollup-darwin-arm64': 4.61.1 + '@rollup/rollup-darwin-x64': 4.61.1 + '@rollup/rollup-freebsd-arm64': 4.61.1 + '@rollup/rollup-freebsd-x64': 4.61.1 + '@rollup/rollup-linux-arm-gnueabihf': 4.61.1 + '@rollup/rollup-linux-arm-musleabihf': 4.61.1 + '@rollup/rollup-linux-arm64-gnu': 4.61.1 + '@rollup/rollup-linux-arm64-musl': 4.61.1 + '@rollup/rollup-linux-loong64-gnu': 4.61.1 + '@rollup/rollup-linux-loong64-musl': 4.61.1 + '@rollup/rollup-linux-ppc64-gnu': 4.61.1 + '@rollup/rollup-linux-ppc64-musl': 4.61.1 + '@rollup/rollup-linux-riscv64-gnu': 4.61.1 + '@rollup/rollup-linux-riscv64-musl': 4.61.1 + '@rollup/rollup-linux-s390x-gnu': 4.61.1 + '@rollup/rollup-linux-x64-gnu': 4.61.1 + '@rollup/rollup-linux-x64-musl': 4.61.1 + '@rollup/rollup-openbsd-x64': 4.61.1 + '@rollup/rollup-openharmony-arm64': 4.61.1 + '@rollup/rollup-win32-arm64-msvc': 4.61.1 + '@rollup/rollup-win32-ia32-msvc': 4.61.1 + '@rollup/rollup-win32-x64-gnu': 4.61.1 + '@rollup/rollup-win32-x64-msvc': 4.61.1 + fsevents: 2.3.3 + + semver@7.8.2: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + siginfo@2.0.0: {} + + signal-exit@4.1.0: {} + + source-map-js@1.2.1: {} + + spdx-correct@3.2.0: + dependencies: + spdx-expression-parse: 3.0.1 + spdx-license-ids: 3.0.23 + + spdx-exceptions@2.5.0: {} + + spdx-expression-parse@3.0.1: + dependencies: + spdx-exceptions: 2.5.0 + spdx-license-ids: 3.0.23 + + spdx-license-ids@3.0.23: {} + + stackback@0.0.2: {} + + std-env@4.1.0: {} + + string-argv@0.3.2: {} + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-final-newline@4.0.0: {} + + supports-color@10.2.2: {} + + tagged-tag@1.0.0: {} + + tinybench@2.9.0: {} + + tinyexec@1.2.4: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + + tinyrainbow@3.1.0: {} + + tslib@2.8.1: {} + + tsx@4.22.4: + dependencies: + esbuild: 0.28.0 + optionalDependencies: + fsevents: 2.3.3 + + type-fest@4.41.0: {} + + type-fest@5.7.0: + dependencies: + tagged-tag: 1.0.0 + + typedoc-plugin-coverage@4.0.3(typedoc@0.28.19(typescript@5.9.3)): + dependencies: + typedoc: 0.28.19(typescript@5.9.3) + + typedoc-plugin-markdown@4.12.0(typedoc@0.28.19(typescript@5.9.3)): + dependencies: + typedoc: 0.28.19(typescript@5.9.3) + + typedoc@0.28.19(typescript@5.9.3): + dependencies: + '@gerrit0/mini-shiki': 3.23.0 + lunr: 2.3.9 + markdown-it: 14.2.0 + minimatch: 10.2.5 + typescript: 5.9.3 + yaml: 2.9.0 + + typescript@5.9.3: {} + + uc.micro@2.1.0: {} + + undici-types@7.24.6: {} + + unicorn-magic@0.3.0: {} + + unicorn-magic@0.4.0: {} + + universalify@2.0.1: {} + + uri-js-replace@1.0.1: {} + + validate-npm-package-license@3.0.4: + dependencies: + spdx-correct: 3.2.0 + spdx-expression-parse: 3.0.1 + + vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0): + dependencies: + esbuild: 0.27.7 + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + postcss: 8.5.15 + rollup: 4.61.1 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 25.9.2 + fsevents: 2.3.3 + jiti: 2.7.0 + tsx: 4.22.4 + yaml: 2.9.0 + + vitest@4.1.8(@types/node@25.9.2)(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)): + dependencies: + '@vitest/expect': 4.1.8 + '@vitest/mocker': 4.1.8(vite@7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0)) + '@vitest/pretty-format': 4.1.8 + '@vitest/runner': 4.1.8 + '@vitest/snapshot': 4.1.8 + '@vitest/spy': 4.1.8 + '@vitest/utils': 4.1.8 + es-module-lexer: 2.1.0 + expect-type: 1.3.0 + magic-string: 0.30.21 + obug: 2.1.2 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 4.1.0 + tinybench: 2.9.0 + tinyexec: 1.2.4 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.0 + vite: 7.3.1(@types/node@25.9.2)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 25.9.2 + transitivePeerDependencies: + - msw + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + yaml-ast-parser@0.0.43: {} + + yaml@2.9.0: {} + + yargs-parser@21.1.1: {} + + yocto-queue@1.2.2: {} + + yoctocolors@2.1.2: {} + + zimmerframe@1.1.4: {} + + zod@4.4.3: {} diff --git a/api/client/javascript/pnpm-workspace.yaml b/api/client/javascript/pnpm-workspace.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b608f1d7c6e16071b76d3b418e13c873f091dfaf --- /dev/null +++ b/api/client/javascript/pnpm-workspace.yaml @@ -0,0 +1,10 @@ +blockExoticSubdeps: true +minimumReleaseAge: 4320 +trustPolicy: no-downgrade +patchedDependencies: + openapi-typescript: patches/openapi-typescript.patch +overrides: + 'vite@>=7.0.0 <=7.3.1': '>=7.3.2' + 'vite@>=7.1.0 <=7.3.1': '>=7.3.2' +allowBuilds: + esbuild: true diff --git a/api/client/javascript/scripts/add-as-const.ts b/api/client/javascript/scripts/add-as-const.ts new file mode 100644 index 0000000000000000000000000000000000000000..c61aa8fd41be76050bf3dcb1997db96575309a88 --- /dev/null +++ b/api/client/javascript/scripts/add-as-const.ts @@ -0,0 +1,16 @@ +import { readFileSync, writeFileSync } from 'node:fs' + +/** + * Post-generation workaround for orval's zod output: object-literal defaults + * are emitted without `as const`, so property values widen to `string` and + * fail Zod's `.default()` signature when the schema expects a literal type. + * Remove this script once orval emits `as const` for object-literal defaults. + * See: https://github.com/orval-labs/orval/issues/3244 + */ +const file = new URL('../src/zod/index.ts', import.meta.url) +const src = readFileSync(file, 'utf8') +const fixed = src.replace( + /(^export const \w+Default =\s*\{[^{}]*\})/gm, + '$1 as const', +) +writeFileSync(file, fixed) diff --git a/api/client/javascript/scripts/generate.ts b/api/client/javascript/scripts/generate.ts new file mode 100644 index 0000000000000000000000000000000000000000..e732f61f21bfcb915d8be8515e7c583b021bb805 --- /dev/null +++ b/api/client/javascript/scripts/generate.ts @@ -0,0 +1,51 @@ +import fs from 'node:fs' +import openapiTS, { astToString } from 'openapi-typescript' +import { factory, SyntaxKind } from 'typescript' + +const DATE = factory.createTypeReferenceNode(factory.createIdentifier('Date')) // `Date` +const NULL = factory.createLiteralTypeNode(factory.createNull()) // `null` +const STRING = factory.createKeywordTypeNode(SyntaxKind.StringKeyword) // `string` + +const schema = new URL('../../../openapi.cloud.yaml', import.meta.url) + +const ast = await openapiTS(schema, { + defaultNonNullable: false, + rootTypes: true, + rootTypesNoSchemaPrefix: true, + transform(schemaObject, metadata) { + if (metadata.path === '#/components/schemas/Event') { + if ( + schemaObject.type === 'string' && + !schemaObject.nullable && + !['customer-id', 'com.example.someevent'].includes(schemaObject.example) + ) { + return { + questionToken: true, + schema: STRING, + } + } + } + if (schemaObject.format === 'date-time') { + const allowString = + (metadata.schema && + 'in' in metadata.schema && + metadata.schema.in === 'query') || + metadata.path?.includes('/parameters/query') + + // allow string in query parameters + if (allowString) { + return schemaObject.nullable + ? factory.createUnionTypeNode([DATE, NULL, STRING]) + : factory.createUnionTypeNode([DATE, STRING]) + } + + return schemaObject.nullable + ? factory.createUnionTypeNode([DATE, NULL]) + : DATE + } + }, +}) + +const contents = astToString(ast) + +fs.writeFileSync('./src/client/schemas.ts', contents) diff --git a/api/client/javascript/src/client/addons.ts b/api/client/javascript/src/client/addons.ts new file mode 100644 index 0000000000000000000000000000000000000000..346b7e58caa2c580cc1182c020b1ffb2c349f5ea --- /dev/null +++ b/api/client/javascript/src/client/addons.ts @@ -0,0 +1,122 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { AddonCreate, operations, paths } from './schemas.js' +import { transformResponse } from './utils.js' + +export class Addons { + constructor(private client: Client) {} + + /** + * Create a addon + * @param addon - The addon to create + * @param options - Optional request options + * @returns The created addon + */ + public async create(addon: AddonCreate, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/addons', { + body: addon, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List addons + * @param params - Optional parameters for listing addons + * @param options - Optional request options + * @returns A list of addons + */ + public async list( + params?: operations['listAddons']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/addons', { + params: { query: params }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get an addon by ID + * @param addonId - The ID of the addon to retrieve + * @param options - Optional request options + * @returns The addon + */ + public async get(addonId: string, options?: RequestOptions) { + const resp = await this.client.GET('/api/v1/addons/{addonId}', { + params: { path: { addonId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update an addon + * @param addonId - The ID of the addon to update + * @param addon - The addon data to update + * @param options - Optional request options + * @returns The updated addon + */ + public async update( + addonId: string, + addon: operations['updateAddon']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/addons/{addonId}', { + body: addon, + params: { path: { addonId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete an addon by ID + * @param addonId - The ID of the addon to delete + * @param options - Optional request options + * @returns void or standard error response structure + */ + public async delete(addonId: string, options?: RequestOptions) { + const resp = await this.client.DELETE('/api/v1/addons/{addonId}', { + params: { path: { addonId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Publish an addon + * @param addonId - The ID of the addon to publish + * @param options - Optional request options + * @returns The published addon + */ + public async publish(addonId: string, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/addons/{addonId}/publish', { + params: { path: { addonId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Archive an addon + * @param addonId - The ID of the addon to archive + * @param options - Optional request options + * @returns The archived addon + */ + public async archive(addonId: string, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/addons/{addonId}/archive', { + params: { path: { addonId } }, + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/apps.ts b/api/client/javascript/src/client/apps.ts new file mode 100644 index 0000000000000000000000000000000000000000..254d457471ec0e870e2a44843ad2014109ccec62 --- /dev/null +++ b/api/client/javascript/src/client/apps.ts @@ -0,0 +1,335 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + AppReplaceUpdate, + CreateStripeCheckoutSessionRequest, + operations, + paths, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Apps + * Manage integrations for extending OpenMeter's functionality. + */ +export class Apps { + public marketplace: AppMarketplace + public stripe: AppStripe + public customInvoicing: AppCustomInvoicing + + constructor(private client: Client) { + this.marketplace = new AppMarketplace(client) + this.stripe = new AppStripe(client) + this.customInvoicing = new AppCustomInvoicing(client) + } + + /** + * List apps + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The apps + */ + public async list( + query?: operations['listApps']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/apps', { + params: { query }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get an app + * @param id - The ID of the app + * @param signal - An optional abort signal + * @returns The app + */ + public async get( + id: operations['getApp']['parameters']['path']['id'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/apps/{id}', { + params: { path: { id } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update an app + * @param id - The ID of the app + * @param body - The body of the request + * @param signal - An optional abort signal + * @returns The app + */ + public async update( + id: operations['updateApp']['parameters']['path']['id'], + body: AppReplaceUpdate, + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/apps/{id}', { + body, + params: { path: { id } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Uninstall an app + * @param id - The ID of the app + * @param signal - An optional abort signal + * @returns The app + */ + public async uninstall( + id: operations['uninstallApp']['parameters']['path']['id'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/apps/{id}', { + params: { path: { id } }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * App Marketplace + * Available apps from the OpenMeter Marketplace. + */ +export class AppMarketplace { + constructor(private client: Client) {} + + /** + * List available apps + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The apps + */ + public async list( + query?: operations['listMarketplaceListings']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/marketplace/listings', { + params: { query }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get details for a listing + * @param type - The type of the listing + * @param signal - An optional abort signal + * @returns The listing + */ + public async get( + type: operations['getMarketplaceListing']['parameters']['path']['type'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/marketplace/listings/{type}', { + params: { path: { type } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Install an app via OAuth. Returns a URL to start the OAuth 2.0 flow. + * @param type - The type of the listing + * @param signal - An optional abort signal + * @returns The OAuth2 install URL + */ + public async getOauth2InstallUrl( + type: operations['marketplaceOAuth2InstallGetURL']['parameters']['path']['type'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/marketplace/listings/{type}/install/oauth2', + { + params: { path: { type } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Authorize OAuth2 code. Verifies the OAuth code and exchanges it for a token and refresh token + * @param type - The type of the listing + * @param signal - An optional abort signal + * @returns The authorization URL + */ + public async authorizeOauth2( + type: operations['marketplaceOAuth2InstallAuthorize']['parameters']['path']['type'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/marketplace/listings/{type}/install/oauth2/authorize', + { + params: { path: { type } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Install an app via API key. + * @param type - The type of the listing + * @param signal - An optional abort signal + * @returns The installation + */ + public async installWithAPIKey( + type: operations['marketplaceAppAPIKeyInstall']['parameters']['path']['type'], + body: operations['marketplaceAppAPIKeyInstall']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/marketplace/listings/{type}/install/apikey', + { + body, + params: { path: { type } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Stripe App + */ +export class AppStripe { + constructor(private client: Client) {} + + /** + * Create a checkout session + * @param body - The body of the request + * @param signal - An optional abort signal + * @returns The checkout session + */ + public async createCheckoutSession( + body: CreateStripeCheckoutSessionRequest, + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/stripe/checkout/sessions', { + body, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update Stripe API key + * @param id - The ID of the app + * @param body - The API key data + * @param options - The request options + * @returns The updated API key + * @deprecated + */ + public async updateApiKey( + id: string, + body: operations['updateStripeAPIKey']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/apps/{id}/stripe/api-key', { + body, + params: { path: { id } }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Custom Invoicing App + */ +export class AppCustomInvoicing { + constructor(private client: Client) {} + + /** + * Submit draft synchronization results + * @param invoiceId - The ID of the invoice + * @param body - The body of the request + * @param options - The request options + * @returns The synchronization result + */ + public async draftSynchronized( + invoiceId: string, + body: operations['appCustomInvoicingDraftSynchronized']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized', + { + body, + params: { path: { invoiceId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Submit issuing synchronization results + * @param invoiceId - The ID of the invoice + * @param body - The body of the request + * @param options - The request options + * @returns The synchronization result + */ + public async issuingSynchronized( + invoiceId: string, + body: operations['appCustomInvoicingIssuingSynchronized']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized', + { + body, + params: { path: { invoiceId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Update payment status + * @param invoiceId - The ID of the invoice + * @param body - The body of the request + * @param options - The request options + * @returns The payment status update result + */ + public async updatePaymentStatus( + invoiceId: string, + body: operations['appCustomInvoicingUpdatePaymentStatus']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/apps/custom-invoicing/{invoiceId}/payment/status', + { + body, + params: { path: { invoiceId } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/billing.ts b/api/client/javascript/src/client/billing.ts new file mode 100644 index 0000000000000000000000000000000000000000..917bd56b8d698106d2e92908ff43c2d0fa62327d --- /dev/null +++ b/api/client/javascript/src/client/billing.ts @@ -0,0 +1,525 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + BillingProfileCreate, + BillingProfileCustomerOverrideCreate, + BillingProfileReplaceUpdateWithWorkflow, + InvoicePendingLineCreateInput, + InvoiceReplaceUpdate, + InvoiceSimulationInput, + operations, + paths, + VoidInvoiceActionInput, +} from './schemas.js' +import { transformResponse } from './utils.js' +/** + * Billing + */ +export class Billing { + public profiles: BillingProfiles + public invoices: BillingInvoices + public customers: BillingCustomers + + constructor(private client: Client) { + this.profiles = new BillingProfiles(this.client) + this.invoices = new BillingInvoices(this.client) + this.customers = new BillingCustomers(this.client) + } +} + +/** + * Billing Profiles + */ +export class BillingProfiles { + constructor(private client: Client) {} + + /** + * Create a billing profile + * @param billingProfile - The billing profile to create + * @param signal - An optional abort signal + * @returns The created billing profile + */ + public async create( + billingProfile: BillingProfileCreate, + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/billing/profiles', { + body: billingProfile, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a billing profile by ID + * @param id - The ID of the billing profile to get + * @param signal - An optional abort signal + * @returns The billing profile + */ + public async get( + id: operations['getBillingProfile']['parameters']['path']['id'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/billing/profiles/{id}', { + params: { + path: { id }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List billing profiles + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The billing profiles + */ + public async list( + query?: operations['listBillingProfiles']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/billing/profiles', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update a billing profile + * @param id - The ID of the billing profile to update + * @param billingProfile - The billing profile to update + * @param signal - An optional abort signal + * @returns The updated billing profile + */ + public async update( + id: operations['updateBillingProfile']['parameters']['path']['id'], + billingProfile: BillingProfileReplaceUpdateWithWorkflow, + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/billing/profiles/{id}', { + body: billingProfile, + params: { + path: { id }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a billing profile + * @param id - The ID of the billing profile to delete + * @param options - The request options + * @returns The deleted billing profile + */ + public async delete( + id: operations['deleteBillingProfile']['parameters']['path']['id'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/billing/profiles/{id}', { + params: { + path: { id }, + }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Billing Invoices + */ +export class BillingInvoices { + constructor(private client: Client) {} + + /** + * List invoices + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The invoices + */ + public async list( + query?: operations['listInvoices']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/billing/invoices', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get an invoice by ID + * @param id - The ID of the invoice to get + * @param signal - An optional abort signal + * @returns The invoice + */ + public async get( + id: operations['getInvoice']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/billing/invoices/{invoiceId}', { + params: { + path: { invoiceId: id }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update an invoice + * @description Only invoices in draft or earlier status can be updated. + * @param id - The ID of the invoice to update + * @param invoice - The invoice to update + * @param signal - An optional abort signal + * @returns The updated invoice + */ + public async update( + id: operations['updateInvoice']['parameters']['path']['invoiceId'], + invoice: InvoiceReplaceUpdate, + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/billing/invoices/{invoiceId}', { + body: invoice, + params: { path: { invoiceId: id } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete an invoice + * @description Only invoices that are in the draft (or earlier) status can be deleted. + * @param id - The ID of the invoice to delete + * @param options - The request options + * @returns The deleted invoice + */ + public async delete( + id: operations['deleteInvoice']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/billing/invoices/{invoiceId}', + { + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Advance the invoice to the next status + * @description The call doesn't "approve the invoice", it only advances the invoice to the next status if the transition would be automatic. The action can be called when the invoice's statusDetails' actions field contain the "advance" action. + * @param id - The ID of the invoice to advance + * @param signal - An optional abort signal + * @returns The advanced invoice + */ + public async advance( + id: operations['advanceInvoiceAction']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/invoices/{invoiceId}/advance', + { + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Approve an invoice + * @description This call instantly sends the invoice to the customer using the configured billing profile app. + * @param id - The ID of the invoice to approve + * @param signal - An optional abort signal + * @returns The approved invoice + */ + public async approve( + id: operations['approveInvoiceAction']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/invoices/{invoiceId}/approve', + { + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Retry advancing the invoice after a failed attempt. + * @param id - The ID of the invoice to retry + * @param signal - An optional abort signal + * @returns The retried invoice + */ + public async retry( + id: operations['retryInvoiceAction']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/invoices/{invoiceId}/retry', + { + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Void an invoice + * @description Void an invoice + * + * Only invoices that have been alread issued can be voided. + * @param id - The ID of the invoice to void + * @param signal - An optional abort signal + * @returns The voided invoice + */ + public async void( + id: operations['voidInvoiceAction']['parameters']['path']['invoiceId'], + body: VoidInvoiceActionInput, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/invoices/{invoiceId}/void', + { + body, + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Recalculate an invoice's tax amounts + * @param id - The ID of the invoice to recalculate + * @param signal - An optional abort signal + * @returns The recalculated invoice + */ + public async recalculateTax( + id: operations['recalculateInvoiceTaxAction']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/invoices/{invoiceId}/taxes/recalculate', + { + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Snapshot invoice line item quantities + * @description Snapshot the quantities of the invoice line items. This is useful for invoices that have usage-based line items. + * @param id - The ID of the invoice to snapshot + * @param signal - An optional abort signal + * @returns The invoice with snapshotted quantities + */ + public async snapshotQuantities( + id: operations['snapshotQuantitiesInvoiceAction']['parameters']['path']['invoiceId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/invoices/{invoiceId}/snapshot-quantities', + { + params: { path: { invoiceId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Simulate an invoice for a customer + * @param id - The ID of the customer to simulate the invoice for + * @param signal - An optional abort signal + * @returns The simulated invoice + */ + public async simulate( + id: operations['simulateInvoice']['parameters']['path']['customerId'], + body: InvoiceSimulationInput, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/customers/{customerId}/invoices/simulate', + { + body, + params: { path: { customerId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Create pending line items + * @description Create new pending line items (charges). + * This call is used to create a new pending line item for the customer if required a new + * gathering invoice will be created. + * + * A new invoice will be created if: + * - there is no invoice in gathering state + * - the currency of the line item doesn't match the currency of any invoices in gathering state + * @param customerId - The ID of the customer to create the line items for + * @param body - The line items to create + * @param signal - An optional abort signal + * @returns The created line items + */ + public async createLineItems( + customerId: operations['createPendingInvoiceLine']['parameters']['path']['customerId'], + body: InvoicePendingLineCreateInput, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/billing/customers/{customerId}/invoices/pending-lines', + { + body, + params: { path: { customerId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Invoice a customer based on the pending line items + * @description Create a new invoice from the pending line items. This should only be called if for some reason we need to invoice a customer outside of the normal billing cycle. + * @param body - The invoice data + * @param options - The request options + * @returns The created invoices + */ + public async invoicePendingLines( + body: operations['invoicePendingLinesAction']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/billing/invoices/invoice', { + body, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Billing Customer Invoices and Overrides + */ +export class BillingCustomers { + constructor(private client: Client) {} + + /** + * Create or update a customer override + * @param id - The ID of the customer to create the override for + * @param body - The customer override to create + * @param signal - An optional abort signal + * @returns The created customer override + */ + public async createOverride( + id: operations['upsertBillingProfileCustomerOverride']['parameters']['path']['customerId'], + body: BillingProfileCustomerOverrideCreate, + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v1/billing/customers/{customerId}', + { + body, + params: { path: { customerId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get a customer override + * @param id - The ID of the customer to get the override for + * @param signal - An optional abort signal + * @returns The customer override + */ + public async getOverride( + id: operations['getBillingProfileCustomerOverride']['parameters']['path']['customerId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/billing/customers/{customerId}', + { + params: { path: { customerId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List customer overrides + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The customer overrides + */ + public async listOverrides( + query?: operations['listBillingProfileCustomerOverrides']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/billing/customers', { + params: { query }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a customer override + * @param id - The ID of the customer to delete the override for + * @param signal - An optional abort signal + * @returns The deleted customer override + */ + public async deleteOverride( + id: operations['deleteBillingProfileCustomerOverride']['parameters']['path']['customerId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/billing/customers/{customerId}', + { + params: { path: { customerId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/common.ts b/api/client/javascript/src/client/common.ts new file mode 100644 index 0000000000000000000000000000000000000000..69ff2d94e541474fbb98b7a2732ed91f8bdaea11 --- /dev/null +++ b/api/client/javascript/src/client/common.ts @@ -0,0 +1,66 @@ +import type { UnexpectedProblemResponse } from './schemas.js' + +/** + * Request options + */ +export type RequestOptions = Pick + +/** + * An error that occurred during an HTTP request + */ +export class HTTPError extends Error { + public name = 'HTTPError' + public client = 'OpenMeter' + + constructor( + public message: string, + public type: string, + public title: string, + public status: number, + public url: string, + protected __raw?: Record, + ) { + super(message) + } + + static fromResponse(resp: { + response: Response + error?: UnexpectedProblemResponse + }): HTTPError { + if ( + resp.response.headers.get('Content-Type') === + 'application/problem+json' && + resp.error + ) { + return new HTTPError( + `Request failed (${resp.response.url}) [${resp.response.status}]: ${resp.error.detail}`, + resp.error.type, + resp.error.title, + resp.error.status ?? resp.response.status, + resp.response.url, + resp.error, + ) + } + + return new HTTPError( + `Request failed (${resp.response.url}) [${resp.response.status}]: ${resp.response.statusText}`, + resp.response.statusText, + resp.response.statusText, + resp.response.status, + resp.response.url, + ) + } + + getField(key: string) { + return this.__raw?.[key] + } +} + +/** + * Check if an error is an HTTPError + * @param error - The error to check + * @returns Whether the error is an HTTPError + */ +export function isHTTPError(error: unknown): error is HTTPError { + return error instanceof HTTPError +} diff --git a/api/client/javascript/src/client/customers.ts b/api/client/javascript/src/client/customers.ts new file mode 100644 index 0000000000000000000000000000000000000000..93632f6ebf126346d01745f92d99c254bf75fb63 --- /dev/null +++ b/api/client/javascript/src/client/customers.ts @@ -0,0 +1,672 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + CreateStripeCustomerPortalSessionParams, + CustomerAppData, + CustomerCreate, + CustomerReplaceUpdate, + operations, + paths, + StripeCustomerAppDataBase, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Customers + * Manage customer subscription lifecycles and plan assignments. + */ +export class Customers { + public apps: CustomerApps + public entitlementsV1: CustomerEntitlements + public entitlements: CustomerEntitlementsV2 + public stripe: CustomerStripe + + constructor(private client: Client) { + this.apps = new CustomerApps(client) + this.entitlementsV1 = new CustomerEntitlements(client) + this.entitlements = new CustomerEntitlementsV2(client) + this.stripe = new CustomerStripe(client) + } + + /** + * Create a customer + * @param customer - The customer to create + * @param signal - An optional abort signal + * @returns The created customer + */ + public async create(customer: CustomerCreate, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/customers', { + body: customer, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a customer by ID + * @param customerIdOrKey - The ID or Key of the customer + * @param signal - An optional abort signal + * @returns The customer + */ + public async get( + customerIdOrKey: operations['getCustomer']['parameters']['path']['customerIdOrKey'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/customers/{customerIdOrKey}', { + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update a customer + * @param customerIdOrKey - The ID or Key of the customer + * @param customer - The customer to update + * @param signal - An optional abort signal + * @returns The updated customer + */ + public async update( + customerIdOrKey: operations['updateCustomer']['parameters']['path']['customerIdOrKey'], + customer: CustomerReplaceUpdate, + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/customers/{customerIdOrKey}', { + body: customer, + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a customer + * @param customerIdOrKey - The ID or Key of the customer + * @param signal - An optional abort signal + * @returns The deleted customer + */ + public async delete( + customerIdOrKey: operations['deleteCustomer']['parameters']['path']['customerIdOrKey'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/customers/{customerIdOrKey}', + { + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List customers + * @param signal - An optional abort signal + * @returns The list of customers + */ + public async list( + query?: operations['listCustomers']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/customers', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get customer access + * @param customerIdOrKey - The ID or Key of the customer + * @param options - Optional request options + * @returns The customer access information + */ + public async getAccess( + customerIdOrKey: operations['getCustomerAccess']['parameters']['path']['customerIdOrKey'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/customers/{customerIdOrKey}/access', + { + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List customer subscriptions + * @param customerIdOrKey - The ID or key of the customer + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The list of customer subscriptions + */ + public async listSubscriptions( + customerIdOrKey: operations['listCustomerSubscriptions']['parameters']['path']['customerIdOrKey'], + query?: operations['listCustomerSubscriptions']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/customers/{customerIdOrKey}/subscriptions', + { + params: { path: { customerIdOrKey }, query }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Customer Apps + * Manage customer apps. + */ +export class CustomerApps { + constructor(private client: Client) {} + + /** + * Upsert customer app data + * @param customerIdOrKey - The ID or Key of the customer + * @param appData - The app data to upsert + * @param signal - An optional abort signal + * @returns The upserted app data + */ + public async upsert( + customerIdOrKey: operations['upsertCustomerAppData']['parameters']['path']['customerIdOrKey'], + appData: CustomerAppData[], + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v1/customers/{customerIdOrKey}/apps', + { + body: appData, + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List customer app data + * @param customerIdOrKey - The ID or key of the customer + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The list of customer app data + */ + public async list( + customerIdOrKey: operations['listCustomerAppData']['parameters']['path']['customerIdOrKey'], + query?: operations['listCustomerAppData']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/customers/{customerIdOrKey}/apps', + { + params: { + path: { customerIdOrKey }, + query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Delete customer app data + * @param customerIdOrKey - The ID or key of the customer + * @param appId - The ID of the app + * @param signal - An optional abort signal + * @returns The deleted customer app data + */ + public async delete( + customerIdOrKey: operations['deleteCustomerAppData']['parameters']['path']['customerIdOrKey'], + appId: operations['deleteCustomerAppData']['parameters']['path']['appId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/customers/{customerIdOrKey}/apps/{appId}', + { + params: { path: { appId, customerIdOrKey } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Customer Stripe + * Manage customer Stripe data. + */ +export class CustomerStripe { + constructor(private client: Client) {} + + /** + * Upsert customer stripe app data + * @param customerIdOrKey - The ID or Key of the customer + * @param appData - The app data to upsert + * @param signal - An optional abort signal + * @returns The upserted customer stripe app data + */ + public async upsert( + customerIdOrKey: operations['upsertCustomerStripeAppData']['parameters']['path']['customerIdOrKey'], + stripeAppData: StripeCustomerAppDataBase, + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v1/customers/{customerIdOrKey}/stripe', + { + body: stripeAppData, + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get customer stripe app data + * @param customerIdOrKey - The ID or key of the customer + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The customer stripe app data + */ + public async get( + customerIdOrKey: operations['getCustomerStripeAppData']['parameters']['path']['customerIdOrKey'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/customers/{customerIdOrKey}/stripe', + { + params: { + path: { customerIdOrKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Create a Stripe customer portal session + * @param customerIdOrKey - The ID or Key of the customer + * @param params - The parameters for creating a Stripe customer portal session + * @param signal - An optional abort signal + * @returns The Stripe customer portal session + */ + public async createPortalSession( + customerIdOrKey: operations['createCustomerStripePortalSession']['parameters']['path']['customerIdOrKey'], + params: CreateStripeCustomerPortalSessionParams, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/customers/{customerIdOrKey}/stripe/portal', + { + body: params, + params: { + path: { + customerIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Customer Entitlements + */ +export class CustomerEntitlements { + constructor(private client: Client) {} + + /** + * Get the value of an entitlement for a customer + * @param customerIdOrKey - The ID or Key of the customer + * @param featureKey - The key of the feature + * @param signal - An optional abort signal + * @returns The value of the entitlement + */ + public async value( + customerIdOrKey: operations['getCustomerEntitlementValue']['parameters']['path']['customerIdOrKey'], + featureKey: operations['getCustomerEntitlementValue']['parameters']['path']['featureKey'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value', + { + params: { path: { customerIdOrKey, featureKey } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Customer Entitlements V2 + */ +export class CustomerEntitlementsV2 { + constructor(private client: Client) {} + + /** + * List all entitlements for a customer + * @param customerIdOrKey - The ID or Key of the customer + * @param options - Request options including query parameters + * @returns List of customer entitlements + */ + public async list( + customerIdOrKey: operations['listCustomerEntitlementsV2']['parameters']['path']['customerIdOrKey'], + options?: RequestOptions & { + query?: operations['listCustomerEntitlementsV2']['parameters']['query'] + }, + ) { + const resp = await this.client.GET( + '/api/v2/customers/{customerIdOrKey}/entitlements', + { + params: { + path: { customerIdOrKey }, + query: options?.query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Create a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlement - The entitlement data to create + * @param options - Request options + * @returns The created entitlement + */ + public async create( + customerIdOrKey: operations['createCustomerEntitlementV2']['parameters']['path']['customerIdOrKey'], + entitlement: operations['createCustomerEntitlementV2']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v2/customers/{customerIdOrKey}/entitlements', + { + body: entitlement, + params: { + path: { customerIdOrKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get a specific customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param options - Request options + * @returns The entitlement + */ + public async get( + customerIdOrKey: operations['getCustomerEntitlementV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['getCustomerEntitlementV2']['parameters']['path']['entitlementIdOrFeatureKey'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}', + { + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Delete a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param options - Request options + * @returns The deletion response + */ + public async delete( + customerIdOrKey: operations['deleteCustomerEntitlementV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['deleteCustomerEntitlementV2']['parameters']['path']['entitlementIdOrFeatureKey'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}', + { + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Override a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param entitlement - The new entitlement data + * @param options - Request options + * @returns The overridden entitlement + */ + public async override( + customerIdOrKey: operations['overrideCustomerEntitlementV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['overrideCustomerEntitlementV2']['parameters']['path']['entitlementIdOrFeatureKey'], + entitlement: operations['overrideCustomerEntitlementV2']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override', + { + body: entitlement, + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List grants for a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param options - Request options including query parameters + * @returns List of entitlement grants + */ + public async listGrants( + customerIdOrKey: operations['listCustomerEntitlementGrantsV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['listCustomerEntitlementGrantsV2']['parameters']['path']['entitlementIdOrFeatureKey'], + options?: RequestOptions & { + query?: operations['listCustomerEntitlementGrantsV2']['parameters']['query'] + }, + ) { + const resp = await this.client.GET( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants', + { + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + query: options?.query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Create a grant for a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param grant - The grant data to create + * @param options - Request options + * @returns The created grant + */ + public async createGrant( + customerIdOrKey: operations['createCustomerEntitlementGrantV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['createCustomerEntitlementGrantV2']['parameters']['path']['entitlementIdOrFeatureKey'], + grant: operations['createCustomerEntitlementGrantV2']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants', + { + body: grant, + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get the value of a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param options - Request options including query parameters + * @returns The entitlement value + */ + public async value( + customerIdOrKey: operations['getCustomerEntitlementValueV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['getCustomerEntitlementValueV2']['parameters']['path']['entitlementIdOrFeatureKey'], + options?: RequestOptions & { + query?: operations['getCustomerEntitlementValueV2']['parameters']['query'] + }, + ) { + const resp = await this.client.GET( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value', + { + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + query: options?.query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get the history of a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param windowSize - The window size for the history + * @param options - Request options including query parameters + * @returns The entitlement history + */ + public async history( + customerIdOrKey: operations['getCustomerEntitlementHistoryV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['getCustomerEntitlementHistoryV2']['parameters']['path']['entitlementIdOrFeatureKey'], + windowSize: operations['getCustomerEntitlementHistoryV2']['parameters']['query']['windowSize'], + options?: RequestOptions & { + query?: Omit< + operations['getCustomerEntitlementHistoryV2']['parameters']['query'], + 'windowSize' + > + }, + ) { + const resp = await this.client.GET( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history', + { + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + query: { + windowSize, + ...options?.query, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Reset the usage of a customer entitlement + * @param customerIdOrKey - The ID or Key of the customer + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param reset - The reset data + * @param options - Request options + * @returns The reset response + */ + public async resetUsage( + customerIdOrKey: operations['resetCustomerEntitlementUsageV2']['parameters']['path']['customerIdOrKey'], + entitlementIdOrFeatureKey: operations['resetCustomerEntitlementUsageV2']['parameters']['path']['entitlementIdOrFeatureKey'], + reset: operations['resetCustomerEntitlementUsageV2']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset', + { + body: reset, + params: { + path: { customerIdOrKey, entitlementIdOrFeatureKey }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/debug.ts b/api/client/javascript/src/client/debug.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b9712616e850faf1f3a0b159225aca4b312d8f9 --- /dev/null +++ b/api/client/javascript/src/client/debug.ts @@ -0,0 +1,25 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { paths } from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Debug utilities for OpenMeter + */ +export class Debug { + constructor(private client: Client) {} + + /** + * Get event metrics + * @description Returns debug metrics (in OpenMetrics format) like the number of ingested events since mindnight UTC. + * @param options - The request options + * @returns The debug metrics + */ + public async getMetrics(options?: RequestOptions) { + const resp = await this.client.GET('/api/v1/debug/metrics', { + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/entitlements.ts b/api/client/javascript/src/client/entitlements.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d71bf5aa31c07f276a2c144576995dd7237df06 --- /dev/null +++ b/api/client/javascript/src/client/entitlements.ts @@ -0,0 +1,493 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + Entitlement, + EntitlementCreateInputs, + EntitlementGrantCreateInput, + operations, + paths, + ResetEntitlementUsageInput, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Entitlements + * @description With Entitlements, you can define and enforce usage limits, implement quota-based pricing, and manage access to features in your application. + */ +export class Entitlements { + public grants: Grants + + constructor(private client: Client) { + this.grants = new Grants(client) + } + + /** + * Create an entitlement + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given subject can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlement - The entitlement to create + * @param signal - An optional abort signal + * @returns The created entitlement + */ + public async create( + subjectIdOrKey: operations['createEntitlement']['parameters']['path']['subjectIdOrKey'], + entitlement: EntitlementCreateInputs, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subjects/{subjectIdOrKey}/entitlements', + { + body: entitlement, + params: { + path: { + subjectIdOrKey: subjectIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get an entitlement by ID + * + * @param id - The ID of the entitlement + * @param signal - An optional abort signal + * @returns The entitlement + */ + public async get( + id: operations['getEntitlement']['parameters']['path']['entitlementId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/entitlements/{entitlementId}', { + params: { + path: { + entitlementId: id, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List entitlements + * + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The entitlements + */ + public async list( + query?: Omit< + operations['listEntitlements']['parameters']['query'], + 'page' | 'pageSize' + >, + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/entitlements', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) as Entitlement[] + } + + /** + * Delete an entitlement + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementId - The ID of the entitlement + * @param signal - An optional abort signal + * @returns The deleted entitlement + */ + public async delete( + subjectIdOrKey: operations['deleteEntitlement']['parameters']['path']['subjectIdOrKey'], + entitlementId: operations['deleteEntitlement']['parameters']['path']['entitlementId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}', + { + params: { + path: { + entitlementId, + subjectIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get the value of an entitlement to check access + * All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The entitlement value + */ + public async value( + subjectIdOrKey: operations['getEntitlementValue']['parameters']['path']['subjectIdOrKey'], + entitlementIdOrFeatureKey: operations['getEntitlementValue']['parameters']['path']['entitlementIdOrFeatureKey'], + query?: operations['getEntitlementValue']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value', + { + params: { + path: { + entitlementIdOrFeatureKey, + subjectIdOrKey, + }, + query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get the history of an entitlement + * Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementId - The ID of the entitlement + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The history of the entitlement + */ + public async history( + subjectIdOrKey: operations['getEntitlementHistory']['parameters']['path']['subjectIdOrKey'], + entitlementId: operations['getEntitlementHistory']['parameters']['path']['entitlementId'], + query: operations['getEntitlementHistory']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history', + { + params: { + path: { + entitlementId, + subjectIdOrKey, + }, + query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Override an entitlement + * This is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param override - The override to create + * @param signal - An optional abort signal + * @returns The overridden entitlement + */ + public async override( + subjectIdOrKey: operations['overrideEntitlement']['parameters']['path']['subjectIdOrKey'], + entitlementIdOrFeatureKey: operations['overrideEntitlement']['parameters']['path']['entitlementIdOrFeatureKey'], + override: EntitlementCreateInputs, + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override', + { + body: override, + params: { + path: { + entitlementIdOrFeatureKey, + subjectIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Reset entitlement usage + * - Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the subjects billing period to enforce usage based on their subscription. + * - Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementId - The ID of the entitlement + * @param body - The body of the request + * @param signal - An optional abort signal + * @returns The reset entitlement + */ + public async reset( + subjectIdOrKey: operations['resetEntitlementUsage']['parameters']['path']['subjectIdOrKey'], + entitlementId: operations['resetEntitlementUsage']['parameters']['path']['entitlementId'], + body: ResetEntitlementUsageInput, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset', + { + body, + params: { + path: { + entitlementId, + subjectIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +export class Grants { + constructor(private client: Client) {} + + /** + * Grant usage to a subject for an entitlement + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param grant - The grant to create + * @param signal - An optional abort signal + * @returns The created grant + */ + public async create( + subjectIdOrKey: operations['createGrant']['parameters']['path']['subjectIdOrKey'], + entitlementIdOrFeatureKey: operations['createGrant']['parameters']['path']['entitlementIdOrFeatureKey'], + grant: EntitlementGrantCreateInput, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants', + { + body: grant, + params: { + path: { + entitlementIdOrFeatureKey, + subjectIdOrKey, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List grants for an entitlement + * + * @param subjectIdOrKey - The ID or key of the subject + * @param entitlementIdOrFeatureKey - The ID or feature key of the entitlement + * @param signal - An optional abort signal + * @returns The grants + */ + public async list( + subjectIdOrKey: operations['listEntitlementGrants']['parameters']['path']['subjectIdOrKey'], + entitlementIdOrFeatureKey: operations['listEntitlementGrants']['parameters']['path']['entitlementIdOrFeatureKey'], + query?: operations['listEntitlementGrants']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants', + { + params: { + path: { + entitlementIdOrFeatureKey, + subjectIdOrKey, + }, + query, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List all grants + * List all grants for all the subjects and entitlements. + * + * @param query - The query parameters + * @param options - The request options + * @returns The grants + */ + public async listAll( + query?: operations['listGrants']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/grants', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Void a grant + * Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. + * Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed + * to the grant will remain, but future usage cannot be burnt down from the grant. + * + * @param grantId - The ID of the grant + * @param options - The request options + * @returns The voided grant + */ + public async void( + grantId: operations['voidGrant']['parameters']['path']['grantId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/grants/{grantId}', { + params: { + path: { + grantId, + }, + }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Entitlements V2 + * @description With Entitlements, you can define and enforce usage limits, implement quota-based pricing, and manage access to features in your application. + */ +export class EntitlementsV2 { + public grants: GrantsV2 + + constructor(private client: Client) { + this.grants = new GrantsV2(client) + } + + /** + * List all entitlements for all customers and features + * @description This endpoint is intended for administrative purposes only. + * To fetch entitlements of a specific customer, use the customer entitlements endpoint. + * @param options - Request options including query parameters + * @returns List of entitlements + */ + public async list( + options?: RequestOptions & { + query?: operations['listEntitlementsV2']['parameters']['query'] + }, + ) { + const resp = await this.client.GET('/api/v2/entitlements', { + params: { + query: options?.query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get entitlement by ID + * @param entitlementId - The ID of the entitlement + * @param options - Request options + * @returns The entitlement + */ + public async get( + entitlementId: operations['getEntitlementByIdV2']['parameters']['path']['entitlementId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v2/entitlements/{entitlementId}', { + params: { + path: { entitlementId }, + }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Grants + */ +export class GrantsV2 { + constructor(private client: Client) {} + + /** + * List all grants for all customers and entitlements + * @description This endpoint is intended for administrative purposes only. + * To fetch grants of a specific entitlement, use the customer entitlements grants endpoint. + * @param options - Request options including query parameters + * @returns List of grants + */ + public async list( + options?: RequestOptions & { + query?: operations['listGrantsV2']['parameters']['query'] + }, + ) { + const resp = await this.client.GET('/api/v2/grants', { + params: { + query: options?.query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Void a grant (legacy method using V1 endpoint) + * @description Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. + * Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed + * to the grant will remain, but future usage cannot be burnt down from the grant. + * @param grantId - The ID of the grant + * @param options - Request options + * @returns The voided grant + * @deprecated This method uses the legacy V1 endpoint. Consider using customer-specific grant operations instead. + */ + public async void( + grantId: operations['voidGrant']['parameters']['path']['grantId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/grants/{grantId}', { + params: { + path: { + grantId, + }, + }, + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/events.spec.ts b/api/client/javascript/src/client/events.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb916e9818c237e01ed8fa1b36ec954efda40d03 --- /dev/null +++ b/api/client/javascript/src/client/events.spec.ts @@ -0,0 +1,110 @@ +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import type { Event } from './index.js' +import { OpenMeter } from './index.js' + +interface Context { + baseUrl: string + client: OpenMeter +} + +describe('Events', () => { + beforeEach((ctx) => { + fetchMock.mockReset() + const baseUrl = 'http://openmeter-mock.local' + const client = new OpenMeter({ + baseUrl, + fetch: fetchMock.fetchHandler, + }) + + ctx.baseUrl = baseUrl + ctx.client = client + }) + + it('ingest (POST /api/v1/events)', async ({ + baseUrl, + client, + task, + }) => { + const route = `${baseUrl}/api/v1/events` + const event: Event = { + data: { + tokens: 100, + }, + id: '5c10fade-1c9e-4d6c-8275-c52c36731d3c', + subject: 'customer_id', + time: new Date(), + type: 'prompt', + } + + fetchMock.route( + route, + { + status: 200, + }, + { + body: [ + { + ...event, + source: '@openmeter/sdk', + specversion: '1.0', + subject: 'customer_id', + time: event.time?.toISOString(), + type: 'prompt', + }, + ], + headers: { + 'Content-Type': 'application/cloudevents-batch+json', + }, + method: 'POST', + name: task.name, + }, + ) + const resp = await client.events.ingest(event) + expect(resp).toBeUndefined() + expect(fetchMock.callHistory.done(task.name)).toBeTruthy() + }) + + it('list (GET /api/v1/events)', async ({ + baseUrl, + client, + task, + }) => { + const query = { + from: new Date(), + hasError: false, + id: '5c10fade-1c9e-4d6c-8275-c52c36731d3c', + ingestedAtFrom: new Date(), + ingestedAtTo: new Date(), + limit: 10, + subject: 'customer_id', + to: new Date(), + } + const route = `${baseUrl}/api/v1/events` + const respBody = [] + fetchMock.route( + route, + { + body: respBody, + status: 200, + }, + { + method: 'GET', + name: task.name, + query: { + from: query.from.toISOString(), + hasError: query.hasError.toString(), + id: query.id, + ingestedAtFrom: query.ingestedAtFrom.toISOString(), + ingestedAtTo: query.ingestedAtTo.toISOString(), + limit: query.limit.toString(), + subject: query.subject, + to: query.to.toISOString(), + }, + }, + ) + const resp = await client.events.list(query) + expect(resp).toEqual(respBody) + expect(fetchMock.callHistory.done(task.name)).toBeTruthy() + }) +}) diff --git a/api/client/javascript/src/client/events.ts b/api/client/javascript/src/client/events.ts new file mode 100644 index 0000000000000000000000000000000000000000..731909359c6b70a5d480342ffe78ce129b077109 --- /dev/null +++ b/api/client/javascript/src/client/events.ts @@ -0,0 +1,131 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { Event, operations, paths } from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Events are used to track usage of your product or service. + * Events are processed asynchronously by the meters, so they may not be immediately available for querying. + */ +export class Events { + constructor(private client: Client) {} + + /** + * Ingests an event or batch of events + * @param events - The events to ingest + * @param signal - An optional abort signal + * @returns The ingested events + */ + public async ingest(events: Event | Event[], options?: RequestOptions) { + const body = await Promise.all( + (Array.isArray(events) ? events : [events]).map(setDefaultsForEvent), + ) + + const resp = await this.client.POST('/api/v1/events', { + body, + headers: { + 'Content-Type': 'application/cloudevents-batch+json', + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List events + * @param params - The query parameters + * @param options - Optional request options + * @returns The events + */ + public async list( + params?: operations['listEvents']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/events', { + params: { query: params }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List events (V2) + * @description List ingested events with advanced filtering and cursor pagination. + * @param params - The query parameters + * @param options - Optional request options + * @returns The events + */ + public async listV2( + params?: operations['listEventsV2']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v2/events', { + params: { query: params }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Sets the defaults for an event + * @param ev - The event to set the defaults for + * @returns The event with the defaults set + */ +export async function setDefaultsForEvent(ev: Event): Promise { + return { + ...ev, + id: ev.id ?? (await generateId()), + source: ev.source ?? '@openmeter/sdk', + specversion: ev.specversion ?? '1.0', + time: ev.time ?? new Date(), + } +} + +let _randomUUID: (() => string) | undefined + +// One-off attempt to load node:crypto and capture randomUUID (if present) +async function loadUUIDProvider() { + if (_randomUUID !== undefined) { + // already tried + return _randomUUID + } + + try { + const c = await import('node:crypto') + if (typeof c.randomUUID === 'function') { + // available + _randomUUID = c.randomUUID.bind(c) + } + } catch { + // not-available + } + + return _randomUUID +} + +/** + * Generates a random ID + * @returns A random ID + */ +async function generateId() { + const randomUUID = await loadUUIDProvider() + if (randomUUID) { + return randomUUID() + } + + // Fallback to semi-random ID + const bytes = new Uint8Array(16) + for (let i = 0; i < 16; i++) { + bytes[i] = (Math.random() * 256) | 0 + } + + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + + const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('') + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` +} diff --git a/api/client/javascript/src/client/features.ts b/api/client/javascript/src/client/features.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e9be95ad8e7199d0b90f37d79ddba02fcdc174d --- /dev/null +++ b/api/client/javascript/src/client/features.ts @@ -0,0 +1,99 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + Feature, + FeatureCreateInputs, + operations, + paths, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Features + * @description Features are the building blocks of your application. They represent the capabilities or services that your application offers. + */ +export class Features { + constructor(private client: Client) {} + + /** + * Create a feature + * @param feature - The feature to create + * @param signal - An optional abort signal + * @returns The created feature + */ + public async create(feature: FeatureCreateInputs, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/features', { + body: feature, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a feature by ID + * @param id - The ID of the feature + * @param signal - An optional abort signal + * @returns The feature + */ + public async get( + id: operations['getFeature']['parameters']['path']['featureId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/features/{featureId}', { + params: { + path: { + featureId: id, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List features + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The features + */ + public async list( + query?: Omit< + operations['listFeatures']['parameters']['query'], + 'page' | 'pageSize' + >, + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/features', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) as Feature[] + } + + /** + * Delete a feature by ID + * @param id - The ID of the feature + * @param signal - An optional abort signal + * @returns The deleted feature + */ + public async delete( + id: operations['deleteFeature']['parameters']['path']['featureId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/features/{featureId}', { + params: { + path: { + featureId: id, + }, + }, + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/index.ts b/api/client/javascript/src/client/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9de2bbd9ec152cf3f0e73ff01b7cd230f0e0c5c --- /dev/null +++ b/api/client/javascript/src/client/index.ts @@ -0,0 +1,107 @@ +import createClient, { + type Client, + type ClientOptions, + createQuerySerializer, +} from 'openapi-fetch' +import { Addons } from './addons.js' +import { Apps } from './apps.js' +import { Billing } from './billing.js' +import { Customers } from './customers.js' +import { Debug } from './debug.js' +import { Entitlements, EntitlementsV2 } from './entitlements.js' +import { Events } from './events.js' +import { Features } from './features.js' +import { Info } from './info.js' +import { Meters } from './meters.js' +import { Notifications } from './notifications.js' +import { Plans } from './plans.js' +import { Portal } from './portal.js' +import type { paths } from './schemas.js' +import { Subjects } from './subjects.js' +import { SubscriptionAddons } from './subscription-addons.js' +import { Subscriptions } from './subscriptions.js' +import { encodeDates } from './utils.js' + +export * from './common.js' +export * from './schemas.js' + +/** + * OpenMeter Config + */ +export type Config = Pick< + ClientOptions, + 'baseUrl' | 'headers' | 'fetch' | 'Request' | 'requestInitExt' +> & + ( + | { + apiKey?: string + } + | { + baseUrl: 'https://openmeter.cloud' + apiKey: string + } + ) + +/** + * OpenMeter Client + */ +export class OpenMeter { + public client: Client + + public addons: Addons + public apps: Apps + public billing: Billing + public customers: Customers + public debug: Debug + public entitlementsV1: Entitlements + public entitlements: EntitlementsV2 + public events: Events + public features: Features + public info: Info + public meters: Meters + public notifications: Notifications + public plans: Plans + public portal: Portal + public subjects: Subjects + public subscriptionAddons: SubscriptionAddons + public subscriptions: Subscriptions + + constructor(public config: Config) { + this.client = createClient({ + ...config, + headers: { + ...config.headers, + Authorization: config.apiKey ? `Bearer ${config.apiKey}` : undefined, + }, + querySerializer: (q) => + createQuerySerializer({ + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, + })(encodeDates(q)), + }) + + this.addons = new Addons(this.client) + this.apps = new Apps(this.client) + this.billing = new Billing(this.client) + this.customers = new Customers(this.client) + this.debug = new Debug(this.client) + this.entitlementsV1 = new Entitlements(this.client) + this.entitlements = new EntitlementsV2(this.client) + this.events = new Events(this.client) + this.features = new Features(this.client) + this.info = new Info(this.client) + this.meters = new Meters(this.client) + this.notifications = new Notifications(this.client) + this.plans = new Plans(this.client) + this.portal = new Portal(this.client) + this.subjects = new Subjects(this.client) + this.subscriptionAddons = new SubscriptionAddons(this.client) + this.subscriptions = new Subscriptions(this.client) + } +} diff --git a/api/client/javascript/src/client/info.ts b/api/client/javascript/src/client/info.ts new file mode 100644 index 0000000000000000000000000000000000000000..008607fb2fea9969d0e46fc6082f534a1cc530da --- /dev/null +++ b/api/client/javascript/src/client/info.ts @@ -0,0 +1,45 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { operations, paths } from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Info utilities for OpenMeter + */ +export class Info { + constructor(private client: Client) {} + + /** + * List supported currencies + * @description List all supported currencies. + * @param options - The request options + * @returns The supported currencies + */ + public async listCurrencies(options?: RequestOptions) { + const resp = await this.client.GET('/api/v1/info/currencies', { + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get progress + * @param id - The ID of the progress to get + * @param options - The request options + * @returns The progress + */ + public async getProgress( + id: operations['getProgress']['parameters']['path']['id'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/info/progress/{id}', { + params: { + path: { id }, + }, + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/meters.ts b/api/client/javascript/src/client/meters.ts new file mode 100644 index 0000000000000000000000000000000000000000..95e6fdde21e061af7c0286542e23234787cc3e20 --- /dev/null +++ b/api/client/javascript/src/client/meters.ts @@ -0,0 +1,203 @@ +import type { Client } from "openapi-fetch"; +import type { RequestOptions } from "./common.js"; +import type { MeterCreate, operations, paths } from "./schemas.js"; +import { transformResponse } from "./utils.js"; + +/** + * Meters + * @description Meters are used to track and manage usage of your application. + */ +export class Meters { + constructor(private client: Client) {} + + /** + * Create a meter + * @param meter - The meter to create + * @param signal - An optional abort signal + * @returns The created meter + */ + public async create(meter: MeterCreate, options?: RequestOptions) { + const resp = await this.client.POST("/api/v1/meters", { + body: meter, + ...options, + }); + + return transformResponse(resp); + } + + /** + * Get a meter by ID or slug + * @param idOrSlug - The ID or slug of the meter + * @param signal - An optional abort signal + * @returns The meter + */ + public async get( + idOrSlug: operations["getMeter"]["parameters"]["path"]["meterIdOrSlug"], + options?: RequestOptions, + ) { + const resp = await this.client.GET("/api/v1/meters/{meterIdOrSlug}", { + params: { + path: { + meterIdOrSlug: idOrSlug, + }, + }, + ...options, + }); + + return transformResponse(resp); + } + + /** + * List meters + * @param signal - An optional abort signal + * @returns The meters + */ + public async list(options?: RequestOptions) { + const resp = await this.client.GET("/api/v1/meters", { + ...options, + }); + + return transformResponse(resp); + } + + /** + * Query usage data for a meter by ID or slug + * @param idOrSlug - The ID or slug of the meter + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The meter data + */ + public async query( + idOrSlug: operations["queryMeter"]["parameters"]["path"]["meterIdOrSlug"], + query?: operations["queryMeter"]["parameters"]["query"], + options?: RequestOptions, + ) { + const resp = await this.client.GET("/api/v1/meters/{meterIdOrSlug}/query", { + headers: { + Accept: "application/json", + }, + params: { + path: { + meterIdOrSlug: idOrSlug, + }, + query, + }, + ...options, + }); + + return transformResponse( + resp, + ) as operations["queryMeter"]["responses"]["200"]["content"]["application/json"]; + } + + /** + * Update a meter by ID or slug + * @param idOrSlug - The ID or slug of the meter + * @param meter - The meter update data + * @param options - Optional request options + * @returns The updated meter + */ + public async update( + idOrSlug: operations["updateMeter"]["parameters"]["path"]["meterIdOrSlug"], + meter: operations["updateMeter"]["requestBody"]["content"]["application/json"], + options?: RequestOptions, + ) { + const resp = await this.client.PUT("/api/v1/meters/{meterIdOrSlug}", { + body: meter, + params: { + path: { + meterIdOrSlug: idOrSlug, + }, + }, + ...options, + }); + + return transformResponse(resp); + } + + /** + * Delete a meter by ID or slug + * @param idOrSlug - The ID or slug of the meter + * @param signal - An optional abort signal + * @returns The deleted meter + */ + public async delete( + idOrSlug: operations["deleteMeter"]["parameters"]["path"]["meterIdOrSlug"], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE("/api/v1/meters/{meterIdOrSlug}", { + params: { + path: { + meterIdOrSlug: idOrSlug, + }, + }, + ...options, + }); + + return transformResponse(resp); + } + + /** + * List meter group-by values + * @description List all values for a specific group-by key in a meter. + * @param idOrSlug - The ID or slug of the meter + * @param groupByKey - The group-by key to list values for + * @param query - The query parameters + * @param options - Optional request options + * @returns The list of group-by values + */ + public async listGroupByValues( + idOrSlug: operations["listMeterGroupByValues"]["parameters"]["path"]["meterIdOrSlug"], + groupByKey: operations["listMeterGroupByValues"]["parameters"]["path"]["groupByKey"], + query?: operations["listMeterGroupByValues"]["parameters"]["query"], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + "/api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values", + { + params: { + path: { + groupByKey, + meterIdOrSlug: idOrSlug, + }, + query, + }, + ...options, + }, + ); + + return transformResponse(resp); + } + + /** + * Query usage data for a meter by ID or slug using POST + * @description Query meter using POST method. This is useful for complex queries that exceed URL length limits. + * @param idOrSlug - The ID or slug of the meter + * @param body - The query body parameters + * @param options - Optional request options + * @returns The meter data + */ + public async queryPost( + idOrSlug: operations["queryMeterPost"]["parameters"]["path"]["meterIdOrSlug"], + body: operations["queryMeterPost"]["requestBody"]["content"]["application/json"], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + "/api/v1/meters/{meterIdOrSlug}/query", + { + body, + headers: { + Accept: "application/json", + }, + params: { + path: { + meterIdOrSlug: idOrSlug, + }, + }, + ...options, + }, + ); + + return transformResponse(resp); + } +} diff --git a/api/client/javascript/src/client/notifications.ts b/api/client/javascript/src/client/notifications.ts new file mode 100644 index 0000000000000000000000000000000000000000..c54b61c65b4adbd354450438abae5015ab249e2e --- /dev/null +++ b/api/client/javascript/src/client/notifications.ts @@ -0,0 +1,349 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + NotificationChannel, + NotificationRuleCreateRequest, + operations, + paths, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Notifications + * @description Notifications provide automated triggers when specific entitlement balances and usage thresholds are reached, ensuring that your customers and sales teams are always informed. Notify customers and internal teams when specific conditions are met, like reaching 75%, 100%, and 150% of their monthly usage allowance. + */ +export class Notifications { + public channels: NotificationChannels + public rules: NotificationRules + public events: NotificationEvents + + constructor(private client: Client) { + this.channels = new NotificationChannels(this.client) + this.rules = new NotificationRules(this.client) + this.events = new NotificationEvents(this.client) + } +} + +/** + * Notification Channels + * @description Notification channels are the destinations for notifications. + */ +export class NotificationChannels { + constructor(private client: Client) {} + + /** + * Create a notification channel + * @param notification - The notification to create + * @param signal - An optional abort signal + * @returns The created notification + */ + public async create( + notification: NotificationChannel, + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/notification/channels', { + body: notification, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a notification channel by ID + * @param id - The ID of the notification channel + * @param signal - An optional abort signal + * @returns The notification channel + */ + public async get( + id: operations['getNotificationChannel']['parameters']['path']['channelId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/notification/channels/{channelId}', + { + params: { + path: { + channelId: id, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Update a notification channel + * @param id - The ID of the notification channel + * @param notification - The notification to update + * @param signal - An optional abort signal + * @returns The updated notification + */ + public async update( + id: operations['updateNotificationChannel']['parameters']['path']['channelId'], + notification: NotificationChannel, + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v1/notification/channels/{channelId}', + { + body: notification, + params: { + path: { + channelId: id, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List notification channels + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The list of notification channels + */ + public async list( + query?: operations['listNotificationChannels']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/notification/channels', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a notification channel + * @param id - The ID of the notification channel + * @param signal - An optional abort signal + * @returns The deleted notification + */ + public async delete( + id: operations['deleteNotificationChannel']['parameters']['path']['channelId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/notification/channels/{channelId}', + { + params: { + path: { + channelId: id, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Notification Rules + * @description Notification rules are the conditions that trigger notifications. + */ +export class NotificationRules { + constructor(private client: Client) {} + + /** + * Create a notification rule + * @param rule - The rule to create + * @param signal - An optional abort signal + * @returns The created rule + */ + public async create( + rule: NotificationRuleCreateRequest, + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/notification/rules', { + body: rule, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a notification rule by ID + * @param id - The ID of the notification rule + * @param signal - An optional abort signal + * @returns The notification rule + */ + public async get( + id: operations['getNotificationRule']['parameters']['path']['ruleId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/notification/rules/{ruleId}', { + params: { + path: { + ruleId: id, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update a notification rule + * @param id - The ID of the notification rule + * @param rule - The rule to update + * @param signal - An optional abort signal + * @returns The updated rule + */ + public async update( + id: operations['updateNotificationRule']['parameters']['path']['ruleId'], + rule: NotificationRuleCreateRequest, + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/notification/rules/{ruleId}', { + body: rule, + params: { + path: { + ruleId: id, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List notification rules + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The list of notification rules + */ + public async list( + query?: operations['listNotificationRules']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/notification/rules', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a notification rule + * @param id - The ID of the notification rule + * @param signal - An optional abort signal + * @returns The deleted notification + */ + public async delete( + id: operations['deleteNotificationRule']['parameters']['path']['ruleId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/notification/rules/{ruleId}', + { + params: { + path: { + ruleId: id, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} + +/** + * Notification Events + * @description Notification events are the events that trigger notifications. + */ +export class NotificationEvents { + constructor(private client: Client) {} + + /** + * Get a notification event by ID + * @param id - The ID of the notification event + * @param signal - An optional abort signal + * @returns The notification event + */ + public async get( + id: operations['getNotificationEvent']['parameters']['path']['eventId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/notification/events/{eventId}', + { + params: { + path: { + eventId: id, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List notification events + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The list of notification events + */ + public async list( + query?: operations['listNotificationEvents']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/notification/events', { + params: { + query, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Resend a notification event + * @description Resend a notification event that has already been sent. + * @param id - The ID of the notification event + * @param channels - The channels to resend the notification event to, if not provided it will resend to all channels + * @param signal - An optional abort signal + * @returns The resent notification event + */ + public async resend( + id: operations['resendNotificationEvent']['parameters']['path']['eventId'], + body: operations['resendNotificationEvent']['requestBody']['content']['application/json'] = {}, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/notification/events/{eventId}/resend', + { + body, + params: { + path: { + eventId: id, + }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/plans.ts b/api/client/javascript/src/client/plans.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8e3c055d0658be2ed7379b85d3f0a1bfabf2101 --- /dev/null +++ b/api/client/javascript/src/client/plans.ts @@ -0,0 +1,278 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + operations, + PlanCreate, + PlanReplaceUpdate, + paths, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Plans + * Manage customer subscription plans and addon assignments. + */ +export class Plans { + public addons: PlanAddons + + constructor(private client: Client) { + this.addons = new PlanAddons(this.client) + } + + /** + * Create a plan + * @param plan - The plan to create + * @param options - Optional request options + * @returns The created plan + */ + public async create(plan: PlanCreate, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/plans', { + body: plan, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a plan by ID + * @param planId - The ID of the plan to retrieve + * @param params - Optional query parameters + * @param options - Optional request options + * @returns The plan + */ + public async get( + planId: operations['getPlan']['parameters']['path']['planId'], + params?: operations['getPlan']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/plans/{planId}', { + params: { + path: { planId }, + query: params, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List plans + * @param params - Optional parameters for listing plans + * @param options - Optional request options + * @returns A list of plans + */ + public async list( + params?: operations['listPlans']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/plans', { + params: { query: params }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Update a plan + * @param planId - The ID of the plan to update + * @param plan - The plan data to update + * @param options - Optional request options + * @returns The updated plan + */ + public async update( + planId: operations['updatePlan']['parameters']['path']['planId'], + plan: PlanReplaceUpdate, + options?: RequestOptions, + ) { + const resp = await this.client.PUT('/api/v1/plans/{planId}', { + body: plan, + params: { path: { planId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a plan by ID + * @param planId - The ID of the plan to delete + * @param options - Optional request options + * @returns void or standard error response structure + */ + public async delete( + planId: operations['deletePlan']['parameters']['path']['planId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/plans/{planId}', { + params: { path: { planId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Archive a plan + * @param planId - The ID of the plan to archive + * @param options - Optional request options + * @returns The archived plan + */ + public async archive( + planId: operations['archivePlan']['parameters']['path']['planId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/plans/{planId}/archive', { + params: { path: { planId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Publish a plan + * @param planId - The ID of the plan to publish + * @param options - Optional request options + * @returns The published plan + */ + public async publish( + planId: operations['publishPlan']['parameters']['path']['planId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/plans/{planId}/publish', { + params: { path: { planId } }, + ...options, + }) + + return transformResponse(resp) + } +} + +/** + * Plan Addons + * Manage addon assignments for plans. + */ +export class PlanAddons { + constructor(private client: Client) {} + + /** + * List plan addons + * @param planId - The ID of the plan + * @param params - Optional query parameters + * @param options - Optional request options + * @returns A list of plan addons + */ + public async list( + planId: operations['listPlanAddons']['parameters']['path']['planId'], + params?: operations['listPlanAddons']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/plans/{planId}/addons', { + params: { + path: { planId }, + query: params, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Create a plan addon + * @param planId - The ID of the plan + * @param planAddon - The plan addon to create + * @param options - Optional request options + * @returns The created plan addon + */ + public async create( + planId: operations['createPlanAddon']['parameters']['path']['planId'], + planAddon: operations['createPlanAddon']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/plans/{planId}/addons', { + body: planAddon, + params: { path: { planId } }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a plan addon by ID + * @param planId - The ID of the plan + * @param planAddonId - The ID of the plan addon + * @param options - Optional request options + * @returns The plan addon + */ + public async get( + planId: operations['getPlanAddon']['parameters']['path']['planId'], + planAddonId: operations['getPlanAddon']['parameters']['path']['planAddonId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/plans/{planId}/addons/{planAddonId}', + { + params: { + path: { planAddonId, planId }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Update a plan addon + * @param planId - The ID of the plan + * @param planAddonId - The ID of the plan addon to update + * @param planAddon - The plan addon data to update + * @param options - Optional request options + * @returns The updated plan addon + */ + public async update( + planId: operations['updatePlanAddon']['parameters']['path']['planId'], + planAddonId: operations['updatePlanAddon']['parameters']['path']['planAddonId'], + planAddon: operations['updatePlanAddon']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.PUT( + '/api/v1/plans/{planId}/addons/{planAddonId}', + { + body: planAddon, + params: { path: { planAddonId, planId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Delete a plan addon by ID + * @param planId - The ID of the plan + * @param planAddonId - The ID of the plan addon to delete + * @param options - Optional request options + * @returns void or standard error response structure + */ + public async delete( + planId: operations['deletePlanAddon']['parameters']['path']['planId'], + planAddonId: operations['deletePlanAddon']['parameters']['path']['planAddonId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/plans/{planId}/addons/{planAddonId}', + { + params: { path: { planAddonId, planId } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/portal.ts b/api/client/javascript/src/client/portal.ts new file mode 100644 index 0000000000000000000000000000000000000000..69b135d0831f1b93c3da2f9c23933dba9480caa0 --- /dev/null +++ b/api/client/javascript/src/client/portal.ts @@ -0,0 +1,63 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { operations, PortalToken, paths } from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Portal + * Manage portal tokens. + */ +export class Portal { + constructor(private client: Client) {} + + /** + * Create a consumer portal token + * @param request - The request body + * @param options - The request options + * @returns The portal token + */ + public async create(body: PortalToken, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/portal/tokens', { + body, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List consumer portal tokens + * @param query - The query parameters + * @param options - The request options + * @returns The portal tokens + */ + public async list( + query?: operations['listPortalTokens']['parameters']['query'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/portal/tokens', { + params: { query }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Invalidate consumer portal tokens + * @param body - The id or subject to invalidate + * @param options - The request options + * @returns The portal token + */ + public async invalidate( + body: operations['invalidatePortalTokens']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/portal/tokens/invalidate', { + body, + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/schemas.ts b/api/client/javascript/src/client/schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..7600f0aeea98f728efcb5f42ab6207d6a13aceb4 --- /dev/null +++ b/api/client/javascript/src/client/schemas.ts @@ -0,0 +1,28473 @@ +export interface paths { + '/api/v1/addons': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List add-ons + * @description List all add-ons. + */ + get: operations['listAddons'] + put?: never + /** + * Create an add-on + * @description Create a new add-on. + */ + post: operations['createAddon'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/addons/{addonId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get add-on + * @description Get add-on by id or key. The latest published version is returned if latter is used. + */ + get: operations['getAddon'] + /** + * Update add-on + * @description Update add-on by id. + */ + put: operations['updateAddon'] + post?: never + /** + * Delete add-on + * @description Soft delete add-on by id. + * + * Once a add-on is deleted it cannot be undeleted. + */ + delete: operations['deleteAddon'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/addons/{addonId}/archive': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Archive add-on version + * @description Archive a add-on version. + */ + post: operations['archiveAddon'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/addons/{addonId}/publish': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Publish add-on + * @description Publish a add-on version. + */ + post: operations['publishAddon'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List apps + * @description List apps. + */ + get: operations['listApps'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** Submit draft synchronization results */ + post: operations['appCustomInvoicingDraftSynchronized'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** Submit issuing synchronization results */ + post: operations['appCustomInvoicingIssuingSynchronized'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps/custom-invoicing/{invoiceId}/payment/status': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** Update payment status */ + post: operations['appCustomInvoicingUpdatePaymentStatus'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps/{id}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get app + * @description Get the app. + */ + get: operations['getApp'] + /** + * Update app + * @description Update an app. + */ + put: operations['updateApp'] + post?: never + /** + * Uninstall app + * @description Uninstall an app. + */ + delete: operations['uninstallApp'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps/{id}/stripe/api-key': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + /** + * Update Stripe API key + * @deprecated + * @description Update the Stripe API key. + * + * ⚠️ __Deprecated__: Use [`PUT /api/v1/apps/{id}`](#tag/apps/put/api/v1/apps/{id}) instead. + */ + put: operations['updateStripeAPIKey'] + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/apps/{id}/stripe/webhook': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Stripe webhook + * @description Handle stripe webhooks for apps. + */ + post: operations['appStripeWebhook'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/customers': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List customer overrides + * @description List customer overrides using the specified filters. + * + * The response will include the customer override values and the merged billing profile values. + * + * If the includeAllCustomers is set to true, the list contains all customers. This mode is + * useful for getting the current effective billing workflow settings for all users regardless + * if they have customer orverrides or not. + */ + get: operations['listBillingProfileCustomerOverrides'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/customers/{customerId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get a customer override + * @description Get a customer override by customer id. + * + * The response will include the customer override values and the merged billing profile values. + * + * If the customer override is not found, the default billing profile's values are returned. This behavior + * allows for getting a merged profile regardless of the customer override existence. + */ + get: operations['getBillingProfileCustomerOverride'] + /** + * Create a new or update a customer override + * @description The customer override can be used to pin a given customer to a billing profile + * different from the default one. + * + * This can be used to test the effect of different billing profiles before making them + * the default ones or have different workflow settings for example for enterprise customers. + */ + put: operations['upsertBillingProfileCustomerOverride'] + post?: never + /** + * Delete a customer override + * @description Delete a customer override by customer id. + * + * This will remove the customer override and the customer will be subject to the default + * billing profile's settings again. + */ + delete: operations['deleteBillingProfileCustomerOverride'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/customers/{customerId}/invoices/pending-lines': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Create pending line items + * @description Create a new pending line item (charge). + * + * This call is used to create a new pending line item for the customer if required a new + * gathering invoice will be created. + * + * A new invoice will be created if: + * - there is no invoice in gathering state + * - the currency of the line item doesn't match the currency of any invoices in gathering state + */ + post: operations['createPendingInvoiceLine'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/customers/{customerId}/invoices/simulate': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Simulate an invoice for a customer + * @description Simulate an invoice for a customer. + * + * This call will simulate an invoice for a customer based on the pending line items. + * + * The call will return the total amount of the invoice and the line items that will be included in the invoice. + */ + post: operations['simulateInvoice'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List invoices + * @description List invoices based on the specified filters. + * + * The expand option can be used to include additional information (besides the invoice header and totals) + * in the response. For example by adding the expand=lines option the invoice lines will be included in the response. + * + * Gathering invoices will always show the current usage calculated on the fly. + */ + get: operations['listInvoices'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/invoice': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Invoice a customer based on the pending line items + * @description Create a new invoice from the pending line items. + * + * This should be only called if for some reason we need to invoice a customer outside of the normal billing cycle. + * + * When creating an invoice, the pending line items will be marked as invoiced and the invoice will be created with the total amount of the pending items. + * + * New pending line items will be created for the period between now() and the next billing cycle's begining date for any metered item. + * + * The call can return multiple invoices if the pending line items are in different currencies. + */ + post: operations['invoicePendingLinesAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get an invoice + * @description Get an invoice by ID. + * + * Gathering invoices will always show the current usage calculated on the fly. + */ + get: operations['getInvoice'] + /** + * Update an invoice + * @description Update an invoice + * + * Only invoices in draft or earlier status can be updated. + */ + put: operations['updateInvoice'] + post?: never + /** + * Delete an invoice + * @description Delete an invoice + * + * Only invoices that are in the draft (or earlier) status can be deleted. + * + * Invoices that are post finalization can only be voided. + */ + delete: operations['deleteInvoice'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}/advance': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Advance the invoice's state to the next status + * @description Advance the invoice's state to the next status. + * + * The call doesn't "approve the invoice", it only advances the invoice to the next status if the transition would be automatic. + * + * The action can be called when the invoice's statusDetails' actions field contain the "advance" action. + */ + post: operations['advanceInvoiceAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}/approve': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Send the invoice to the customer + * @description Approve an invoice and start executing the payment workflow. + * + * This call instantly sends the invoice to the customer using the configured billing profile app. + * + * This call is valid in two invoice statuses: + * - `draft`: the invoice will be sent to the customer, the invluce state becomes issued + * - `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes issued + */ + post: operations['approveInvoiceAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}/retry': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Retry advancing the invoice after a failed attempt. + * @description Retry advancing the invoice after a failed attempt. + * + * The action can be called when the invoice's statusDetails' actions field contain the "retry" action. + */ + post: operations['retryInvoiceAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}/snapshot-quantities': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Snapshot quantities for usage based line items + * @description Snapshot quantities for usage based line items. + * + * This call will snapshot the quantities for all usage based line items in the invoice. + * + * This call is only valid in `draft.waiting_for_collection` status, where the collection period + * can be skipped using this action. + */ + post: operations['snapshotQuantitiesInvoiceAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}/taxes/recalculate': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Recalculate an invoice's tax amounts + * @description Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + * + * Note: charges might apply, depending on the tax provider. + */ + post: operations['recalculateInvoiceTaxAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/invoices/{invoiceId}/void': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Void an invoice + * @description Void an invoice + * + * Only invoices that have been alread issued can be voided. + * + * Voiding an invoice will mark it as voided, the user can specify how to handle the voided line items. + */ + post: operations['voidInvoiceAction'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/profiles': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List billing profiles + * @description List all billing profiles matching the specified filters. + * + * The expand option can be used to include additional information (besides the billing profile) + * in the response. For example by adding the expand=apps option the apps used by the billing profile + * will be included in the response. + */ + get: operations['listBillingProfiles'] + put?: never + /** + * Create a new billing profile + * @description Create a new billing profile + * + * Billing profiles are representations of a customer's billing information. Customer overrides + * can be applied to a billing profile to customize the billing behavior for a specific customer. + */ + post: operations['createBillingProfile'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/billing/profiles/{id}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get a billing profile + * @description Get a billing profile by id. + * + * The expand option can be used to include additional information (besides the billing profile) + * in the response. For example by adding the expand=apps option the apps used by the billing profile + * will be included in the response. + */ + get: operations['getBillingProfile'] + /** + * Update a billing profile + * @description Update a billing profile by id. + * + * The apps field cannot be updated directly, if an app change is desired a new + * profile should be created. + */ + put: operations['updateBillingProfile'] + post?: never + /** + * Delete a billing profile + * @description Delete a billing profile by id. + * + * Only such billing profiles can be deleted that are: + * - not the default one + * - not pinned to any customer using customer overrides + * - only have finalized invoices + */ + delete: operations['deleteBillingProfile'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List customers + * @description List customers. + */ + get: operations['listCustomers'] + put?: never + /** + * Create customer + * @description Create a new customer. + */ + post: operations['createCustomer'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer + * @description Get a customer by ID or key. + */ + get: operations['getCustomer'] + /** + * Update customer + * @description Update a customer by ID. + */ + put: operations['updateCustomer'] + post?: never + /** + * Delete customer + * @description Delete a customer by ID. + */ + delete: operations['deleteCustomer'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/access': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer access + * @description Get the overall access of a customer. + */ + get: operations['getCustomerAccess'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/apps': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List customer app data + * @description List customers app data. + */ + get: operations['listCustomerAppData'] + /** + * Upsert customer app data + * @description Upsert customer app data. + */ + put: operations['upsertCustomerAppData'] + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/apps/{appId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + post?: never + /** + * Delete customer app data + * @description Delete customer app data. + */ + delete: operations['deleteCustomerAppData'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer entitlement value + * @description Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + */ + get: operations['getCustomerEntitlementValue'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/stripe': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer stripe app data + * @description Get stripe app data for a customer. + * Only returns data if the customer billing profile is linked to a stripe app. + */ + get: operations['getCustomerStripeAppData'] + /** + * Upsert customer stripe app data + * @description Upsert stripe app data for a customer. + * Only updates data if the customer billing profile is linked to a stripe app. + */ + put: operations['upsertCustomerStripeAppData'] + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/stripe/portal': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Create Stripe customer portal session + * @description Create Stripe customer portal session. + * Only returns URL if the customer billing profile is linked to a stripe app and customer. + * + * Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + * change their billing address and access their invoice history. + */ + post: operations['createCustomerStripePortalSession'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/customers/{customerIdOrKey}/subscriptions': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List customer subscriptions + * @description Lists all subscriptions for a customer. + */ + get: operations['listCustomerSubscriptions'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/debug/metrics': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get event metrics + * @description Returns debug metrics (in OpenMetrics format) like the number of ingested events since mindnight UTC. + * + * The OpenMetrics Counter(s) reset every day at midnight UTC. + */ + get: operations['getDebugMetrics'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/entitlements': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List all entitlements + * @deprecated + * @description List all entitlements for all the subjects and features. This endpoint is intended for administrative purposes only. + * To fetch the entitlements of a specific subject please use the /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements`](#tag/entitlements/get/api/v2/entitlements) instead. + */ + get: operations['listEntitlements'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/entitlements/{entitlementId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get entitlement by ID + * @deprecated + * @description Get entitlement by ID. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements/{entitlementId}`](#tag/entitlements/get/api/v2/entitlements/{entitlementId}) instead. + */ + get: operations['getEntitlementById'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/events': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List ingested events + * @description List ingested events within a time range. + * + * If the from query param is not provided it defaults to last 72 hours. + */ + get: operations['listEvents'] + put?: never + /** + * Ingest events + * @description Ingests an event or batch of events following the CloudEvents specification. + */ + post: operations['ingestEvents'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/features': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List features + * @description List features. + */ + get: operations['listFeatures'] + put?: never + /** + * Create feature + * @description Features are either metered or static. A feature is metered if meterSlug is provided at creation. + * For metered features you can pass additional filters that will be applied when calculating feature usage, based on the meter's groupBy fields. + * Meters with SUM, COUNT, UNIQUE_COUNT and LATEST aggregations are supported for features. + */ + post: operations['createFeature'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/features/{featureId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get feature + * @description Get a feature by ID. + */ + get: operations['getFeature'] + put?: never + post?: never + /** + * Delete feature + * @description Archive a feature by ID. + * + * Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements cannot be created for it, but archiving the feature does not affect existing entitlements. + * This means, if you want to create a new feature with the same key, and then create entitlements for it, the previous entitlements have to be deleted first on a per subject basis. + */ + delete: operations['deleteFeature'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/grants': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List grants + * @deprecated + * @description List all grants for all the subjects and entitlements. This endpoint is intended for administrative purposes only. + * To fetch the grants of a specific entitlement please use the /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/grants`](#tag/entitlements/get/api/v2/grants) instead. + */ + get: operations['listGrants'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/grants/{grantId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + post?: never + /** + * Void grant + * @description Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed to the grant will remain, but future usage cannot be burnt down from the grant. + * For example, if you have a single grant for your metered entitlement with an initial amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous usage will not be affected. + */ + delete: operations['voidGrant'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/info/currencies': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List supported currencies + * @description List all supported currencies. + */ + get: operations['listCurrencies'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/info/progress/{id}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get progress + * @description Get progress + */ + get: operations['getProgress'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/marketplace/listings': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List available apps + * @description List available apps of the app marketplace. + */ + get: operations['listMarketplaceListings'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/marketplace/listings/{type}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get app details by type + * @description Get a marketplace listing by type. + */ + get: operations['getMarketplaceListing'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/marketplace/listings/{type}/install': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Install app + * @description Install an app from the marketplace. + */ + post: operations['marketplaceAppInstall'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/marketplace/listings/{type}/install/apikey': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Install app via API key + * @description Install an marketplace app via API Key. + */ + post: operations['marketplaceAppAPIKeyInstall'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/marketplace/listings/{type}/install/oauth2': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get OAuth2 install URL + * @description Install an app via OAuth. + * Returns a URL to start the OAuth 2.0 flow. + */ + get: operations['marketplaceOAuth2InstallGetURL'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/marketplace/listings/{type}/install/oauth2/authorize': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Install app via OAuth2 + * @description Authorize OAuth2 code. + * Verifies the OAuth code and exchanges it for a token and refresh token + */ + get: operations['marketplaceOAuth2InstallAuthorize'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/meters': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List meters + * @description List meters. + */ + get: operations['listMeters'] + put?: never + /** + * Create meter + * @description Create a meter. + */ + post: operations['createMeter'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/meters/{meterIdOrSlug}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get meter + * @description Get a meter by ID or slug. + */ + get: operations['getMeter'] + /** + * Update meter + * @description Update a meter. + */ + put: operations['updateMeter'] + post?: never + /** + * Delete meter + * @description Delete a meter. + */ + delete: operations['deleteMeter'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List meter group by values + * @description List meter group by values. + */ + get: operations['listMeterGroupByValues'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/meters/{meterIdOrSlug}/query': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Query meter + * @description Query meter for usage. + */ + get: operations['queryMeter'] + put?: never + /** Query meter */ + post: operations['queryMeterPost'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/meters/{meterIdOrSlug}/subjects': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List meter subjects + * @description List subjects for a meter. + */ + get: operations['listMeterSubjects'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/channels': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List notification channels + * @description List all notification channels. + */ + get: operations['listNotificationChannels'] + put?: never + /** + * Create a notification channel + * @description Create a new notification channel. + */ + post: operations['createNotificationChannel'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/channels/{channelId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get notification channel + * @description Get a notification channel by id. + */ + get: operations['getNotificationChannel'] + /** + * Update a notification channel + * @description Update notification channel. + */ + put: operations['updateNotificationChannel'] + post?: never + /** + * Delete a notification channel + * @description Soft delete notification channel by id. + * + * Once a notification channel is deleted it cannot be undeleted. + */ + delete: operations['deleteNotificationChannel'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/events': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List notification events + * @description List all notification events. + */ + get: operations['listNotificationEvents'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/events/{eventId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get notification event + * @description Get a notification event by id. + */ + get: operations['getNotificationEvent'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/events/{eventId}/resend': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** Re-send notification event */ + post: operations['resendNotificationEvent'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/rules': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List notification rules + * @description List all notification rules. + */ + get: operations['listNotificationRules'] + put?: never + /** + * Create a notification rule + * @description Create a new notification rule. + */ + post: operations['createNotificationRule'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/rules/{ruleId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get notification rule + * @description Get a notification rule by id. + */ + get: operations['getNotificationRule'] + /** + * Update a notification rule + * @description Update notification rule. + */ + put: operations['updateNotificationRule'] + post?: never + /** + * Delete a notification rule + * @description Soft delete notification rule by id. + * + * Once a notification rule is deleted it cannot be undeleted. + */ + delete: operations['deleteNotificationRule'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/notification/rules/{ruleId}/test': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Test notification rule + * @description Test a notification rule by sending a test event with random data. + */ + post: operations['testNotificationRule'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List plans + * @description List all plans. + */ + get: operations['listPlans'] + put?: never + /** + * Create a plan + * @description Create a new plan. + */ + post: operations['createPlan'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans/{planIdOrKey}/next': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * New draft plan + * @deprecated + * @description Create a new draft version from plan. + * It returns error if there is already a plan in draft or planId does not reference the latest published version. + */ + post: operations['nextPlan'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans/{planId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get plan + * @description Get a plan by id or key. The latest published version is returned if latter is used. + */ + get: operations['getPlan'] + /** + * Update a plan + * @description Update plan by id. + */ + put: operations['updatePlan'] + post?: never + /** + * Delete plan + * @description Soft delete plan by plan.id. + * + * Once a plan is deleted it cannot be undeleted. + */ + delete: operations['deletePlan'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans/{planId}/addons': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List all available add-ons for plan + * @description List all available add-ons for plan. + */ + get: operations['listPlanAddons'] + put?: never + /** + * Create new add-on assignment for plan + * @description Create new add-on assignment for plan. + */ + post: operations['createPlanAddon'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans/{planId}/addons/{planAddonId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get add-on assignment for plan + * @description Get add-on assignment for plan by id. + */ + get: operations['getPlanAddon'] + /** + * Update add-on assignment for plan + * @description Update add-on assignment for plan. + */ + put: operations['updatePlanAddon'] + post?: never + /** + * Delete add-on assignment for plan + * @description Delete add-on assignment for plan. + * + * Once a plan is deleted it cannot be undeleted. + */ + delete: operations['deletePlanAddon'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans/{planId}/archive': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Archive plan version + * @description Archive a plan version. + */ + post: operations['archivePlan'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/plans/{planId}/publish': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Publish plan + * @description Publish a plan version. + */ + post: operations['publishPlan'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/portal/meters/{meterSlug}/query': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Query meter Query meter + * @description Query meter for consumer portal. This endpoint is publicly exposable to consumers. Query meter for consumer portal. This endpoint is publicly exposable to consumers. + */ + get: operations['queryPortalMeter'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/portal/tokens': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List consumer portal tokens + * @description List tokens. + */ + get: operations['listPortalTokens'] + put?: never + /** + * Create consumer portal token + * @description Create a consumer portal token. + */ + post: operations['createPortalToken'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/portal/tokens/invalidate': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Invalidate portal tokens + * @description Invalidates consumer portal tokens by ID or subject. + */ + post: operations['invalidatePortalTokens'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/stripe/checkout/sessions': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Create checkout session + * @description Create checkout session. + */ + post: operations['createStripeCheckoutSession'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List subjects + * @deprecated + * @description List subjects. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + */ + get: operations['listSubjects'] + put?: never + /** + * Upsert subject + * @deprecated + * @description Upserts a subject. Creates or updates subject. + * + * If the subject doesn't exist, it will be created. + * If the subject exists, it will be partially updated with the provided fields. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + */ + post: operations['upsertSubject'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get subject + * @deprecated + * @description Get subject by ID or key. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + */ + get: operations['getSubject'] + put?: never + post?: never + /** + * Delete subject + * @deprecated + * @description Delete subject by ID or key. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + */ + delete: operations['deleteSubject'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List subject entitlements + * @deprecated + * @description List all entitlements for a subject. For checking entitlement access, use the /value endpoint instead. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements) instead. + */ + get: operations['listSubjectEntitlements'] + put?: never + /** + * Create a subject entitlement + * @deprecated + * @description OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given subject can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements) instead. + */ + post: operations['createEntitlement'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List subject entitlement grants + * @deprecated + * @description List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + */ + get: operations['listEntitlementGrants'] + put?: never + /** + * Create subject entitlement grant + * @deprecated + * @description Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + * + * A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + * + * Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + * + * Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + * + * Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * + * Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + */ + post: operations['createGrant'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + /** + * Override subject entitlement + * @deprecated + * @description Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided subject-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + * + * This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + * + * ⚠️ __Deprecated__: Use [`PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override`](#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) instead. + */ + put: operations['overrideEntitlement'] + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get subject entitlement value + * @deprecated + * @description This endpoint should be used for access checks and enforcement. All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + * + * For convenience reasons, /value works with both entitlementId and featureKey. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) instead. + */ + get: operations['getEntitlementValue'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get subject entitlement + * @deprecated + * @description Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + */ + get: operations['getEntitlement'] + put?: never + post?: never + /** + * Delete subject entitlement + * @deprecated + * @description Deleting an entitlement revokes access to the associated feature. As a single subject can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + * As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + * + * ⚠️ __Deprecated__: Use [`DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + */ + delete: operations['deleteEntitlement'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get subject entitlement history + * @deprecated + * @description Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + * + * WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) instead. + */ + get: operations['getEntitlementHistory'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Reset subject entitlement + * @deprecated + * @description Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the subjects billing period to enforce usage based on their subscription. + * + * Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) instead. + */ + post: operations['resetEntitlementUsage'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** Create subscription */ + post: operations['createSubscription'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** Get subscription */ + get: operations['getSubscription'] + put?: never + post?: never + /** + * Delete subscription + * @description Deletes a subscription. Only scheduled subscriptions can be deleted. + */ + delete: operations['deleteSubscription'] + options?: never + head?: never + /** + * Edit subscription + * @description Batch processing commands for manipulating running subscriptions. + * The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + */ + patch: operations['editSubscription'] + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/addons': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List subscription addons + * @description List all addons of a subscription. In the returned list will match to a set unique by addonId. + */ + get: operations['listSubscriptionAddons'] + put?: never + /** + * Create subscription addon + * @description Create a new subscription addon, either providing the key or the id of the addon. + */ + post: operations['createSubscriptionAddon'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get subscription addon + * @description Get a subscription addon by id. + */ + get: operations['getSubscriptionAddon'] + put?: never + post?: never + delete?: never + options?: never + head?: never + /** + * Update subscription addon + * @description Updates a subscription addon (allows changing the quantity: purchasing more instances or cancelling the current instances) + */ + patch: operations['updateSubscriptionAddon'] + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/cancel': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Cancel subscription + * @description Cancels the subscription. + * Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancellation time. + */ + post: operations['cancelSubscription'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/change': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Change subscription + * @description Closes a running subscription and starts a new one according to the specification. + * Can be used for upgrades, downgrades, and plan changes. + */ + post: operations['changeSubscription'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/migrate': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Migrate subscription + * @description Migrates the subscripiton to the provided version of the current plan. + * If possible, the migration will be done immediately. + * If not, the migration will be scheduled to the end of the current billing period. + */ + post: operations['migrateSubscription'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/restore': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Restore subscription + * @deprecated + * @description Restores a canceled subscription. + * Any subscription scheduled to start later will be deleted and this subscription will be continued indefinitely. + */ + post: operations['restoreSubscription'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v1/subscriptions/{subscriptionId}/unschedule-cancelation': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Unschedule cancelation + * @description Cancels the scheduled cancelation. + */ + post: operations['unscheduleCancelation'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List customer entitlements + * @description List all entitlements for a customer. For checking entitlement access, use the /value endpoint instead. + */ + get: operations['listCustomerEntitlementsV2'] + put?: never + /** + * Create a customer entitlement + * @description OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given customer can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + */ + post: operations['createCustomerEntitlementV2'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer entitlement + * @description Get entitlement by feature key. For checking entitlement access, use the /value endpoint instead. + * If featureKey is used, the entitlement is resolved for the current timestamp. + */ + get: operations['getCustomerEntitlementV2'] + put?: never + post?: never + /** + * Delete customer entitlement + * @description Deleting an entitlement revokes access to the associated feature. As a single customer can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + * As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + */ + delete: operations['deleteCustomerEntitlementV2'] + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List customer entitlement grants + * @description List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + */ + get: operations['listCustomerEntitlementGrantsV2'] + put?: never + /** + * Create customer entitlement grant + * @description Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + * + * A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + * + * Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + * + * Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + * + * Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * + * Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + */ + post: operations['createCustomerEntitlementGrantV2'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer entitlement history + * @description Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + * + * WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + */ + get: operations['getCustomerEntitlementHistoryV2'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + /** + * Override customer entitlement + * @description Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided customer-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + * + * This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + */ + put: operations['overrideCustomerEntitlementV2'] + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + get?: never + put?: never + /** + * Reset customer entitlement + * @description Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the customers billing period to enforce usage based on their subscription. + * + * Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + */ + post: operations['resetCustomerEntitlementUsageV2'] + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get customer entitlement value + * @description Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + */ + get: operations['getCustomerEntitlementValueV2'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/entitlements': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List all entitlements + * @description List all entitlements for all the customers and features. This endpoint is intended for administrative purposes only. + * To fetch the entitlements of a specific subject please use the /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + */ + get: operations['listEntitlementsV2'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/entitlements/{entitlementId}': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * Get entitlement by ID + * @description Get entitlement by ID. + */ + get: operations['getEntitlementByIdV2'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/events': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List ingested events + * @description List ingested events with advanced filtering and cursor pagination. + */ + get: operations['listEventsV2'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } + '/api/v2/grants': { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + /** + * List grants + * @description List all grants for all the customers and entitlements. This endpoint is intended for administrative purposes only. + * To fetch the grants of a specific entitlement please use the /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + * If page is provided that takes precedence and the paginated response is returned. + */ + get: operations['listGrantsV2'] + put?: never + post?: never + delete?: never + options?: never + head?: never + patch?: never + trace?: never + } +} +export type webhooks = Record +export interface components { + schemas: { + /** @description Add-on allows extending subscriptions with compatible plans with additional ratecards. */ + Addon: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Version + * @description Version of the add-on. Incremented when the add-on is updated. + * @default 1 + */ + readonly version: number + /** + * InstanceType + * @description The instanceType of the add-ons. Can be "single" or "multiple". + */ + instanceType: components['schemas']['AddonInstanceType'] + /** + * Currency + * @description The currency code of the add-on. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Effective start date + * Format: date-time + * @description The date and time when the add-on becomes effective. When not specified, the add-on is a draft. + * @example 2023-01-01T01:01:01.001Z + */ + readonly effectiveFrom?: Date + /** + * Effective end date + * Format: date-time + * @description The date and time when the add-on is no longer effective. When not specified, the add-on is effective indefinitely. + * @example 2023-01-01T01:01:01.001Z + */ + readonly effectiveTo?: Date + /** + * Status + * @description The status of the add-on. + * Computed based on the effective start and end dates: + * - draft = no effectiveFrom + * - active = effectiveFrom <= now < effectiveTo + * - archived = effectiveTo <= now + */ + readonly status: components['schemas']['AddonStatus'] + /** + * Rate cards + * @description The rate cards of the add-on. + */ + rateCards: components['schemas']['RateCard'][] + /** + * Validation errors + * @description List of validation errors. + */ + readonly validationErrors: + | components['schemas']['ValidationError'][] + | null + } + /** @description Resource create operation model. */ + AddonCreate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** + * InstanceType + * @description The instanceType of the add-ons. Can be "single" or "multiple". + */ + instanceType: components['schemas']['AddonInstanceType'] + /** + * Currency + * @description The currency code of the add-on. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Rate cards + * @description The rate cards of the add-on. + */ + rateCards: components['schemas']['RateCard'][] + } + /** + * @description The instanceType of the add-on. + * Single instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once. + * @enum {string} + */ + AddonInstanceType: 'single' | 'multiple' + /** + * @description Order by options for add-ons. + * @enum {string} + */ + AddonOrderBy: 'id' | 'key' | 'version' | 'created_at' | 'updated_at' + /** @description Paginated response */ + AddonPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Addon'][] + } + /** @description Resource update operation model. */ + AddonReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * InstanceType + * @description The instanceType of the add-ons. Can be "single" or "multiple". + */ + instanceType: components['schemas']['AddonInstanceType'] + /** + * Rate cards + * @description The rate cards of the add-on. + */ + rateCards: components['schemas']['RateCard'][] + } + /** + * @description The status of the add-on defined by the effectiveFrom and effectiveTo properties. + * @enum {string} + */ + AddonStatus: 'draft' | 'active' | 'archived' + /** @description Address */ + Address: { + /** @description Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format. */ + country?: components['schemas']['CountryCode'] + /** @description Postal code. */ + postalCode?: string + /** @description State or province. */ + state?: string + /** @description City. */ + city?: string + /** @description First line of the address. */ + line1?: string + /** @description Second line of the address. */ + line2?: string + /** @description Phone number. */ + phoneNumber?: string + } + /** + * @deprecated + * @description Alignment configuration for a plan or subscription. + */ + Alignment: { + /** + * @deprecated + * @description Whether all Billable items and RateCards must align. + * Alignment means the Price's BillingCadence must align for both duration and anchor time. + */ + billablesMustAlign?: boolean + } + /** + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + * @example { + * "externalId": "019142cc-a016-796a-8113-1a942fecd26d" + * } + */ + Annotations: { + [key: string]: unknown + } + /** + * @description App. + * One of: stripe + */ + App: + | components['schemas']['StripeApp'] + | components['schemas']['SandboxApp'] + | components['schemas']['CustomInvoicingApp'] + /** + * @description App capability. + * + * Capabilities only exist in config so they don't extend the Resource model. + * @example { + * "type": "collectPayments", + * "key": "stripe_collect_payment", + * "name": "Collect Payments", + * "description": "Stripe payments collects outstanding revenue with Stripe customer's default payment method." + * } + */ + AppCapability: { + /** @description The capability type. */ + type: components['schemas']['AppCapabilityType'] + /** @description Key */ + key: string + /** @description The capability name. */ + name: string + /** @description The capability description. */ + description: string + } + /** + * @description App capability type. + * @enum {string} + */ + AppCapabilityType: + | 'reportUsage' + | 'reportEvents' + | 'calculateTax' + | 'invoiceCustomers' + | 'collectPayments' + /** @description Paginated response */ + AppPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['App'][] + } + /** + * @description App reference + * + * Can be used as a short reference to an app if the full app object is not needed. + */ + AppReference: { + /** + * @description The ID of the app. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + } + /** @description App ReplaceUpdate Model */ + AppReplaceUpdate: + | components['schemas']['StripeAppReplaceUpdate'] + | components['schemas']['SandboxAppReplaceUpdate'] + | components['schemas']['CustomInvoicingAppReplaceUpdate'] + /** + * @description App installed status. + * @enum {string} + */ + AppStatus: 'ready' | 'unauthorized' + /** + * @description Type of the app. + * @enum {string} + */ + AppType: 'stripe' | 'sandbox' | 'custom_invoicing' + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + BadRequestProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** @description The balance history window. */ + BalanceHistoryWindow: { + period: components['schemas']['Period'] + /** + * Format: double + * @description The total usage of the feature in the period. + * @example 100 + */ + readonly usage: number + /** + * Format: double + * @description The entitlement balance at the start of the period. + * @example 100 + */ + readonly balanceAtStart: number + } + /** + * @description Customer specific merged profile. + * + * This profile is calculated from the customer override and the billing profile it references or the default. + * + * Thus this does not have any kind of resource fields, only the calculated values. + */ + BillingCustomerProfile: { + /** @description The name and contact information for the supplier this billing profile represents */ + readonly supplier: components['schemas']['BillingParty'] + /** @description The billing workflow settings for this profile */ + readonly workflow: components['schemas']['BillingWorkflow'] + /** + * @description The applications used by this billing profile. + * + * Expand settings govern if this includes the whole app object or just the ID references. + */ + readonly apps: components['schemas']['BillingProfileAppsOrReference'] + } + /** @description A percentage discount. */ + BillingDiscountPercentage: { + /** + * Percentage + * @description The percentage of the discount. + */ + percentage: components['schemas']['Percentage'] + /** + * @description Correlation ID for the discount. + * + * This is used to link discounts across different invoices (progressive billing use case). + * + * If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + * please make sure to keep the same correlation ID of the discount or in progressive billing + * setups the discount amounts might be incorrect. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + correlationId?: string + } + /** @description The reason for the discount. */ + BillingDiscountReason: + | components['schemas']['DiscountReasonMaximumSpend'] + | components['schemas']['DiscountReasonRatecardPercentage'] + | components['schemas']['DiscountReasonRatecardUsage'] + /** @description A usage discount. */ + BillingDiscountUsage: { + /** + * Usage + * @description The quantity of the usage discount. + * + * Must be positive. + */ + quantity: components['schemas']['Numeric'] + /** + * @description Correlation ID for the discount. + * + * This is used to link discounts across different invoices (progressive billing use case). + * + * If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + * please make sure to keep the same correlation ID of the discount or in progressive billing + * setups the discount amounts might be incorrect. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + correlationId?: string + } + /** @description A discount by type. */ + BillingDiscounts: { + /** @description The percentage discount. */ + percentage?: components['schemas']['BillingDiscountPercentage'] + /** @description The usage discount. */ + usage?: components['schemas']['BillingDiscountUsage'] + } + /** + * @description BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the billing party details for invoices. + * + * These fields contain the OpenMeter specific details for the customer, that are not strictly required for the invoice itself. + */ + BillingInvoiceCustomerExtendedDetails: { + /** @description Unique identifier for the party (if available) */ + readonly id?: string + /** + * Key + * @description An optional unique key of the party (if available) + */ + key?: string + /** @description Legal name or representation of the organization. */ + name?: string + /** + * @description The entity's legal ID code used for tax purposes. They may have + * other numbers, but we're only interested in those valid for tax purposes. + */ + taxId?: components['schemas']['BillingPartyTaxIdentity'] + /** @description Regular post addresses for where information should be sent if needed. */ + addresses?: components['schemas']['Address'][] + /** + * Usage Attribution + * @description Mapping to attribute metered usage to the customer + */ + usageAttribution: components['schemas']['CustomerUsageAttribution'] + } + /** @description Party represents a person or business entity. */ + BillingParty: { + /** @description Unique identifier for the party (if available) */ + readonly id?: string + /** + * Key + * @description An optional unique key of the party (if available) + */ + key?: string + /** @description Legal name or representation of the organization. */ + name?: string + /** + * @description The entity's legal ID code used for tax purposes. They may have + * other numbers, but we're only interested in those valid for tax purposes. + */ + taxId?: components['schemas']['BillingPartyTaxIdentity'] + /** @description Regular post addresses for where information should be sent if needed. */ + addresses?: components['schemas']['Address'][] + } + /** @description Resource update operation model. */ + BillingPartyReplaceUpdate: { + /** + * Key + * @description An optional unique key of the party (if available) + */ + key?: string + /** @description Legal name or representation of the organization. */ + name?: string + /** + * @description The entity's legal ID code used for tax purposes. They may have + * other numbers, but we're only interested in those valid for tax purposes. + */ + taxId?: components['schemas']['BillingPartyTaxIdentity'] + /** @description Regular post addresses for where information should be sent if needed. */ + addresses?: components['schemas']['Address'][] + } + /** @description Identity stores the details required to identify an entity for tax purposes in a specific country. */ + BillingPartyTaxIdentity: { + /** @description Normalized tax code shown on the original identity document. */ + code?: components['schemas']['BillingTaxIdentificationCode'] + } + /** @description BillingProfile represents a billing profile */ + BillingProfile: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description The name and contact information for the supplier this billing profile represents */ + supplier: components['schemas']['BillingParty'] + /** @description The billing workflow settings for this profile */ + readonly workflow: components['schemas']['BillingWorkflow'] + /** + * @description The applications used by this billing profile. + * + * Expand settings govern if this includes the whole app object or just the ID references. + */ + readonly apps: components['schemas']['BillingProfileAppsOrReference'] + /** @description Is this the default profile? */ + default: boolean + } + /** @description BillingProfileAppReferences represents the references (id, type) to the apps used by a billing profile */ + BillingProfileAppReferences: { + /** @description The tax app used for this workflow */ + readonly tax: components['schemas']['AppReference'] + /** @description The invoicing app used for this workflow */ + readonly invoicing: components['schemas']['AppReference'] + /** @description The payment app used for this workflow */ + readonly payment: components['schemas']['AppReference'] + } + /** @description BillingProfileApps represents the applications used by a billing profile */ + BillingProfileApps: { + /** @description The tax app used for this workflow */ + readonly tax: components['schemas']['App'] + /** @description The invoicing app used for this workflow */ + readonly invoicing: components['schemas']['App'] + /** @description The payment app used for this workflow */ + readonly payment: components['schemas']['App'] + } + /** @description BillingProfileAppsCreate represents the input for creating a billing profile's apps */ + BillingProfileAppsCreate: { + /** + * @description The tax app used for this workflow + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + tax: string + /** + * @description The invoicing app used for this workflow + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + invoicing: string + /** + * @description The payment app used for this workflow + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + payment: string + } + /** + * @description ProfileAppsOrReference represents the union of ProfileApps and ProfileAppReferences + * for a billing profile. + */ + BillingProfileAppsOrReference: + | components['schemas']['BillingProfileApps'] + | components['schemas']['BillingProfileAppReferences'] + /** @description BillingProfileCreate represents the input for creating a billing profile */ + BillingProfileCreate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** @description The name and contact information for the supplier this billing profile represents */ + supplier: components['schemas']['BillingParty'] + /** @description Is this the default profile? */ + default: boolean + /** @description The billing workflow settings for this profile. */ + workflow: components['schemas']['BillingWorkflowCreate'] + /** @description The apps used by this billing profile. */ + apps: components['schemas']['BillingProfileAppsCreate'] + } + /** @description Customer override values. */ + BillingProfileCustomerOverride: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * @description The billing profile this override is associated with. + * + * If empty the default profile is looked up dynamically. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + billingProfileId?: string + /** + * @description The customer id this override is associated with. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId: string + } + /** @description Payload for creating a new or updating an existing customer override. */ + BillingProfileCustomerOverrideCreate: { + /** + * @description The billing profile this override is associated with. + * + * If not provided, the default billing profile is chosen if available. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + billingProfileId?: string + } + /** + * @description CustomerOverrideExpand specifies the parts of the profile to expand. + * @enum {string} + */ + BillingProfileCustomerOverrideExpand: 'apps' | 'customer' + /** + * @description Order by options for customers. + * @enum {string} + */ + BillingProfileCustomerOverrideOrderBy: + | 'customerId' + | 'customerName' + | 'customerKey' + | 'customerPrimaryEmail' + | 'customerCreatedAt' + /** @description Customer specific workflow overrides. */ + BillingProfileCustomerOverrideWithDetails: { + /** + * @description The customer override values. + * + * If empty the merged values are calculated based on the default profile. + */ + customerOverride?: components['schemas']['BillingProfileCustomerOverride'] + /** + * @description The billing profile the customerProfile is associated with at the time of query. + * + * customerOverride contains the explicit mapping set in the customer override object. If that is + * empty, then the baseBillingProfileId is the default profile. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + baseBillingProfileId: string + /** @description Merged billing profile with the customer specific overrides. */ + customerProfile?: components['schemas']['BillingCustomerProfile'] + /** @description The customer this override belongs to. */ + customer?: components['schemas']['Customer'] + } + /** @description Paginated response */ + BillingProfileCustomerOverrideWithDetailsPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['BillingProfileCustomerOverrideWithDetails'][] + } + /** + * @description BillingProfileExpand details what profile fields to expand + * @enum {string} + */ + BillingProfileExpand: 'apps' + /** + * @description BillingProfileOrderBy specifies the ordering options for profiles + * @enum {string} + */ + BillingProfileOrderBy: 'createdAt' | 'updatedAt' | 'default' | 'name' + /** @description Paginated response */ + BillingProfilePaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['BillingProfile'][] + } + /** + * @description BillingProfileReplaceUpdate represents the input for updating a billing profile + * + * The apps field cannot be updated directly, if an app change is desired a new + * profile should be created. + */ + BillingProfileReplaceUpdateWithWorkflow: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** @description The name and contact information for the supplier this billing profile represents */ + supplier: components['schemas']['BillingParty'] + /** @description Is this the default profile? */ + default: boolean + /** @description The billing workflow settings for this profile. */ + workflow: components['schemas']['BillingWorkflow'] + } + /** + * @description The settlement mode of a plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * @enum {string} + */ + BillingSettlementMode: 'credit_then_invoice' | 'credit_only' + /** @description TaxIdentificationCode is a normalized tax code shown on the original identity document. */ + BillingTaxIdentificationCode: string + /** @description BillingWorkflow represents the settings for a billing workflow. */ + BillingWorkflow: { + /** @description The collection settings for this workflow */ + collection?: components['schemas']['BillingWorkflowCollectionSettings'] + /** @description The invoicing settings for this workflow */ + invoicing?: components['schemas']['BillingWorkflowInvoicingSettings'] + /** @description The payment settings for this workflow */ + payment?: components['schemas']['BillingWorkflowPaymentSettings'] + /** @description The tax settings for this workflow */ + tax?: components['schemas']['BillingWorkflowTaxSettings'] + } + /** + * @description The alignment for collecting the pending line items into an invoice. + * + * Defaults to subscription, which means that we are to create a new invoice every time the + * a subscription period starts (for in advance items) or ends (for in arrears items). + */ + BillingWorkflowCollectionAlignment: + | components['schemas']['BillingWorkflowCollectionAlignmentSubscription'] + | components['schemas']['BillingWorkflowCollectionAlignmentAnchored'] + /** + * @description BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items + * into an invoice. + */ + BillingWorkflowCollectionAlignmentAnchored: { + /** + * @description The type of alignment. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'anchored' + /** @description The recurring period for the alignment. */ + recurringPeriod: components['schemas']['RecurringPeriodV2'] + } + /** + * @description BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items + * into an invoice. + */ + BillingWorkflowCollectionAlignmentSubscription: { + /** + * @description The type of alignment. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'subscription' + } + /** @description Workflow collection specifies how to collect the pending line items for an invoice */ + BillingWorkflowCollectionSettings: { + /** + * @description The alignment for collecting the pending line items into an invoice. + * @default { + * "type": "subscription" + * } + */ + alignment?: components['schemas']['BillingWorkflowCollectionAlignment'] + /** + * Format: ISO8601 + * @description This grace period can be used to delay the collection of the pending line items specified in + * alignment. + * + * This is useful, in case of multiple subscriptions having slightly different billing periods. + * @default PT1H + * @example P1D + */ + interval?: string + } + /** @description Resource create operation model. */ + BillingWorkflowCreate: { + /** @description The collection settings for this workflow */ + collection?: components['schemas']['BillingWorkflowCollectionSettings'] + /** @description The invoicing settings for this workflow */ + invoicing?: components['schemas']['BillingWorkflowInvoicingSettings'] + /** @description The payment settings for this workflow */ + payment?: components['schemas']['BillingWorkflowPaymentSettings'] + /** @description The tax settings for this workflow */ + tax?: components['schemas']['BillingWorkflowTaxSettings'] + } + /** + * Workflow invoice settings + * @description BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow + */ + BillingWorkflowInvoicingSettings: { + /** + * @description Whether to automatically issue the invoice after the draftPeriod has passed. + * @default true + */ + autoAdvance?: boolean + /** + * Format: ISO8601 + * @description The period for the invoice to be kept in draft status for manual reviews. + * @default P0D + * @example P1D + */ + draftPeriod?: string + /** + * Format: ISO8601 + * @description The period after which the invoice is due. + * With some payment solutions it's only applicable for manual collection method. + * @default P30D + * @example P30D + */ + dueAfter?: string + /** + * @description Should progressive billing be allowed for this workflow? + * @default true + */ + progressiveBilling?: boolean + /** + * @description Controls how subscription-ending shortened service periods are billed. + * @default bill_actual_period + */ + subscriptionEndProrationMode?: components['schemas']['BillingWorkflowInvoicingSubscriptionEndProrationMode'] + /** + * @description Default tax configuration to apply to the invoices. + * + * Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + * deprecated and can no longer be added or changed: the organization default tax code is + * used instead. Existing tax-code values may still be removed, and `behavior` remains + * fully supported. + */ + defaultTaxConfig?: components['schemas']['TaxConfig'] + } + /** + * @description Billing workflow subscription end proration mode. + * @enum {string} + */ + BillingWorkflowInvoicingSubscriptionEndProrationMode: + | 'bill_full_period' + | 'bill_actual_period' + /** + * Workflow payment settings + * @description BillingWorkflowPaymentSettings represents the payment settings for a billing workflow + */ + BillingWorkflowPaymentSettings: { + /** + * @description The payment method for the invoice. + * @default charge_automatically + */ + collectionMethod?: components['schemas']['CollectionMethod'] + } + /** + * Workflow tax settings + * @description BillingWorkflowTaxSettings represents the tax settings for a billing workflow + */ + BillingWorkflowTaxSettings: { + /** + * @description Enable automatic tax calculation when tax is supported by the app. + * For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + * @default true + */ + enabled?: boolean + /** + * @description Enforce tax calculation when tax is supported by the app. + * When enabled, OpenMeter will not allow to create an invoice without tax calculation. + * Enforcement is different per apps, for example, Stripe app requires customer + * to have a tax location when starting a paid subscription. + * @default false + */ + enforced?: boolean + } + /** @description Stripe CheckoutSession.custom_text */ + CheckoutSessionCustomTextAfterSubmitParams: { + /** @description Custom text that should be displayed after the payment confirmation button. */ + afterSubmit?: { + message?: string + } + /** @description Custom text that should be displayed alongside shipping address collection. */ + shippingAddress?: { + message?: string + } + /** @description Custom text that should be displayed alongside the payment confirmation button. */ + submit?: { + message?: string + } + /** @description Custom text that should be displayed in place of the default terms of service agreement text. */ + termsOfServiceAcceptance?: { + message?: string + } + } + /** + * @description Stripe CheckoutSession.ui_mode + * @enum {string} + */ + CheckoutSessionUIMode: 'embedded' | 'hosted' + /** @description Response from the client app (OpenMeter backend) to start the OAuth2 flow. */ + ClientAppStartResponse: { + /** @description The URL to start the OAuth2 authorization code grant flow. */ + url: string + } + /** + * Collection method + * @description CollectionMethod specifies how the invoice should be collected (automatic vs manual) + * @enum {string} + */ + CollectionMethod: 'charge_automatically' | 'send_invoice' + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + ConflictProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** + * @description [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. + * Custom two-letter country codes are also supported for convenience. + * @example US + */ + CountryCode: string + /** @description Create Stripe checkout session tax ID collection. */ + CreateCheckoutSessionTaxIdCollection: { + /** @description Enable tax ID collection during checkout. Defaults to false. */ + enabled: boolean + /** @description Describes whether a tax ID is required during checkout. Defaults to never. */ + required?: components['schemas']['CreateCheckoutSessionTaxIdCollectionRequired'] + } + /** + * @description Create Stripe checkout session tax ID collection required. + * @enum {string} + */ + CreateCheckoutSessionTaxIdCollectionRequired: 'if_supported' | 'never' + /** + * @description Specify whether Checkout should collect the customer’s billing address. + * @enum {string} + */ + CreateStripeCheckoutSessionBillingAddressCollection: 'auto' | 'required' + /** @description Configure fields for the Checkout Session to gather active consent from customers. */ + CreateStripeCheckoutSessionConsentCollection: { + /** + * @description Determines the position and visibility of the payment method reuse agreement in the UI. + * When set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI. + */ + paymentMethodReuseAgreement?: components['schemas']['CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement'] + /** + * @description If set to auto, enables the collection of customer consent for promotional communications. + * The Checkout Session will determine whether to display an option to opt into promotional + * communication from the merchant depending on the customer’s locale. Only available to US merchants. + */ + promotions?: components['schemas']['CreateStripeCheckoutSessionConsentCollectionPromotions'] + /** + * @description If set to required, it requires customers to check a terms of service checkbox before being able to pay. + * There must be a valid terms of service URL set in your Stripe Dashboard settings. + * https://dashboard.stripe.com/settings/public + */ + termsOfService?: components['schemas']['CreateStripeCheckoutSessionConsentCollectionTermsOfService'] + } + /** @description Create Stripe checkout session payment method reuse agreement. */ + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement: { + position?: components['schemas']['CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition'] + } + /** + * @description Create Stripe checkout session consent collection agreement position. + * @enum {string} + */ + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition: + | 'auto' + | 'hidden' + /** + * @description Create Stripe checkout session consent collection promotions. + * @enum {string} + */ + CreateStripeCheckoutSessionConsentCollectionPromotions: 'auto' | 'none' + /** + * @description Create Stripe checkout session consent collection terms of service. + * @enum {string} + */ + CreateStripeCheckoutSessionConsentCollectionTermsOfService: + | 'none' + | 'required' + /** @description Controls what fields on Customer can be updated by the Checkout Session. */ + CreateStripeCheckoutSessionCustomerUpdate: { + /** + * @description Describes whether Checkout saves the billing address onto customer.address. + * To always collect a full billing address, use billing_address_collection. + * Defaults to never. + */ + address?: components['schemas']['CreateStripeCheckoutSessionCustomerUpdateBehavior'] + /** + * @description Describes whether Checkout saves the name onto customer.name. + * Defaults to never. + */ + name?: components['schemas']['CreateStripeCheckoutSessionCustomerUpdateBehavior'] + /** + * @description Describes whether Checkout saves shipping information onto customer.shipping. + * To collect shipping information, use shipping_address_collection. + * Defaults to never. + */ + shipping?: components['schemas']['CreateStripeCheckoutSessionCustomerUpdateBehavior'] + } + /** + * @description Create Stripe checkout session customer update behavior. + * @enum {string} + */ + CreateStripeCheckoutSessionCustomerUpdateBehavior: 'auto' | 'never' + /** + * @description Create Stripe checkout session redirect on completion. + * @enum {string} + */ + CreateStripeCheckoutSessionRedirectOnCompletion: + | 'always' + | 'if_required' + | 'never' + /** + * @description Create Stripe checkout session request. + * @example { + * "customer": { + * "name": "ACME, Inc.", + * "currency": "USD", + * "usageAttribution": { + * "subjectKeys": [ + * "my-identifier" + * ] + * } + * }, + * "options": { + * "currency": "USD", + * "successURL": "http://example.com", + * "billingAddressCollection": "required", + * "taxIdCollection": { + * "enabled": true, + * "required": "if_supported" + * }, + * "customerUpdate": { + * "name": "auto", + * "address": "auto" + * } + * } + * } + */ + CreateStripeCheckoutSessionRequest: { + /** + * @description If not provided, the default Stripe app is used if any. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + appId?: string + /** + * @description Provide a customer ID or key to use an existing OpenMeter customer. + * or provide a customer object to create a new customer. + */ + customer: + | components['schemas']['CustomerId'] + | components['schemas']['CustomerKey'] + | components['schemas']['CustomerCreate'] + /** + * @description Stripe customer ID. + * If not provided OpenMeter creates a new Stripe customer or + * uses the OpenMeter customer's default Stripe customer ID. + */ + stripeCustomerId?: string + /** @description Options passed to Stripe when creating the checkout session. */ + options: components['schemas']['CreateStripeCheckoutSessionRequestOptions'] + } + /** + * @description Create Stripe checkout session options + * See https://docs.stripe.com/api/checkout/sessions/create + */ + CreateStripeCheckoutSessionRequestOptions: { + /** @description Specify whether Checkout should collect the customer’s billing address. Defaults to auto. */ + billingAddressCollection?: components['schemas']['CreateStripeCheckoutSessionBillingAddressCollection'] + /** + * @description If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + * This parameter is not allowed if ui_mode is embedded. + */ + cancelURL?: string + /** @description A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. */ + clientReferenceID?: string + /** @description Controls what fields on Customer can be updated by the Checkout Session. */ + customerUpdate?: components['schemas']['CreateStripeCheckoutSessionCustomerUpdate'] + /** @description Configure fields for the Checkout Session to gather active consent from customers. */ + consentCollection?: components['schemas']['CreateStripeCheckoutSessionConsentCollection'] + /** @description Three-letter ISO currency code, in lowercase. */ + currency?: components['schemas']['CurrencyCode'] + /** @description Display additional text for your customers using custom text. */ + customText?: components['schemas']['CheckoutSessionCustomTextAfterSubmitParams'] + /** + * Format: int64 + * @description The Epoch time in seconds at which the Checkout Session will expire. + * It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + */ + expiresAt?: number + locale?: string + /** + * @description Set of key-value pairs that you can attach to an object. + * This can be useful for storing additional information about the object in a structured format. + * Individual keys can be unset by posting an empty value to them. + * All keys can be unset by posting an empty value to metadata. + */ + metadata?: { + [key: string]: string + } + /** + * @description The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site. + * This parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session. + */ + returnURL?: string + /** + * @description The URL to which Stripe should send customers when payment or setup is complete. + * This parameter is not allowed if ui_mode is embedded. + * If you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + successURL?: string + /** @description The UI mode of the Session. Defaults to hosted. */ + uiMode?: components['schemas']['CheckoutSessionUIMode'] + /** @description A list of the types of payment methods (e.g., card) this Checkout Session can accept. */ + paymentMethodTypes?: string[] + /** + * @description This parameter applies to ui_mode: embedded. Defaults to always. + * Learn more about the redirect behavior of embedded sessions at + * https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + */ + redirectOnCompletion?: components['schemas']['CreateStripeCheckoutSessionRedirectOnCompletion'] + /** @description Controls tax ID collection during checkout. */ + taxIdCollection?: components['schemas']['CreateCheckoutSessionTaxIdCollection'] + } + /** @description Create Stripe Checkout Session response. */ + CreateStripeCheckoutSessionResult: { + /** + * @description The OpenMeter customer ID. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId: string + /** @description The Stripe customer ID. */ + stripeCustomerId: string + /** @description The checkout session ID. */ + sessionId: string + /** @description The checkout session setup intent ID. */ + setupIntentId: string + /** + * @description The client secret of the checkout session. + * This can be used to initialize Stripe.js for your client-side implementation. + */ + clientSecret?: string + /** + * @description A unique string to reference the Checkout Session. + * This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + */ + clientReferenceId?: string + /** @description Customer's email address provided to Stripe. */ + customerEmail?: string + /** @description Three-letter ISO currency code, in lowercase. */ + currency?: components['schemas']['CurrencyCode'] + /** + * Format: date-time + * @description Timestamp at which the checkout session was created. + * @example 2023-01-01T01:01:01.001Z + */ + createdAt: Date + /** + * Format: date-time + * @description Timestamp at which the checkout session will expire. + * @example 2023-01-01T01:01:01.001Z + */ + expiresAt?: Date + /** @description Set of key-value pairs attached to the checkout session. */ + metadata?: { + [key: string]: string + } + /** @description The status of the checkout session. */ + status?: string + /** @description URL to show the checkout session. */ + url?: string + /** + * @description Mode + * Always `setup` for now. + */ + mode: components['schemas']['StripeCheckoutSessionMode'] + /** @description Cancel URL. */ + cancelURL?: string + /** @description Success URL. */ + successURL?: string + /** @description Return URL. */ + returnURL?: string + } + /** @description Stripe customer portal request params. */ + CreateStripeCustomerPortalSessionParams: { + /** + * Configuration + * @description The ID of an existing configuration to use for this session, + * describing its functionality and features. + * If not specified, the session uses the default configuration. + * + * See https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration + */ + configurationId?: string + /** + * Locale + * @description The IETF language tag of the locale customer portal is displayed in. + * If blank or auto, the customer’s preferred_locales or browser’s locale is used. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale + */ + locale?: string + /** + * ReturnUrl + * @description The URL to redirect the customer to after they have completed + * their requested actions. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url + */ + returnUrl?: string + } + /** @description CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is based on. */ + CreditNoteOriginalInvoiceRef: { + /** + * @description Type of the invoice. + * @enum {string} + */ + type: 'credit_note_original_invoice' + /** + * Format: date-time + * @description IssueAt reflects the time the document was issued. + * @example 2023-01-01T01:01:01.001Z + */ + readonly issuedAt?: Date + /** @description (Serial) Number of the referenced document. */ + readonly number?: components['schemas']['InvoiceNumber'] + /** + * Format: uri + * @description Link to the source document. + */ + readonly url: string + } & WithRequired + /** @description Currency describes a currency supported by OpenMeter. */ + Currency: { + /** @description The currency ISO code. */ + code: components['schemas']['CurrencyCode'] + /** @description The currency name. */ + name: string + /** @description The currency symbol. */ + symbol: string + /** + * Format: uint32 + * @description Subunit of the currency. + */ + subunits: number + } + /** + * @description Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. + * Custom three-letter currency codes are also supported for convenience. + * @example USD + */ + CurrencyCode: string + /** + * @description Custom Invoicing app can be used for interface with any invoicing or payment system. + * + * This app provides ways to manipulate invoices and payments, however the integration + * must rely on Notifications API to get notified about invoice changes. + */ + CustomInvoicingApp: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description The marketplace listing that this installed app is based on. */ + readonly listing: components['schemas']['MarketplaceListing'] + /** @description Status of the app connection. */ + readonly status: components['schemas']['AppStatus'] + /** + * @description The app's type is CustomInvoicing. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'custom_invoicing' + /** + * @description Enable draft.sync hook. + * + * If the hook is not enabled, the invoice will be progressed to the next state automatically. + */ + enableDraftSyncHook: boolean + /** + * @description Enable issuing.sync hook. + * + * If the hook is not enabled, the invoice will be progressed to the next state automatically. + */ + enableIssuingSyncHook: boolean + } + /** @description Resource update operation model. */ + CustomInvoicingAppReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * @description The app's type is CustomInvoicing. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'custom_invoicing' + /** + * @description Enable draft.sync hook. + * + * If the hook is not enabled, the invoice will be progressed to the next state automatically. + */ + enableDraftSyncHook: boolean + /** + * @description Enable issuing.sync hook. + * + * If the hook is not enabled, the invoice will be progressed to the next state automatically. + */ + enableIssuingSyncHook: boolean + } + /** @description Custom Invoicing Customer App Data. */ + CustomInvoicingCustomerAppData: { + /** @description The installed custom invoicing app this data belongs to. */ + readonly app?: components['schemas']['CustomInvoicingApp'] + /** + * App ID + * @description The app ID. + * If not provided, it will use the global default for the app type. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id?: string + /** + * @description The app name. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'custom_invoicing' + /** @description Metadata to be used by the custom invoicing provider. */ + metadata?: components['schemas']['Metadata'] + } + /** @description Information to finalize the draft details of an invoice. */ + CustomInvoicingDraftSynchronizedRequest: { + /** @description The result of the synchronization. */ + invoicing?: components['schemas']['CustomInvoicingSyncResult'] + } + /** @description Information to finalize the invoicing details of an invoice. */ + CustomInvoicingFinalizedInvoicingRequest: { + /** @description If set the invoice's number will be set to this value. */ + invoiceNumber?: components['schemas']['InvoiceNumber'] + /** + * Format: date-time + * @description If set the invoice's sent to customer at will be set to this value. + * @example 2023-01-01T01:01:01.001Z + */ + sentToCustomerAt?: Date + } + /** @description Information to finalize the payment details of an invoice. */ + CustomInvoicingFinalizedPaymentRequest: { + /** @description If set the invoice's payment external ID will be set to this value. */ + externalId?: string + } + /** + * @description Information to finalize the invoice. + * + * If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix). + */ + CustomInvoicingFinalizedRequest: { + /** @description The result of the synchronization. */ + invoicing?: components['schemas']['CustomInvoicingFinalizedInvoicingRequest'] + /** @description The result of the payment synchronization. */ + payment?: components['schemas']['CustomInvoicingFinalizedPaymentRequest'] + } + /** @description Mapping between line discounts and external IDs. */ + CustomInvoicingLineDiscountExternalIdMapping: { + /** + * @description The line discount ID. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + lineDiscountId: string + /** @description The external ID (e.g. custom invoicing system's ID). */ + externalId: string + } + /** @description Mapping between lines and external IDs. */ + CustomInvoicingLineExternalIdMapping: { + /** + * @description The line ID. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + lineId: string + /** @description The external ID (e.g. custom invoicing system's ID). */ + externalId: string + } + /** + * @description Payment trigger to execute on a finalized invoice. + * @enum {string} + */ + CustomInvoicingPaymentTrigger: + | 'paid' + | 'payment_failed' + | 'payment_uncollectible' + | 'payment_overdue' + | 'action_required' + | 'void' + /** + * @description Information to synchronize the invoice. + * + * Can be used to store external app's IDs on the invoice or lines. + */ + CustomInvoicingSyncResult: { + /** @description If set the invoice's number will be set to this value. */ + invoiceNumber?: components['schemas']['InvoiceNumber'] + /** @description If set the invoice's invoicing external ID will be set to this value. */ + externalId?: string + /** + * @description If set the invoice's line external IDs will be set to this value. + * + * This can be used to reference the external system's entities in the + * invoice. + */ + lineExternalIds?: components['schemas']['CustomInvoicingLineExternalIdMapping'][] + /** + * @description If set the invoice's line discount external IDs will be set to this value. + * + * This can be used to reference the external system's entities in the + * invoice. + */ + lineDiscountExternalIds?: components['schemas']['CustomInvoicingLineDiscountExternalIdMapping'][] + } + /** @description Custom invoicing tax config. */ + CustomInvoicingTaxConfig: { + /** + * Tax code + * @description Tax code. + * + * The tax code should be interpreted by the custom invoicing provider. + */ + code: string + } + /** + * @description Update payment status request. + * + * Can be used to manipulate invoice's payment status (when custominvoicing app is being used). + */ + CustomInvoicingUpdatePaymentStatusRequest: { + /** @description The trigger to be executed on the invoice. */ + trigger: components['schemas']['CustomInvoicingPaymentTrigger'] + } + /** @description Plan input for custom subscription creation (without key and version). */ + CustomPlanInput: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** @description Alignment configuration for the plan. */ + alignment?: components['schemas']['Alignment'] + /** + * Currency + * @description The currency code of the plan. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Billing cadence + * Format: duration + * @description The default billing cadence for subscriptions using this plan. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + * @example P1M + */ + billingCadence: string + /** + * Pro-rating configuration + * @description Default pro-rating configuration for subscriptions using this plan. + * @default { + * "enabled": true, + * "mode": "prorate_prices" + * } + */ + proRatingConfig?: components['schemas']['ProRatingConfig'] + /** + * Settlement mode + * @description The settlement mode of the plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + * @default credit_then_invoice + */ + settlementMode?: components['schemas']['BillingSettlementMode'] + /** + * Plan phases + * @description The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + * A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + */ + phases: components['schemas']['PlanPhase'][] + } + /** @description Change a custom subscription. */ + CustomSubscriptionChange: { + /** + * @description Timing configuration for the change, when the change should take effect. + * For changing a subscription, the accepted values depend on the subscription configuration. + */ + timing: components['schemas']['SubscriptionTiming'] + /** + * Format: date-time + * @description The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + * @example 2023-01-01T01:01:01.001Z + */ + billingAnchor?: Date + /** @description The custom plan description which defines the Subscription. */ + customPlan: components['schemas']['CustomPlanInput'] + } + /** + * Create custom + * @description Create a custom subscription. + */ + CustomSubscriptionCreate: { + /** @description The custom plan description which defines the Subscription. */ + customPlan: components['schemas']['CustomPlanInput'] + /** + * @description Timing configuration for the change, when the change should take effect. + * The default is immediate. + * @default immediate + */ + timing?: components['schemas']['SubscriptionTiming'] + /** + * @description The ID of the customer. Provide either the key or ID. Has presedence over the key. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId?: string + /** @description The key of the customer. Provide either the key or ID. */ + customerKey?: string + /** + * Format: date-time + * @description The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + * @example 2023-01-01T01:01:01.001Z + */ + billingAnchor?: Date + } + /** + * @description A customer object. + * @example { + * "id": "01G65Z755AFWAKHE12NY0CQ9FH", + * "name": "ACME Inc.", + * "usageAttribution": { + * "subjectKeys": [ + * "my_subject_key" + * ] + * }, + * "createdAt": "2024-01-01T01:01:01.001Z", + * "updatedAt": "2024-01-01T01:01:01.001Z" + * } + */ + Customer: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Key + * @description An optional unique key of the customer. + * Either key or usageAttribution.subjectKeys must be provided. + * Useful to reference the customer in external systems. + * For example, your database ID. + */ + key?: string + /** + * Usage Attribution + * @description Mapping to attribute metered usage to the customer + * Either key or usageAttribution.subjectKeys must be provided. + */ + usageAttribution?: components['schemas']['CustomerUsageAttribution'] + /** + * Primary Email + * @description The primary email address of the customer. + */ + primaryEmail?: string + /** + * Currency + * @description Currency of the customer. + * Used for billing, tax and invoicing. + */ + currency?: components['schemas']['CurrencyCode'] + /** + * Billing Address + * @description The billing address of the customer. + * Used for tax and invoicing. + */ + billingAddress?: components['schemas']['Address'] + /** + * Current Subscription ID + * @description The ID of the Subscription if the customer has one. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly currentSubscriptionId?: string + /** + * Subscriptions + * @description The subscriptions of the customer. + * Only with the `subscriptions` expand option. + */ + readonly subscriptions?: components['schemas']['Subscription'][] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + } + /** @description CustomerAccess describes what features the customer has access to. */ + CustomerAccess: { + /** + * @description Map of entitlements the customer has access to. + * The key is the feature key, the value is the entitlement value + the entitlement ID. + */ + readonly entitlements: { + [key: string]: components['schemas']['EntitlementValue'] + } + } + /** + * @description CustomerAppData + * Stores the app specific data for the customer. + * One of: stripe, sandbox, custom_invoicing + */ + CustomerAppData: + | components['schemas']['StripeCustomerAppData'] + | components['schemas']['SandboxCustomerAppData'] + | components['schemas']['CustomInvoicingCustomerAppData'] + /** + * @description CustomerAppData + * Stores the app specific data for the customer. + * One of: stripe, sandbox, custom_invoicing + */ + CustomerAppDataCreateOrUpdateItem: + | components['schemas']['StripeCustomerAppDataCreateOrUpdateItem'] + | components['schemas']['SandboxCustomerAppData'] + | components['schemas']['CustomInvoicingCustomerAppData'] + /** @description Paginated response */ + CustomerAppDataPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['CustomerAppData'][] + } + /** @description Resource create operation model. */ + CustomerCreate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Key + * @description An optional unique key of the customer. + * Either key or usageAttribution.subjectKeys must be provided. + * Useful to reference the customer in external systems. + * For example, your database ID. + */ + key?: string + /** + * Usage Attribution + * @description Mapping to attribute metered usage to the customer + * Either key or usageAttribution.subjectKeys must be provided. + */ + usageAttribution?: components['schemas']['CustomerUsageAttribution'] + /** + * Primary Email + * @description The primary email address of the customer. + */ + primaryEmail?: string + /** + * Currency + * @description Currency of the customer. + * Used for billing, tax and invoicing. + */ + currency?: components['schemas']['CurrencyCode'] + /** + * Billing Address + * @description The billing address of the customer. + * Used for tax and invoicing. + */ + billingAddress?: components['schemas']['Address'] + } + /** + * @description CustomerExpand specifies the parts of the customer to expand in the list output. + * @enum {string} + */ + CustomerExpand: 'subscriptions' + /** @description Create Stripe checkout session with customer ID. */ + CustomerId: { + /** + * @description ULID (Universally Unique Lexicographically Sortable Identifier). + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + } + /** @description Create Stripe checkout session with customer key. */ + CustomerKey: { + key: string + } + /** + * @description Order by options for customers. + * @enum {string} + */ + CustomerOrderBy: 'id' | 'name' | 'createdAt' + /** @description Paginated response */ + CustomerPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Customer'][] + } + /** @description Resource update operation model. */ + CustomerReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Key + * @description An optional unique key of the customer. + * Either key or usageAttribution.subjectKeys must be provided. + * Useful to reference the customer in external systems. + * For example, your database ID. + */ + key?: string + /** + * Usage Attribution + * @description Mapping to attribute metered usage to the customer + * Either key or usageAttribution.subjectKeys must be provided. + */ + usageAttribution?: components['schemas']['CustomerUsageAttribution'] + /** + * Primary Email + * @description The primary email address of the customer. + */ + primaryEmail?: string + /** + * Currency + * @description Currency of the customer. + * Used for billing, tax and invoicing. + */ + currency?: components['schemas']['CurrencyCode'] + /** + * Billing Address + * @description The billing address of the customer. + * Used for tax and invoicing. + */ + billingAddress?: components['schemas']['Address'] + } + /** + * @description Order by options for customer subscriptions. + * @enum {string} + */ + CustomerSubscriptionOrderBy: 'activeFrom' | 'activeTo' + /** + * @description Mapping to attribute metered usage to the customer. + * One customer can have zero or more subjects, + * but one subject can only belong to one customer. + */ + CustomerUsageAttribution: { + /** + * SubjectKeys + * @description The subjects that are attributed to the customer. + * Can be empty when no subjects are associated with the customer. + */ + subjectKeys: string[] + } + /** @description Percentage discount. */ + DiscountPercentage: { + /** + * Percentage + * @description The percentage of the discount. + */ + percentage: components['schemas']['Percentage'] + } + /** @description The reason for the discount is a maximum spend. */ + DiscountReasonMaximumSpend: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'maximum_spend' + } + /** @description The reason for the discount is a ratecard percentage. */ + DiscountReasonRatecardPercentage: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'ratecard_percentage' + /** + * Percentage + * @description The percentage of the discount. + */ + percentage: components['schemas']['Percentage'] + /** + * @description Correlation ID for the discount. + * + * This is used to link discounts across different invoices (progressive billing use case). + * + * If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + * please make sure to keep the same correlation ID of the discount or in progressive billing + * setups the discount amounts might be incorrect. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + correlationId?: string + } + /** @description The reason for the discount is a ratecard usage. */ + DiscountReasonRatecardUsage: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'ratecard_usage' + /** + * Usage + * @description The quantity of the usage discount. + * + * Must be positive. + */ + quantity: components['schemas']['Numeric'] + /** + * @description Correlation ID for the discount. + * + * This is used to link discounts across different invoices (progressive billing use case). + * + * If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + * please make sure to keep the same correlation ID of the discount or in progressive billing + * setups the discount amounts might be incorrect. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + correlationId?: string + } + /** + * @description Usage discount. + * + * Usage discount means that the first N items are free. From billing perspective + * this means that any usage on a specific feature is considered 0 until this discount + * is exhausted. + */ + DiscountUsage: { + /** + * Usage + * @description The quantity of the usage discount. + * + * Must be positive. + */ + quantity: components['schemas']['Numeric'] + } + /** @description Discount by type on a price */ + Discounts: { + /** @description The percentage discount. */ + percentage?: components['schemas']['DiscountPercentage'] + /** @description The usage discount. */ + usage?: components['schemas']['DiscountUsage'] + } + /** @description Dynamic price with spend commitments. */ + DynamicPriceWithCommitments: { + /** + * @description The type of the price. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'dynamic' + /** + * The multiplier to apply to the base price to get the dynamic price + * @description The multiplier to apply to the base price to get the dynamic price. + * + * Examples: + * - 0.0: the price is zero + * - 0.5: the price is 50% of the base price + * - 1.0: the price is the same as the base price + * - 1.5: the price is 150% of the base price + * @default 1 + */ + multiplier?: components['schemas']['Numeric'] + /** + * Minimum amount + * @description The customer is committed to spend at least the amount. + */ + minimumAmount?: components['schemas']['Numeric'] + /** + * Maximum amount + * @description The customer is limited to spend at most the amount. + */ + maximumAmount?: components['schemas']['Numeric'] + } + /** @description Add a new item to a phase. */ + EditSubscriptionAddItem: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + op: 'add_item' + phaseKey: string + rateCard: components['schemas']['RateCard'] + } + /** @description Add a new phase */ + EditSubscriptionAddPhase: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + op: 'add_phase' + phase: components['schemas']['SubscriptionPhaseCreate'] + } + /** @description Remove an item from a phase. */ + EditSubscriptionRemoveItem: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + op: 'remove_item' + phaseKey: string + itemKey: string + } + /** @description Remove a phase */ + EditSubscriptionRemovePhase: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + op: 'remove_phase' + phaseKey: string + shift: components['schemas']['RemovePhaseShifting'] + } + /** @description Stretch a phase */ + EditSubscriptionStretchPhase: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + op: 'stretch_phase' + phaseKey: string + /** Format: duration */ + extendBy: string + } + /** @description Unschedules any edits from the current phase. */ + EditSubscriptionUnscheduleEdit: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + op: 'unschedule_edit' + } + /** + * @deprecated + * @description Entitlement templates are used to define the entitlements of a plan. + * Features are omitted from the entitlement template, as they are defined in the rate card. + */ + Entitlement: + | components['schemas']['EntitlementMetered'] + | components['schemas']['EntitlementStatic'] + | components['schemas']['EntitlementBoolean'] + /** + * @deprecated + * @description Entitlement template of a boolean entitlement. + */ + EntitlementBoolean: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'boolean' + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The annotations of the entitlement. + * @example { + * "subscription.id": "sub_123" + * } + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The identifier key unique to the subject. + * NOTE: Subjects are being deprecated, please use the new customer APIs. + * @example customer-1 + */ + subjectKey: string + /** + * @description The feature the subject is entitled to use. + * @example example-feature-key + */ + featureKey: string + /** + * @description The feature the subject is entitled to use. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId: string + /** @description The current usage period. */ + currentUsagePeriod?: components['schemas']['Period'] + /** @description The defined usage period of the entitlement */ + usagePeriod?: components['schemas']['RecurringPeriod'] + } + /** + * @deprecated + * @description Create inputs for boolean entitlement + */ + EntitlementBooleanCreateInputs: { + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example example-feature-key + */ + featureKey?: string + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId?: string + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** @description The usage period associated with the entitlement. */ + usagePeriod?: components['schemas']['RecurringPeriodCreateInput'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'boolean' + } + /** @description Entitlement template of a boolean entitlement. */ + EntitlementBooleanV2: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'boolean' + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The annotations of the entitlement. + * @example { + * "subscription.id": "sub_123" + * } + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The feature the subject is entitled to use. + * @example example-feature-key + */ + featureKey: string + /** + * @description The feature the subject is entitled to use. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId: string + /** @description The current usage period. */ + currentUsagePeriod?: components['schemas']['Period'] + /** @description The defined usage period of the entitlement */ + usagePeriod?: components['schemas']['RecurringPeriod'] + /** + * @description The identifier key unique to the customer + * @example customer-1 + */ + customerKey?: string + /** + * @description The identifier unique to the customer + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + customerId: string + } + /** @description Create inputs for entitlement */ + EntitlementCreateInputs: + | components['schemas']['EntitlementMeteredCreateInputs'] + | components['schemas']['EntitlementStaticCreateInputs'] + | components['schemas']['EntitlementBooleanCreateInputs'] + /** + * @deprecated + * @description The grant. + */ + EntitlementGrant: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Format: double + * @description The amount to grant. Should be a positive number. + * @example 100 + */ + amount: number + /** + * Format: uint8 + * @description The priority of the grant. Grants with higher priority are applied first. + * Priority is a positive decimal numbers. With lower numbers indicating higher importance. + * For example, a priority of 1 is more urgent than a priority of 2. + * When there are several grants available for the same subject, the system selects the grant with the highest priority. + * In cases where grants share the same priority level, the grant closest to its expiration will be used first. + * In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + * @example 1 + */ + priority?: number + /** + * Format: date-time + * @description Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + * @example 2023-01-01T01:01:01.001Z + */ + effectiveAt: Date + /** @description The grant expiration definition */ + expiration: components['schemas']['ExpirationPeriod'] + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @default 0 + * @example 100 + */ + maxRolloverAmount?: number + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @default 0 + * @example 100 + */ + minRolloverAmount?: number + /** + * @description The grant metadata. + * @example { + * "stripePaymentId": "pi_4OrAkhLvyihio9p51h9iiFnB" + * } + */ + metadata?: components['schemas']['Metadata'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The unique entitlement ULID that the grant is associated with. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly entitlementId: string + /** + * Format: date-time + * @description The next time the grant will recurr. + * @example 2023-01-01T01:01:01.001Z + */ + nextRecurrence?: Date + /** + * Format: date-time + * @description The time the grant expires. + * @example 2023-01-01T01:01:01.001Z + */ + readonly expiresAt?: Date + /** + * Format: date-time + * @description The time the grant was voided. + * @example 2023-01-01T01:01:01.001Z + */ + voidedAt?: Date + /** @description The recurrence period of the grant. */ + recurrence?: components['schemas']['RecurringPeriod'] + /** + * @description Grant annotations + * @example { + * "issueAfterReset": true + * } + */ + annotations?: components['schemas']['Annotations'] + } + /** + * @deprecated + * @description The grant creation input. + */ + EntitlementGrantCreateInput: { + /** + * Format: double + * @description The amount to grant. Should be a positive number. + * @example 100 + */ + amount: number + /** + * Format: uint8 + * @description The priority of the grant. Grants with higher priority are applied first. + * Priority is a positive decimal numbers. With lower numbers indicating higher importance. + * For example, a priority of 1 is more urgent than a priority of 2. + * When there are several grants available for the same subject, the system selects the grant with the highest priority. + * In cases where grants share the same priority level, the grant closest to its expiration will be used first. + * In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + * @example 1 + */ + priority?: number + /** + * Format: date-time + * @description Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + * @example 2023-01-01T01:01:01.001Z + */ + effectiveAt: Date + /** @description The grant expiration definition */ + expiration: components['schemas']['ExpirationPeriod'] + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @default 0 + * @example 100 + */ + maxRolloverAmount?: number + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @default 0 + * @example 100 + */ + minRolloverAmount?: number + /** + * @description The grant metadata. + * @example { + * "stripePaymentId": "pi_4OrAkhLvyihio9p51h9iiFnB" + * } + */ + metadata?: components['schemas']['Metadata'] + /** @description The subject of the grant. */ + recurrence?: components['schemas']['RecurringPeriodCreateInput'] + } + /** @description The grant creation input. */ + EntitlementGrantCreateInputV2: { + /** + * Format: double + * @description The amount to grant. Should be a positive number. + * @example 100 + */ + amount: number + /** + * Format: uint8 + * @description The priority of the grant. Grants with higher priority are applied first. + * Priority is a positive decimal numbers. With lower numbers indicating higher importance. + * For example, a priority of 1 is more urgent than a priority of 2. + * When there are several grants available for the same subject, the system selects the grant with the highest priority. + * In cases where grants share the same priority level, the grant closest to its expiration will be used first. + * In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + * @example 1 + */ + priority?: number + /** + * Format: date-time + * @description Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + * @example 2023-01-01T01:01:01.001Z + */ + effectiveAt: Date + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @default 0 + * @example 100 + */ + minRolloverAmount?: number + /** + * @description The grant metadata. + * @example { + * "stripePaymentId": "pi_4OrAkhLvyihio9p51h9iiFnB" + * } + */ + metadata?: components['schemas']['Metadata'] + /** @description The subject of the grant. */ + recurrence?: components['schemas']['RecurringPeriodCreateInput'] + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @example 100 + */ + maxRolloverAmount?: number + /** @description The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. */ + expiration?: components['schemas']['ExpirationPeriod'] + /** + * @description Grant annotations + * @example { + * "internal_reference": "internal_reference" + * } + */ + annotations?: components['schemas']['Annotations'] + } + /** @description The grant. */ + EntitlementGrantV2: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Format: double + * @description The amount to grant. Should be a positive number. + * @example 100 + */ + amount: number + /** + * Format: uint8 + * @description The priority of the grant. Grants with higher priority are applied first. + * Priority is a positive decimal numbers. With lower numbers indicating higher importance. + * For example, a priority of 1 is more urgent than a priority of 2. + * When there are several grants available for the same subject, the system selects the grant with the highest priority. + * In cases where grants share the same priority level, the grant closest to its expiration will be used first. + * In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + * @example 1 + */ + priority?: number + /** + * Format: date-time + * @description Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + * @example 2023-01-01T01:01:01.001Z + */ + effectiveAt: Date + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @default 0 + * @example 100 + */ + minRolloverAmount?: number + /** + * @description The grant metadata. + * @example { + * "stripePaymentId": "pi_4OrAkhLvyihio9p51h9iiFnB" + * } + */ + metadata?: components['schemas']['Metadata'] + /** + * Format: double + * @description Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * @example 100 + */ + maxRolloverAmount?: number + /** @description The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. */ + expiration?: components['schemas']['ExpirationPeriod'] + /** + * @description Grant annotations + * @example { + * "internal_reference": "internal_reference" + * } + */ + annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The unique entitlement ULID that the grant is associated with. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly entitlementId: string + /** + * Format: date-time + * @description The next time the grant will recurr. + * @example 2023-01-01T01:01:01.001Z + */ + nextRecurrence?: Date + /** + * Format: date-time + * @description The time the grant expires. + * @example 2023-01-01T01:01:01.001Z + */ + readonly expiresAt?: Date + /** + * Format: date-time + * @description The time the grant was voided. + * @example 2023-01-01T01:01:01.001Z + */ + voidedAt?: Date + /** @description The recurrence period of the grant. */ + recurrence?: components['schemas']['RecurringPeriod'] + } + /** + * @deprecated + * @description Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + * Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + */ + EntitlementMetered: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'metered' + /** + * Soft limit + * @description If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + * @default false + */ + isSoftLimit?: boolean + /** + * @deprecated + * @description Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + * @default false + */ + isUnlimited?: boolean + /** + * Initial grant amount + * Format: double + * @description You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + issueAfterReset?: number + /** + * Issue grant after reset priority + * Format: uint8 + * @description Defines the grant priority for the default grant. + * @default 1 + */ + issueAfterResetPriority?: number + /** + * Preserve overage at reset + * @description If true, the overage is preserved at reset. If false, the usage is reset to 0. + * @default false + */ + preserveOverageAtReset?: boolean + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The annotations of the entitlement. + * @example { + * "subscription.id": "sub_123" + * } + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The identifier key unique to the subject. + * NOTE: Subjects are being deprecated, please use the new customer APIs. + * @example customer-1 + */ + subjectKey: string + /** + * @description The feature the subject is entitled to use. + * @example example-feature-key + */ + featureKey: string + /** + * @description The feature the subject is entitled to use. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId: string + /** + * Format: date-time + * @description The time the last reset happened. + * @example 2023-01-01T01:01:01.001Z + */ + readonly lastReset: Date + /** @description The current usage period. */ + readonly currentUsagePeriod: components['schemas']['Period'] + /** + * Format: date-time + * @description The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + * @example 2023-01-01T01:01:01.001Z + */ + readonly measureUsageFrom: Date + /** @description THe usage period of the entitlement. */ + readonly usagePeriod: components['schemas']['RecurringPeriod'] + } + /** + * @deprecated + * @description Create inpurs for metered entitlement + */ + EntitlementMeteredCreateInputs: { + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example example-feature-key + */ + featureKey?: string + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId?: string + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'metered' + /** + * Soft limit + * @description If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + * @default false + */ + isSoftLimit?: boolean + /** + * @deprecated + * @description Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + * @default false + */ + isUnlimited?: boolean + /** @description The usage period associated with the entitlement. */ + usagePeriod: components['schemas']['RecurringPeriodCreateInput'] + /** @description Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. */ + measureUsageFrom?: components['schemas']['MeasureUsageFrom'] + /** + * Initial grant amount + * Format: double + * @description You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + issueAfterReset?: number + /** + * Issue grant after reset priority + * Format: uint8 + * @description Defines the grant priority for the default grant. + * @default 1 + */ + issueAfterResetPriority?: number + /** + * Preserve overage at reset + * @description If true, the overage is preserved at reset. If false, the usage is reset to 0. + * @default false + */ + preserveOverageAtReset?: boolean + } + /** + * @description Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + * Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + */ + EntitlementMeteredV2: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'metered' + /** + * Soft limit + * @description If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + * @default false + */ + isSoftLimit?: boolean + /** + * Preserve overage at reset + * @description If true, the overage is preserved at reset. If false, the usage is reset to 0. + * @default false + */ + preserveOverageAtReset?: boolean + /** + * Initial grant amount + * Format: double + * @deprecated + * @description You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + issueAfterReset?: number + /** + * Issue grant after reset priority + * Format: uint8 + * @deprecated + * @description Defines the grant priority for the default grant. + * @default 1 + */ + issueAfterResetPriority?: number + /** + * Issue after reset + * @description Issue after reset + */ + issue?: components['schemas']['IssueAfterReset'] + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The annotations of the entitlement. + * @example { + * "subscription.id": "sub_123" + * } + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The feature the subject is entitled to use. + * @example example-feature-key + */ + featureKey: string + /** + * @description The feature the subject is entitled to use. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId: string + /** + * Format: date-time + * @description The time the last reset happened. + * @example 2023-01-01T01:01:01.001Z + */ + readonly lastReset: Date + /** @description The current usage period. */ + readonly currentUsagePeriod: components['schemas']['Period'] + /** + * Format: date-time + * @description The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + * @example 2023-01-01T01:01:01.001Z + */ + readonly measureUsageFrom: Date + /** @description THe usage period of the entitlement. */ + readonly usagePeriod: components['schemas']['RecurringPeriod'] + /** + * @description The identifier key unique to the customer + * @example customer-1 + */ + customerKey?: string + /** + * @description The identifier unique to the customer + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + customerId: string + } + /** @description Create inputs for metered entitlement */ + EntitlementMeteredV2CreateInputs: { + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example example-feature-key + */ + featureKey?: string + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId?: string + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'metered' + /** + * Soft limit + * @description If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + * @default false + */ + isSoftLimit?: boolean + /** @description The usage period associated with the entitlement. */ + usagePeriod: components['schemas']['RecurringPeriodCreateInput'] + /** @description Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. */ + measureUsageFrom?: components['schemas']['MeasureUsageFrom'] + /** + * Preserve overage at reset + * @description If true, the overage is preserved at reset. If false, the usage is reset to 0. + * @default false + */ + preserveOverageAtReset?: boolean + /** + * Initial grant amount + * Format: double + * @deprecated + * @description You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + issueAfterReset?: number + /** + * Issue grant after reset priority + * Format: uint8 + * @deprecated + * @description Defines the grant priority for the default grant. + * @default 1 + */ + issueAfterResetPriority?: number + /** + * Issue after reset + * @description Issue after reset + */ + issue?: components['schemas']['IssueAfterReset'] + /** + * Grants + * @description Grants + */ + grants?: components['schemas']['EntitlementGrantCreateInputV2'][] + } + /** + * @description Order by options for entitlements. + * @enum {string} + */ + EntitlementOrderBy: 'createdAt' | 'updatedAt' + /** @description Paginated response */ + EntitlementPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Entitlement'][] + } + /** + * @deprecated + * @description A static entitlement. + */ + EntitlementStatic: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'static' + /** + * Format: json + * @description The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + * @example { "integrations": ["github"] } + */ + config: string + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The annotations of the entitlement. + * @example { + * "subscription.id": "sub_123" + * } + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The identifier key unique to the subject. + * NOTE: Subjects are being deprecated, please use the new customer APIs. + * @example customer-1 + */ + subjectKey: string + /** + * @description The feature the subject is entitled to use. + * @example example-feature-key + */ + featureKey: string + /** + * @description The feature the subject is entitled to use. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId: string + /** @description The current usage period. */ + currentUsagePeriod?: components['schemas']['Period'] + /** @description The defined usage period of the entitlement */ + usagePeriod?: components['schemas']['RecurringPeriod'] + } + /** + * @deprecated + * @description Create inputs for static entitlement + */ + EntitlementStaticCreateInputs: { + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example example-feature-key + */ + featureKey?: string + /** + * @description The feature the subject is entitled to use. + * Either featureKey or featureId is required. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId?: string + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** @description The usage period associated with the entitlement. */ + usagePeriod?: components['schemas']['RecurringPeriodCreateInput'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'static' + /** + * Format: json + * @description The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + * @example { "integrations": ["github"] } + */ + config: string + } + /** @description A static entitlement. */ + EntitlementStaticV2: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'static' + /** + * Format: json + * @description The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + * @example { "integrations": ["github"] } + */ + config: string + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The annotations of the entitlement. + * @example { + * "subscription.id": "sub_123" + * } + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description The feature the subject is entitled to use. + * @example example-feature-key + */ + featureKey: string + /** + * @description The feature the subject is entitled to use. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + featureId: string + /** @description The current usage period. */ + currentUsagePeriod?: components['schemas']['Period'] + /** @description The defined usage period of the entitlement */ + usagePeriod?: components['schemas']['RecurringPeriod'] + /** + * @description The identifier key unique to the customer + * @example customer-1 + */ + customerKey?: string + /** + * @description The identifier unique to the customer + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + customerId: string + } + /** + * @deprecated + * @description Type of the entitlement. + * @enum {string} + */ + EntitlementType: 'metered' | 'boolean' | 'static' + /** + * @description Entitlement templates are used to define the entitlements of a plan. + * Features are omitted from the entitlement template, as they are defined in the rate card. + */ + EntitlementV2: + | components['schemas']['EntitlementMeteredV2'] + | components['schemas']['EntitlementStaticV2'] + | components['schemas']['EntitlementBooleanV2'] + /** @description Create inputs for entitlement */ + EntitlementV2CreateInputs: + | components['schemas']['EntitlementMeteredV2CreateInputs'] + | components['schemas']['EntitlementStaticCreateInputs'] + | components['schemas']['EntitlementBooleanCreateInputs'] + /** @description Paginated response */ + EntitlementV2PaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['EntitlementV2'][] + } + /** @description Entitlements are the core of OpenMeter access management. They define access to features for subjects. Entitlements can be metered, boolean, or static. */ + EntitlementValue: { + /** + * @description Whether the subject has access to the feature. Shared accross all entitlement types. + * @example true + */ + readonly hasAccess: boolean + /** + * Format: double + * @description Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + * @example 100 + */ + readonly balance?: number + /** + * Format: double + * @description Only available for metered entitlements. Returns the total feature usage in the current period. + * @example 50 + */ + readonly usage?: number + /** + * Format: double + * @description Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + * @example 0 + */ + readonly overage?: number + /** + * Format: double + * @description Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + * @example 100 + */ + readonly totalAvailableGrantAmount?: number + /** + * @description Only available for static entitlements. The JSON parsable config of the entitlement. + * @example { key: "value" } + */ + readonly config?: string + } + /** @description EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 APIs. */ + EntitlementValueV2: { + /** + * @description Whether the subject has access to the feature. Shared accross all entitlement types. + * @example true + */ + readonly hasAccess: boolean + /** + * Format: double + * @description Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + * @example 100 + */ + readonly balance?: number + /** + * Format: double + * @description Only available for metered entitlements. Returns the total feature usage in the current period. + * @example 50 + */ + readonly usage?: number + /** + * Format: double + * @description Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + * @example 0 + */ + readonly overage?: number + /** + * Format: double + * @description Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + * @example 100 + */ + readonly totalAvailableGrantAmount?: number + /** + * @description Only available for static entitlements. The JSON parsable config of the entitlement. + * @example { key: "value" } + */ + readonly config?: string + /** + * @description Only available for metered entitlements. The closing balance of each active grant at query time. + * The key is the grant ID and the value is the remaining balance. + */ + readonly grantBalances?: { + [key: string]: number + } + } + /** @description Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode] */ + ErrorExtension: { + /** + * @description The path to the field. + * @example addons/pro/ratecards/token/featureKey + */ + readonly field: string + /** + * @description The machine readable description of the error. + * @example invalid_feature_key + */ + readonly code: string + /** + * @description The human readable description of the error. + * @example not found feature by key + */ + readonly message: string + } & { + [key: string]: unknown + } + /** + * @description CloudEvents Specification JSON Schema + * + * Optional properties are nullable according to the CloudEvents specification: + * OPTIONAL not omitted attributes MAY be represented as a null JSON value. + * @example { + * "id": "5c10fade-1c9e-4d6c-8275-c52c36731d3c", + * "source": "service-name", + * "specversion": "1.0", + * "type": "prompt", + * "subject": "customer-id", + * "time": "2023-01-01T01:01:01.001Z" + * } + */ + Event: { + /** + * @description Identifies the event. + * @example 5c10fade-1c9e-4d6c-8275-c52c36731d3c + */ + id?: string + /** + * Format: uri-reference + * @description Identifies the context in which an event happened. + * @example service-name + */ + source?: string + /** + * @description The version of the CloudEvents specification which the event uses. + * @default 1.0 + * @example 1.0 + */ + specversion?: string + /** + * @description Contains a value describing the type of event related to the originating occurrence. + * @example com.example.someevent + */ + type: string + /** + * @description Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP. + * @example application/json + * @enum {string|null} + */ + datacontenttype?: 'application/json' | null + /** + * Format: uri + * @description Identifies the schema that data adheres to. + */ + dataschema?: string | null + /** + * @description Describes the subject of the event in the context of the event producer (identified by source). + * @example customer-id + */ + subject: string + /** + * Format: date-time + * @description Timestamp of when the occurrence happened. Must adhere to RFC 3339. + * @example 2023-01-01T01:01:01.001Z + */ + time?: Date | null + /** + * @description The event payload. + * Optional, if present it must be a JSON object. + */ + data?: { + [key: string]: unknown + } | null + } + /** @description The response of the event delivery attempt. */ + EventDeliveryAttemptResponse: { + /** + * Status Code + * @description Status code of the response if available. + */ + readonly statusCode?: number + /** + * Response Body + * @description The body of the response. + */ + readonly body: string + /** + * Response Duration + * @description The duration of the response in milliseconds. + */ + readonly durationMs: number + /** + * URL + * @description URL where the event was sent in case of notification channel with webhook type. + */ + readonly url?: string + } + /** + * @description The expiration duration enum + * @enum {string} + */ + ExpirationDuration: 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR' + /** @description The grant expiration definition */ + ExpirationPeriod: { + /** @description The unit of time for the expiration period. */ + duration: components['schemas']['ExpirationDuration'] + /** + * Format: uint32 + * @description The number of time units in the expiration period. + * @example 12 + */ + count: number + } + /** + * @description Represents a feature that can be enabled or disabled for a plan. + * Used both for product catalog and entitlements. + */ + Feature: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Archival Time + * Format: date-time + * @description Timestamp of when the resource was archived. + * @example 2023-01-01T01:01:01.001Z + */ + readonly archivedAt?: Date + /** + * The unique key of the feature + * @description A key is a unique string that is used to identify a resource. + */ + key: string + /** The human-readable name of the feature */ + name: string + /** + * Optional metadata + * @example { + * "key": "value" + * } + */ + metadata?: components['schemas']['Metadata'] + /** + * Meter slug + * @description A key is a unique string that is used to identify a resource. + * @example tokens_total + */ + meterSlug?: string + /** + * Meter group by filters + * @deprecated + * @description Optional meter group by filters. + * Useful if the meter scope is broader than what feature tracks. + * Example scenario would be a meter tracking all token use with groupBy fields for the model, + * then the feature could filter for model=gpt-4. + * + * ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + * @example { + * "model": "gpt-4", + * "type": "input" + * } + */ + meterGroupByFilters?: { + [key: string]: string + } + /** + * Advanced meter group by filters + * @description Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + * @example { + * "model": { + * "$in": [ + * "gpt-4", + * "gpt-4o" + * ] + * }, + * "type": { + * "$eq": "input" + * } + * } + */ + advancedMeterGroupByFilters?: { + [key: string]: components['schemas']['FilterString'] + } + /** + * Unit cost + * @description Optional per-unit cost configuration. + * Use "manual" for a fixed per-unit cost, or "llm" to look up cost + * from the LLM cost database based on meter group-by properties. + */ + unitCost?: components['schemas']['FeatureUnitCost'] + /** + * @description Readonly unique ULID identifier. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + } + /** + * @description Represents a feature that can be enabled or disabled for a plan. + * Used both for product catalog and entitlements. + */ + FeatureCreateInputs: { + /** + * The unique key of the feature + * @description A key is a unique string that is used to identify a resource. + */ + key: string + /** The human-readable name of the feature */ + name: string + /** + * Optional metadata + * @example { + * "key": "value" + * } + */ + metadata?: components['schemas']['Metadata'] + /** + * Meter slug + * @description A key is a unique string that is used to identify a resource. + * @example tokens_total + */ + meterSlug?: string + /** + * Meter group by filters + * @deprecated + * @description Optional meter group by filters. + * Useful if the meter scope is broader than what feature tracks. + * Example scenario would be a meter tracking all token use with groupBy fields for the model, + * then the feature could filter for model=gpt-4. + * + * ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + * @example { + * "model": "gpt-4", + * "type": "input" + * } + */ + meterGroupByFilters?: { + [key: string]: string + } + /** + * Advanced meter group by filters + * @description Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + * @example { + * "model": { + * "$in": [ + * "gpt-4", + * "gpt-4o" + * ] + * }, + * "type": { + * "$eq": "input" + * } + * } + */ + advancedMeterGroupByFilters?: { + [key: string]: components['schemas']['FilterString'] + } + /** + * Unit cost + * @description Optional per-unit cost configuration. + * Use "manual" for a fixed per-unit cost, or "llm" to look up cost + * from the LLM cost database based on meter group-by properties. + */ + unitCost?: components['schemas']['FeatureUnitCost'] + } + /** + * @description LLM cost lookup configuration. + * Maps meter group-by dimensions to LLM cost database fields. + */ + FeatureLLMUnitCost: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'llm' + /** + * Provider property + * @description Meter group-by property that holds the LLM provider. + * Use this when the meter has a group-by dimension for provider. + * Mutually exclusive with `provider`. + */ + providerProperty?: string + /** + * Provider + * @description Static LLM provider value (e.g., "openai", "anthropic"). + * Use this when the feature tracks a single provider. + * Mutually exclusive with `providerProperty`. + */ + provider?: string + /** + * Model property + * @description Meter group-by property that holds the model ID. + * Use this when the meter has a group-by dimension for model. + * Mutually exclusive with `model`. + */ + modelProperty?: string + /** + * Model + * @description Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). + * Use this when the feature tracks a single model. + * Mutually exclusive with `modelProperty`. + */ + model?: string + /** + * Token type property + * @description Meter group-by property that holds the token type. + * Use this when the meter has a group-by dimension for token type. + * Mutually exclusive with `tokenType`. + */ + tokenTypeProperty?: string + /** + * Token type + * @description Static token type value. + * Use this when the feature tracks a single token type (e.g., only input tokens). + * Expected values: input, output, cache_read, reasoning, cache_write, request, response. + * `request` is an alias for `input`, `response` is an alias for `output`. + * Mutually exclusive with `tokenTypeProperty`. + */ + tokenType?: string + /** + * Resolved pricing + * @description Resolved per-token pricing from the LLM cost database. + * Only populated in responses when the feature's meter group-by filters + * specify exact provider and model values. + */ + readonly pricing?: components['schemas']['FeatureLLMUnitCostPricing'] + } + /** @description Resolved per-token pricing from the LLM cost database. */ + FeatureLLMUnitCostPricing: { + /** + * Input per token + * @description Cost per input token in USD. + */ + inputPerToken: components['schemas']['Numeric'] + /** + * Output per token + * @description Cost per output token in USD. + */ + outputPerToken: components['schemas']['Numeric'] + /** + * Cache read per token + * @description Cost per cache read token in USD. + */ + cacheReadPerToken?: components['schemas']['Numeric'] + /** + * Reasoning per token + * @description Cost per reasoning token in USD. + */ + reasoningPerToken?: components['schemas']['Numeric'] + /** + * Cache write per token + * @description Cost per cache write token in USD. + */ + cacheWritePerToken?: components['schemas']['Numeric'] + } + /** @description A fixed per-unit cost amount. */ + FeatureManualUnitCost: { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'manual' + /** @description Fixed per-unit cost amount in USD. */ + amount: components['schemas']['Numeric'] + } + /** @description Limited representation of a feature resource which includes only its unique identifiers (id, key). */ + FeatureMeta: { + /** + * Feature Unique Identifier + * @description Unique identifier of a feature. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + id: string + /** + * Feature Key + * @description The key is an immutable unique identifier of the feature used throughout the API, + * for example when interacting with a subject's entitlements. + * @example gpt4_tokens + */ + key: string + } + /** + * @description Order by options for features. + * @enum {string} + */ + FeatureOrderBy: 'id' | 'key' | 'name' | 'createdAt' | 'updatedAt' + /** @description Paginated response */ + FeaturePaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Feature'][] + } + /** + * @description Per-unit cost configuration for a feature. + * Either a fixed manual amount or a dynamic LLM cost lookup. + */ + FeatureUnitCost: + | components['schemas']['FeatureManualUnitCost'] + | components['schemas']['FeatureLLMUnitCost'] + /** @description A filter for a ID (ULID) field allowing only equality or inclusion. */ + FilterIDExact: { + /** @description The field must be in the provided list of values. */ + $in?: string[] | null + } + /** @description A filter for a string field. */ + FilterString: { + /** @description The field must be equal to the provided value. */ + $eq?: string | null + /** @description The field must not be equal to the provided value. */ + $ne?: string | null + /** @description The field must be in the provided list of values. */ + $in?: string[] | null + /** @description The field must not be in the provided list of values. */ + $nin?: string[] | null + /** @description The field must match the provided value. */ + $like?: string | null + /** @description The field must not match the provided value. */ + $nlike?: string | null + /** @description The field must match the provided value, ignoring case. */ + $ilike?: string | null + /** @description The field must not match the provided value, ignoring case. */ + $nilike?: string | null + /** @description The field must be greater than the provided value. */ + $gt?: string | null + /** @description The field must be greater than or equal to the provided value. */ + $gte?: string | null + /** @description The field must be less than the provided value. */ + $lt?: string | null + /** @description The field must be less than or equal to the provided value. */ + $lte?: string | null + /** @description Provide a list of filters to be combined with a logical AND. */ + $and?: components['schemas']['FilterString'][] | null + /** @description Provide a list of filters to be combined with a logical OR. */ + $or?: components['schemas']['FilterString'][] | null + } + /** @description A filter for a time field. */ + FilterTime: { + /** + * Format: date-time + * @description The field must be greater than the provided value. + */ + $gt?: Date | null + /** + * Format: date-time + * @description The field must be greater than or equal to the provided value. + */ + $gte?: Date | null + /** + * Format: date-time + * @description The field must be less than the provided value. + */ + $lt?: Date | null + /** + * Format: date-time + * @description The field must be less than or equal to the provided value. + */ + $lte?: Date | null + /** @description Provide a list of filters to be combined with a logical AND. */ + $and?: components['schemas']['FilterTime'][] | null + /** @description Provide a list of filters to be combined with a logical OR. */ + $or?: components['schemas']['FilterTime'][] | null + } + /** @description Flat price. */ + FlatPrice: { + /** + * @description The type of the price. + * @enum {string} + */ + type: 'flat' + /** @description The amount of the flat price. */ + amount: components['schemas']['Numeric'] + } + /** @description Flat price with payment term. */ + FlatPriceWithPaymentTerm: { + /** + * @description The type of the price. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'flat' + /** @description The amount of the flat price. */ + amount: components['schemas']['Numeric'] + /** + * @description The payment term of the flat price. + * Defaults to in advance. + * @default in_advance + */ + paymentTerm?: components['schemas']['PricePaymentTerm'] + } + /** @description The server understood the request but refuses to authorize it. */ + ForbiddenProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** @description The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. */ + GatewayTimeoutProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** + * @description A segment of the grant burn down history. + * + * A given segment represents the usage of a grant between events that changed either the grant burn down priority order or the usag period. + */ + GrantBurnDownHistorySegment: { + /** @description The period of the segment. */ + period: components['schemas']['Period'] + /** + * Format: double + * @description The total usage of the grant in the period. + * @example 100 + */ + readonly usage: number + /** + * Format: double + * @description Overuse that wasn't covered by grants. + * @example 100 + */ + readonly overage: number + /** + * Format: double + * @description entitlement balance at the start of the period. + * @example 100 + */ + readonly balanceAtStart: number + /** + * @description The balance breakdown of each active grant at the start of the period: GrantID: Balance + * @example { + * "01G65Z755AFWAKHE12NY0CQ9FH": 100 + * } + */ + readonly grantBalancesAtStart: { + [key: string]: number + } + /** + * Format: double + * @description The entitlement balance at the end of the period. + * @example 100 + */ + readonly balanceAtEnd: number + /** + * @description The balance breakdown of each active grant at the end of the period: GrantID: Balance + * @example { + * "01G65Z755AFWAKHE12NY0CQ9FH": 100 + * } + */ + readonly grantBalancesAtEnd: { + [key: string]: number + } + /** @description Which grants were actually burnt down in the period and by what amount. */ + readonly grantUsages: components['schemas']['GrantUsageRecord'][] + } + /** + * @description Order by options for grants. + * @enum {string} + */ + GrantOrderBy: 'id' | 'createdAt' | 'updatedAt' + /** @description Paginated response */ + GrantPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['EntitlementGrant'][] + } + /** @description Usage Record */ + GrantUsageRecord: { + /** + * @description The id of the grant + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + grantId: string + /** + * Format: double + * @description The usage in the period + * @example 100 + */ + usage: number + } + /** @description Paginated response */ + GrantV2PaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['EntitlementGrantV2'][] + } + /** @description IDResource is a resouce with an ID. */ + IDResource: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + } + /** + * @description The body of the events request. + * Either a single event or a batch of events. + */ + IngestEventsBody: + | components['schemas']['Event'] + | components['schemas']['Event'][] + /** + * @description An ingested event with optional validation error. + * @example { + * "event": { + * "id": "5c10fade-1c9e-4d6c-8275-c52c36731d3c", + * "source": "service-name", + * "specversion": "1.0", + * "type": "prompt", + * "subject": "customer-id", + * "time": "2023-01-01T01:01:01.001Z" + * }, + * "ingestedAt": "2023-01-01T01:01:01.001Z", + * "storedAt": "2023-01-01T01:01:02.001Z" + * } + */ + IngestedEvent: { + /** @description The original event ingested. */ + event: components['schemas']['Event'] + /** + * @description The customer ID if the event is associated with a customer. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId?: string + /** @description The validation error if the event failed validation. */ + validationError?: string + /** + * Format: date-time + * @description The date and time the event was ingested. + * @example 2023-01-01T01:01:01.001Z + */ + ingestedAt: Date + /** + * Format: date-time + * @description The date and time the event was stored. + * @example 2023-01-01T01:01:01.001Z + */ + storedAt: Date + } + /** @description A response for cursor pagination. */ + IngestedEventCursorPaginatedResponse: { + /** @description The items in the response. */ + items: components['schemas']['IngestedEvent'][] + /** @description The cursor of the last item in the list. */ + nextCursor?: string + } + /** + * @description Install method of the application. + * @enum {string} + */ + InstallMethod: 'with_oauth2' | 'with_api_key' | 'no_credentials_required' + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + InternalServerErrorProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** @description Invoice represents an invoice in the system. */ + Invoice: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description Type of the invoice. + * + * The type of invoice determines the purpose of the invoice and how it should be handled. + * + * Supported types: + * - standard: A regular commercial invoice document between a supplier and customer. + * - credit_note: Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + */ + readonly type: components['schemas']['InvoiceType'] + /** @description The taxable entity supplying the goods or services. */ + supplier: components['schemas']['BillingParty'] + /** @description Legal entity receiving the goods or services. */ + customer: components['schemas']['BillingInvoiceCustomerExtendedDetails'] + /** + * @description Number specifies the human readable key used to reference this Invoice. + * + * The invoice number can change in the draft phases, as we are allocating temporary draft + * invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + * + * Please note that the number is (depending on the upstream settings) either unique for the + * whole organization or unique for the customer, or in multi (stripe) account setups unique for the + * account. + */ + readonly number: components['schemas']['InvoiceNumber'] + /** + * @description Currency for all invoice line items. + * + * Multi currency invoices are not supported yet. + */ + currency: components['schemas']['CurrencyCode'] + /** @description Key information regarding previous invoices and potentially details as to why they were corrected. */ + readonly preceding?: components['schemas']['InvoiceDocumentRef'][] + /** @description Summary of all the invoice totals, including taxes (calculated). */ + readonly totals: components['schemas']['InvoiceTotals'] + /** + * @description The status of the invoice. + * + * This field only conatins a simplified status, for more detailed information use the statusDetails field. + */ + readonly status: components['schemas']['InvoiceStatus'] + /** @description The details of the current invoice status. */ + readonly statusDetails: components['schemas']['InvoiceStatusDetails'] + /** + * Format: date-time + * @description The time the invoice was issued. + * + * Depending on the status of the invoice this can mean multiple things: + * - draft, gathering: The time the invoice will be issued based on the workflow settings. + * - issued: The time the invoice was issued. + * @example 2023-01-01T01:01:01.001Z + */ + readonly issuedAt?: Date + /** + * Format: date-time + * @description The time until the invoice is in draft status. + * + * On draft invoice creation it is calculated from the workflow settings. + * + * If manual approval is required, the draftUntil time is set. + * @example 2023-01-01T01:01:01.001Z + */ + draftUntil?: Date + /** + * Format: date-time + * @description The time when the quantity snapshots on the invoice lines were taken. + * @example 2023-01-01T01:01:01.001Z + */ + readonly quantitySnapshotedAt?: Date + /** + * Format: date-time + * @description The time when the invoice will be/has been collected. + * @example 2023-01-01T01:01:01.001Z + */ + readonly collectionAt?: Date + /** + * Format: date-time + * @description Due time of the fulfillment of the invoice (if available). + * @example 2023-01-01T01:01:01.001Z + */ + readonly dueAt?: Date + /** @description The period the invoice covers. If the invoice has no line items, it's not set. */ + period?: components['schemas']['Period'] + /** + * Format: date-time + * @description The time the invoice was voided. + * + * If the invoice was voided, this field will be set to the time the invoice was voided. + * @example 2023-01-01T01:01:01.001Z + */ + readonly voidedAt?: Date + /** + * Format: date-time + * @description The time the invoice was sent to customer. + * @example 2023-01-01T01:01:01.001Z + */ + readonly sentToCustomerAt?: Date + /** + * @description The workflow associated with the invoice. + * + * It is always a snapshot of the workflow settings at the time of invoice creation. The + * field is optional as it should be explicitly requested with expand options. + */ + workflow: components['schemas']['InvoiceWorkflowSettings'] + /** @description List of invoice lines representing each of the items sold to the customer. */ + lines?: components['schemas']['InvoiceLine'][] + /** @description Information on when, how, and to whom the invoice should be paid. */ + readonly payment?: components['schemas']['InvoicePaymentTerms'] + /** @description Validation issues reported by the invoice workflow. */ + readonly validationIssues?: components['schemas']['ValidationIssue'][] + /** @description External IDs of the invoice in other apps such as Stripe. */ + readonly externalIds?: components['schemas']['InvoiceAppExternalIds'] + } + /** @description InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. */ + InvoiceAppExternalIds: { + /** @description The external ID of the invoice in the invoicing app if available. */ + readonly invoicing?: string + /** @description The external ID of the invoice in the tax app if available. */ + readonly tax?: string + /** @description The external ID of the invoice in the payment app if available. */ + readonly payment?: string + } + /** + * @description InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + * non-gathering invoices. + */ + InvoiceAvailableActionDetails: { + /** + * @description The state the invoice will reach if the action is activated and + * all intermediate steps are successful. + * + * For example advancing a draft_created invoice will result in a draft_manual_approval_needed invoice. + */ + readonly resultingState: string + } + /** + * @description InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + * gathering invoices. + */ + InvoiceAvailableActionInvoiceDetails: Record + /** @description InvoiceAvailableActions represents the actions that can be performed on the invoice. */ + InvoiceAvailableActions: { + /** @description Advance the invoice to the next status. */ + readonly advance?: components['schemas']['InvoiceAvailableActionDetails'] + /** @description Approve an invoice that requires manual approval. */ + readonly approve?: components['schemas']['InvoiceAvailableActionDetails'] + /** @description Delete the invoice (only non-issued invoices can be deleted). */ + readonly delete?: components['schemas']['InvoiceAvailableActionDetails'] + /** @description Retry an invoice issuing step that failed. */ + readonly retry?: components['schemas']['InvoiceAvailableActionDetails'] + /** @description Snapshot quantities for usage based line items. */ + readonly snapshotQuantities?: components['schemas']['InvoiceAvailableActionDetails'] + /** @description Void an already issued invoice. */ + readonly void?: components['schemas']['InvoiceAvailableActionDetails'] + /** @description Invoice a gathering invoice */ + readonly invoice?: components['schemas']['InvoiceAvailableActionInvoiceDetails'] + } + /** @description InvoiceDetailedLine represents a line item that is sold to the customer as a manually added fee. */ + InvoiceDetailedLine: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description ID of the line. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + /** @description managedBy specifies if the line is manually added via the api or managed by OpenMeter. */ + readonly managedBy: components['schemas']['InvoiceLineManagedBy'] + /** + * @description Status of the line. + * + * External calls always create valid lines, other line types are managed by the + * billing engine of OpenMeter. + */ + readonly status: components['schemas']['InvoiceLineStatus'] + /** + * @description Discounts detailes applied to this line. + * + * New discounts can be added via the invoice's discounts API, to facilitate + * discounts that are affecting multiple lines. + */ + readonly discounts?: components['schemas']['InvoiceLineDiscounts'] + /** + * @description Credit allocations applied to this line. + * + * Credits are deducted from the line total before taxes are applied. + */ + readonly creditAllocations?: components['schemas']['InvoiceLineCreditAllocation'][] + /** @description The invoice this item belongs to. */ + invoice?: components['schemas']['InvoiceReference'] + /** @description The currency of this line. */ + currency: components['schemas']['CurrencyCode'] + /** @description Taxes applied to the invoice totals. */ + readonly taxes?: components['schemas']['InvoiceLineTaxItem'][] + /** + * @deprecated + * @description Tax config specify the tax configuration for this line. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** @description Totals for this line. */ + readonly totals: components['schemas']['InvoiceTotals'] + /** + * @description Period of the line item applies to for revenue recognition pruposes. + * + * Billing always treats periods as start being inclusive and end being exclusive. + */ + period: components['schemas']['Period'] + /** @description External IDs of the invoice in other apps such as Stripe. */ + readonly externalIds?: components['schemas']['InvoiceLineAppExternalIds'] + /** @description Subscription are the references to the subscritpions that this line is related to. */ + readonly subscription?: components['schemas']['InvoiceLineSubscriptionReference'] + /** + * Format: date-time + * @deprecated + * @description The time this line item should be invoiced. + * @example 2023-01-01T01:01:01.001Z + */ + invoiceAt: Date + /** + * @deprecated + * @description Type of the line. + * @enum {string} + */ + readonly type: 'flat_fee' + /** + * @deprecated + * @description Price of the item being sold. + */ + perUnitAmount?: components['schemas']['Numeric'] + /** + * @deprecated + * @description Payment term of the line. + * @default in_advance + */ + paymentTerm?: components['schemas']['PricePaymentTerm'] + /** + * @deprecated + * @description Quantity of the item being sold. + */ + quantity?: components['schemas']['Numeric'] + /** @description The rate card that is used for this line. */ + rateCard?: components['schemas']['InvoiceDetailedLineRateCard'] + /** + * @description Category of the flat fee. + * @default regular + */ + readonly category?: components['schemas']['InvoiceDetailedLineCostCategory'] + } + /** + * @description InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a + * commitment. + * @enum {string} + */ + InvoiceDetailedLineCostCategory: 'regular' | 'commitment' + /** @description InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. */ + InvoiceDetailedLineRateCard: { + /** + * Tax config + * @description The tax config of the rate card. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * Price + * @description The price of the rate card. + * When null, the feature or service is free. + * @example { + * "type": "flat", + * "amount": "100", + * "paymentTerm": "in_arrears" + * } + */ + price: components['schemas']['FlatPriceWithPaymentTerm'] | null + /** + * @description Quantity of the item being sold. + * + * Default: 1 + */ + quantity?: components['schemas']['Numeric'] + /** @description The discounts that are applied to the line. */ + discounts?: components['schemas']['BillingDiscounts'] + } + /** @description InvoiceDocumentRef is used to describe a reference to an existing document (invoice). */ + InvoiceDocumentRef: components['schemas']['CreditNoteOriginalInvoiceRef'] + /** + * @description InvoiceDocumentRefType defines the type of document that is being referenced. + * @enum {string} + */ + InvoiceDocumentRefType: 'credit_note_original_invoice' + /** + * @description InvoiceExpand specifies the parts of the invoice to expand in the list output. + * @enum {string} + */ + InvoiceExpand: 'lines' | 'preceding' | 'workflow.apps' + /** + * InvoiceGenericDocumentRef is used to describe an existing document or a specific part of it's contents. + * @description Omitted fields: + * period: Tax period in which the referred document had an effect required by some tax regimes and formats. + * stamps: Seals of approval from other organisations that may need to be listed. + * ext: Extensions for additional codes that may be required. + */ + InvoiceGenericDocumentRef: { + /** @description Type of the document referenced. */ + readonly type: components['schemas']['InvoiceDocumentRefType'] + /** @description Human readable description on why this reference is here or needs to be used. */ + readonly reason?: string + /** @description Additional details about the document. */ + readonly description?: string + } + /** @description InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. */ + InvoiceLine: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description ID of the line. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + /** @description managedBy specifies if the line is manually added via the api or managed by OpenMeter. */ + readonly managedBy: components['schemas']['InvoiceLineManagedBy'] + /** + * @description Status of the line. + * + * External calls always create valid lines, other line types are managed by the + * billing engine of OpenMeter. + */ + readonly status: components['schemas']['InvoiceLineStatus'] + /** + * @description Discounts detailes applied to this line. + * + * New discounts can be added via the invoice's discounts API, to facilitate + * discounts that are affecting multiple lines. + */ + readonly discounts?: components['schemas']['InvoiceLineDiscounts'] + /** + * @description Credit allocations applied to this line. + * + * Credits are deducted from the line total before taxes are applied. + */ + readonly creditAllocations?: components['schemas']['InvoiceLineCreditAllocation'][] + /** @description The invoice this item belongs to. */ + invoice?: components['schemas']['InvoiceReference'] + /** @description The currency of this line. */ + currency: components['schemas']['CurrencyCode'] + /** @description Taxes applied to the invoice totals. */ + readonly taxes?: components['schemas']['InvoiceLineTaxItem'][] + /** + * @deprecated + * @description Tax config specify the tax configuration for this line. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** @description Totals for this line. */ + readonly totals: components['schemas']['InvoiceTotals'] + /** + * @description Period of the line item applies to for revenue recognition pruposes. + * + * Billing always treats periods as start being inclusive and end being exclusive. + */ + period: components['schemas']['Period'] + /** + * Format: date-time + * @description The time this line item should be invoiced. + * @example 2023-01-01T01:01:01.001Z + */ + invoiceAt: Date + /** @description External IDs of the invoice in other apps such as Stripe. */ + readonly externalIds?: components['schemas']['InvoiceLineAppExternalIds'] + /** @description Subscription are the references to the subscritpions that this line is related to. */ + readonly subscription?: components['schemas']['InvoiceLineSubscriptionReference'] + /** + * @deprecated + * @description Type of the line. + * @enum {string} + */ + readonly type: 'usage_based' + /** + * @deprecated + * @description Price of the usage-based item being sold. + */ + price?: components['schemas']['RateCardUsageBasedPrice'] + /** + * @deprecated + * @description The feature that the usage is based on. + */ + featureKey?: string + /** @description The lines detailing the item or service sold. */ + readonly children?: components['schemas']['InvoiceDetailedLine'][] + /** + * @description The rate card that is used for this line. + * + * The rate card captures the intent of the price and discounts for the usage-based item. + */ + rateCard?: components['schemas']['InvoiceUsageBasedRateCard'] + /** + * @description The quantity of the item being sold. + * + * Any usage discounts applied previously are deducted from this quantity. + */ + readonly quantity?: components['schemas']['Numeric'] + /** @description The quantity of the item that has been metered for the period before any discounts were applied. */ + readonly meteredQuantity?: components['schemas']['Numeric'] + /** + * @description The quantity of the item used before this line's period. + * + * It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + * + * Any usage discounts applied previously are deducted from this quantity. + */ + readonly preLinePeriodQuantity?: components['schemas']['Numeric'] + /** + * @description The metered quantity of the item used in before this line's period without any discounts applied. + * + * It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + */ + readonly meteredPreLinePeriodQuantity?: components['schemas']['Numeric'] + } + /** @description InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied before taxes. */ + InvoiceLineAmountDiscount: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description ID of the charge or discount. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** @description Reason code. */ + readonly reason: components['schemas']['BillingDiscountReason'] + /** @description Text description as to why the discount was applied. */ + readonly description?: string + /** @description External IDs of the invoice in other apps such as Stripe. */ + readonly externalIds?: components['schemas']['InvoiceLineAppExternalIds'] + /** + * Amount in the currency of the invoice + * @description Fixed discount amount to apply (calculated if percent present). + */ + readonly amount: components['schemas']['Numeric'] + } + /** @description InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. */ + InvoiceLineAppExternalIds: { + /** @description The external ID of the invoice in the invoicing app if available. */ + readonly invoicing?: string + /** @description The external ID of the invoice in the tax app if available. */ + readonly tax?: string + } + /** @description InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are applied. */ + InvoiceLineCreditAllocation: { + /** + * Amount in the currency of the invoice + * @description Amount allocated from credits. + */ + readonly amount: components['schemas']['Numeric'] + /** @description Text description as to why the credit was allocated. */ + readonly description?: string + } + /** @description InvoiceLineDiscounts represents the discounts applied to the invoice line by type. */ + InvoiceLineDiscounts: { + /** + * @description Amount based discounts applied to the line. + * + * Amount based discounts are deduced from the total price of the line. + */ + amount?: components['schemas']['InvoiceLineAmountDiscount'][] + /** + * @description Usage based discounts applied to the line. + * + * Usage based discounts are deduced from the usage of the line before price calculations are applied. + */ + usage?: components['schemas']['InvoiceLineUsageDiscount'][] + } + /** + * @description InvoiceLineManagedBy specifies who manages the line. + * @enum {string} + */ + InvoiceLineManagedBy: 'subscription' | 'system' | 'manual' + /** + * @description InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. + * + * This type makes ID optional to allow for creating new lines as part of the update. + */ + InvoiceLineReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * @deprecated + * @description Tax config specify the tax configuration for this line. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * @description Period of the line item applies to for revenue recognition pruposes. + * + * Billing always treats periods as start being inclusive and end being exclusive. + */ + period: components['schemas']['Period'] + /** + * Format: date-time + * @description The time this line item should be invoiced. + * @example 2023-01-01T01:01:01.001Z + */ + invoiceAt: Date + /** + * @deprecated + * @description Price of the usage-based item being sold. + */ + price?: components['schemas']['RateCardUsageBasedPrice'] + /** + * @deprecated + * @description The feature that the usage is based on. + */ + featureKey?: string + /** + * @description The rate card that is used for this line. + * + * The rate card captures the intent of the price and discounts for the usage-based item. + */ + rateCard?: components['schemas']['InvoiceUsageBasedRateCard'] + /** + * @description The ID of the line. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id?: string + } + /** + * @description Line status specifies the status of the line. + * @enum {string} + */ + InvoiceLineStatus: 'valid' | 'detailed' | 'split' + /** @description InvoiceLineSubscriptionReference contains the references to the subscription that this line is related to. */ + InvoiceLineSubscriptionReference: { + /** @description The subscription. */ + readonly subscription: components['schemas']['IDResource'] + /** @description The phase of the subscription. */ + readonly phase: components['schemas']['IDResource'] + /** @description The item this line is related to. */ + readonly item: components['schemas']['IDResource'] + /** + * @description The billing period of the subscription. In case the subscription item's billing period is different + * from the subscription's billing period, this field will contain the billing period of the subscription itself. + * + * For example, in case of: + * - A monthly billed subscription anchored to 2025-01-01 + * - A subscription item billed daily + * + * An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed daily, but the subscription's billing period + * will be 2025-01-01 to 2025-01-31. + */ + readonly billingPeriod: components['schemas']['Period'] + } + /** + * @description InvoiceLineTaxBehavior details how the tax item is applied to the base amount. + * + * Inclusive means the tax is included in the base amount. + * Exclusive means the tax is added to the base amount. + * @enum {string} + */ + InvoiceLineTaxBehavior: 'inclusive' | 'exclusive' + /** @description TaxConfig stores the configuration for a tax line relative to an invoice line. */ + InvoiceLineTaxItem: { + /** @description Tax provider configuration. */ + readonly config?: components['schemas']['TaxConfig'] + /** + * @description Percent defines the percentage set manually or determined from + * the rate key (calculated if rate present). A nil percent implies that + * this tax combo is **exempt** from tax.") + */ + readonly percent?: components['schemas']['Percentage'] + /** @description Some countries require an additional surcharge (calculated if rate present). */ + readonly surcharge?: components['schemas']['Numeric'] + /** @description Is the tax item inclusive or exclusive of the base amount. */ + readonly behavior?: components['schemas']['InvoiceLineTaxBehavior'] + } + /** + * @description InvoiceLineUsageDiscount represents an usage-based discount applied to the line. + * + * The deduction is done before the pricing algorithm is applied. + */ + InvoiceLineUsageDiscount: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description ID of the charge or discount. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** @description Reason code. */ + readonly reason: components['schemas']['BillingDiscountReason'] + /** @description Text description as to why the discount was applied. */ + readonly description?: string + /** @description External IDs of the invoice in other apps such as Stripe. */ + readonly externalIds?: components['schemas']['InvoiceLineAppExternalIds'] + /** + * Usage quantity in the unit of the underlying meter + * @description The usage to apply. + */ + readonly quantity: components['schemas']['Numeric'] + /** + * Usage quantity in the unit of the underlying meter + * @description The usage discount already applied to the previous split lines. + * + * Only set if progressive billing is enabled and the line is a split line. + */ + readonly preLinePeriodQuantity?: components['schemas']['Numeric'] + } + /** + * @description InvoiceNumber is a unique identifier for the invoice, generated by the + * invoicing app. + * + * The uniqueness depends on a lot of factors: + * - app setting (unique per app or unique per customer) + * - multiple app scenarios (multiple apps generating invoices with the same prefix) + * @example INV-2024-01-01-01 + */ + InvoiceNumber: string + /** + * @description InvoiceOrderBy specifies the ordering options for invoice listing. + * @enum {string} + */ + InvoiceOrderBy: + | 'customer.name' + | 'issuedAt' + | 'status' + | 'createdAt' + | 'updatedAt' + | 'periodStart' + /** @description Paginated response */ + InvoicePaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Invoice'][] + } + /** @description Payment contains details as to how the invoice should be paid. */ + InvoicePaymentTerms: { + /** @description The terms of payment for the invoice. */ + terms?: components['schemas']['PaymentTerms'] + } + /** @description InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage. */ + InvoicePendingLineCreate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * @deprecated + * @description Tax config specify the tax configuration for this line. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * @description Period of the line item applies to for revenue recognition pruposes. + * + * Billing always treats periods as start being inclusive and end being exclusive. + */ + period: components['schemas']['Period'] + /** + * Format: date-time + * @description The time this line item should be invoiced. + * @example 2023-01-01T01:01:01.001Z + */ + invoiceAt: Date + /** + * @deprecated + * @description Price of the usage-based item being sold. + */ + price?: components['schemas']['RateCardUsageBasedPrice'] + /** + * @deprecated + * @description The feature that the usage is based on. + */ + featureKey?: string + /** + * @description The rate card that is used for this line. + * + * The rate card captures the intent of the price and discounts for the usage-based item. + */ + rateCard?: components['schemas']['InvoiceUsageBasedRateCard'] + } + /** @description InvoicePendingLineCreate represents the create model for a pending invoice line. */ + InvoicePendingLineCreateInput: { + /** @description The currency of the lines to be created. */ + currency: components['schemas']['CurrencyCode'] + /** @description The lines to be created. */ + lines: components['schemas']['InvoicePendingLineCreate'][] + } + /** @description InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. */ + InvoicePendingLineCreateResponse: { + /** @description The lines that were created. */ + readonly lines: components['schemas']['InvoiceLine'][] + /** @description The invoice containing the created lines. */ + readonly invoice: components['schemas']['Invoice'] + /** @description Whether the invoice was newly created. */ + readonly isInvoiceNew: boolean + } + /** @description InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. */ + InvoicePendingLinesActionFiltersInput: { + /** + * @description The pending line items to include in the invoice, if not provided: + * - all line items that have invoice_at < asOf will be included + * - [progressive billing only] all usage based line items will be included up to asOf, new + * usage-based line items will be staged for the rest of the billing cycle + * + * All lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail. + */ + lineIds?: string[] + } + /** + * @description BillingInvoiceActionInput is the input for creating an invoice. + * + * Invoice creation is always based on already pending line items created by the billingCreateLineByCustomer + * operation. Empty invoices are not allowed. + */ + InvoicePendingLinesActionInput: { + /** @description Filters to apply when creating the invoice. */ + filters?: components['schemas']['InvoicePendingLinesActionFiltersInput'] + /** + * Format: date-time + * @description The time as of which the invoice is created. + * + * If not provided, the current time is used. + * @example 2023-01-01T01:01:01.001Z + */ + asOf?: Date + /** + * @description The customer ID for which to create the invoice. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId: string + /** + * @description Override the progressive billing setting of the customer. + * + * Can be used to disable/enable progressive billing in case the business logic + * requires it, if not provided the billing profile's progressive billing setting will be used. + */ + progressiveBillingOverride?: boolean + } + /** @description Reference to an invoice. */ + InvoiceReference: { + /** + * @description The ID of the invoice. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** @description The number of the invoice. */ + readonly number?: components['schemas']['InvoiceNumber'] + } + /** @description InvoiceReplaceUpdate represents the update model for an invoice. */ + InvoiceReplaceUpdate: { + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** @description The supplier of the lines included in the invoice. */ + supplier: components['schemas']['BillingPartyReplaceUpdate'] + /** @description The customer the invoice is sent to. */ + customer: components['schemas']['BillingPartyReplaceUpdate'] + /** @description The lines included in the invoice. */ + lines: components['schemas']['InvoiceLineReplaceUpdate'][] + /** @description The workflow settings for the invoice. */ + workflow: components['schemas']['InvoiceWorkflowReplaceUpdate'] + } + /** @description InvoiceSimulationInput is the input for simulating an invoice. */ + InvoiceSimulationInput: { + /** @description The number of the invoice. */ + number?: components['schemas']['InvoiceNumber'] + /** + * @description Currency for all invoice line items. + * + * Multi currency invoices are not supported yet. + */ + currency: components['schemas']['CurrencyCode'] + /** @description Lines to be included in the generated invoice. */ + lines: components['schemas']['InvoiceSimulationLine'][] + } + /** @description InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint. */ + InvoiceSimulationLine: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * @deprecated + * @description Tax config specify the tax configuration for this line. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * @description Period of the line item applies to for revenue recognition pruposes. + * + * Billing always treats periods as start being inclusive and end being exclusive. + */ + period: components['schemas']['Period'] + /** + * Format: date-time + * @description The time this line item should be invoiced. + * @example 2023-01-01T01:01:01.001Z + */ + invoiceAt: Date + /** + * @deprecated + * @description Price of the usage-based item being sold. + */ + price?: components['schemas']['RateCardUsageBasedPrice'] + /** + * @deprecated + * @description The feature that the usage is based on. + */ + featureKey?: string + /** + * @description The rate card that is used for this line. + * + * The rate card captures the intent of the price and discounts for the usage-based item. + */ + rateCard?: components['schemas']['InvoiceUsageBasedRateCard'] + /** @description The quantity of the item being sold. */ + quantity: components['schemas']['Numeric'] + /** @description The quantity of the item used before this line's period, if the line is billed progressively. */ + preLinePeriodQuantity?: components['schemas']['Numeric'] + /** + * @description ID of the line. If not specified it will be auto-generated. + * + * When discounts are specified, this must be provided, so that the discount can reference it. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id?: string + } + /** + * @description InvoiceStatus describes the status of an invoice. + * @enum {string} + */ + InvoiceStatus: + | 'gathering' + | 'draft' + | 'issuing' + | 'issued' + | 'payment_processing' + | 'overdue' + | 'paid' + | 'uncollectible' + | 'voided' + /** + * @description InvoiceStatusDetails represents the details of the invoice status. + * + * API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine + * the next steps of the invoice instead of the extendedStatus field. + */ + InvoiceStatusDetails: { + /** @description Is the invoice editable? */ + readonly immutable: boolean + /** @description Is the invoice in a failed state? */ + readonly failed: boolean + /** @description Extended status information for the invoice. */ + readonly extendedStatus: string + /** @description The actions that can be performed on the invoice. */ + availableActions: components['schemas']['InvoiceAvailableActions'] + } + /** @description Totals contains the summaries of all calculations for the invoice. */ + InvoiceTotals: { + /** @description The total value of the line before taxes, discounts and commitments. */ + readonly amount: components['schemas']['Numeric'] + /** @description The amount of value of the line that are due to additional charges. */ + readonly chargesTotal: components['schemas']['Numeric'] + /** @description The amount of value of the line that are due to discounts. */ + readonly discountsTotal: components['schemas']['Numeric'] + /** @description The amount of value of the line that are due to credits. */ + readonly creditsTotal: components['schemas']['Numeric'] + /** @description The total amount of taxes that are included in the line. */ + readonly taxesInclusiveTotal: components['schemas']['Numeric'] + /** @description The total amount of taxes that are added on top of amount from the line. */ + readonly taxesExclusiveTotal: components['schemas']['Numeric'] + /** @description The total amount of taxes for this line. */ + readonly taxesTotal: components['schemas']['Numeric'] + /** @description The total amount value of the line after taxes, discounts and commitments. */ + readonly total: components['schemas']['Numeric'] + } + /** + * @description InvoiceType represents the type of invoice. + * + * The type of invoice determines the purpose of the invoice and how it should be handled. + * @enum {string} + */ + InvoiceType: 'standard' | 'credit_note' + /** @description InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. */ + InvoiceUsageBasedRateCard: { + /** + * Feature key + * @description The feature the customer is entitled to use. + */ + featureKey?: string + /** + * Tax config + * @description The tax config of the rate card. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * @description The price of the rate card. + * When null, the feature or service is free. + */ + price: components['schemas']['RateCardUsageBasedPrice'] | null + /** + * @deprecated + * @description The discounts that are applied to the line. + */ + discounts?: components['schemas']['BillingDiscounts'] + } + /** @description InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow. */ + InvoiceWorkflowInvoicingSettingsReplaceUpdate: { + /** + * @description Whether to automatically issue the invoice after the draftPeriod has passed. + * @default true + */ + autoAdvance?: boolean + /** + * Format: ISO8601 + * @description The period for the invoice to be kept in draft status for manual reviews. + * @default P0D + * @example P1D + */ + draftPeriod?: string + /** + * Format: ISO8601 + * @description The period after which the invoice is due. + * With some payment solutions it's only applicable for manual collection method. + * @default P30D + * @example P30D + */ + dueAfter?: string + /** + * @description Controls how subscription-ending shortened service periods are billed. + * @default bill_actual_period + */ + subscriptionEndProrationMode?: components['schemas']['BillingWorkflowInvoicingSubscriptionEndProrationMode'] + /** + * @description Default tax configuration to apply to the invoices. + * + * Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + * deprecated and can no longer be added or changed: the organization default tax code is + * used instead. Existing tax-code values may still be removed, and `behavior` remains + * fully supported. + */ + defaultTaxConfig?: components['schemas']['TaxConfig'] + } + /** + * @description InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. + * + * Fields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings. + */ + InvoiceWorkflowReplaceUpdate: { + /** @description The workflow used for this invoice. */ + workflow: components['schemas']['InvoiceWorkflowSettingsReplaceUpdate'] + } + /** + * @description InvoiceWorkflowSettings represents the workflow settings used by the invoice. + * + * This is a clone of the billing profile's workflow settings at the time of invoice creation + * with customer overrides considered. + */ + InvoiceWorkflowSettings: { + /** @description The apps that will be used to orchestrate the invoice's workflow. */ + readonly apps?: components['schemas']['BillingProfileAppsOrReference'] + /** + * @description sourceBillingProfileID is the billing profile on which the workflow was based on. + * + * The profile is snapshotted on invoice creation, after which it can be altered independently + * of the profile itself. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly sourceBillingProfileId: string + /** @description The workflow details used by this invoice. */ + workflow: components['schemas']['BillingWorkflow'] + } + /** + * @description Mutable workflow settings for an invoice. + * + * Other fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow + * at creation time. + */ + InvoiceWorkflowSettingsReplaceUpdate: { + /** @description The invoicing settings for this workflow */ + invoicing: components['schemas']['InvoiceWorkflowInvoicingSettingsReplaceUpdate'] + /** @description The payment settings for this workflow */ + payment: components['schemas']['BillingWorkflowPaymentSettings'] + } + /** @description Issue after reset */ + IssueAfterReset: { + /** + * Initial grant amount + * Format: double + * @description The initial grant amount + */ + amount: number + /** + * Issue grant after reset priority + * Format: uint8 + * @description The priority of the issue after reset + * @default 1 + */ + priority?: number + } + /** @description List entitlements result */ + ListEntitlementsResult: + | components['schemas']['Entitlement'][] + | components['schemas']['EntitlementPaginatedResponse'] + /** @description List features result */ + ListFeaturesResult: + | components['schemas']['Feature'][] + | components['schemas']['FeaturePaginatedResponse'] + /** @description Marketplace install request payload. */ + MarketplaceInstallRequestPayload: { + /** + * @description Name of the application to install. + * + * If name is not provided defaults to the marketplace listing's name. + */ + name?: string + /** + * @description If true, a billing profile will be created for the app. + * The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + * @default true + */ + createBillingProfile?: boolean + } + /** @description Marketplace install response. */ + MarketplaceInstallResponse: { + app: components['schemas']['App'] + /** @description Default for capabilities */ + defaultForCapabilityTypes: components['schemas']['AppCapabilityType'][] + } + /** + * @description A marketplace listing. + * Represent an available app in the app marketplace that can be installed to the organization. + * + * Marketplace apps only exist in config so they don't extend the Resource model. + * @example { + * "type": "stripe", + * "name": "Stripe", + * "description": "Stripe integration allows you to collect payments with Stripe.", + * "capabilities": [ + * { + * "type": "calculateTax", + * "key": "stripe_calculate_tax", + * "name": "Calculate Tax", + * "description": "Stripe Tax calculates tax portion of the invoices." + * }, + * { + * "type": "invoiceCustomers", + * "key": "stripe_invoice_customers", + * "name": "Invoice Customers", + * "description": "Stripe invoices customers with due amount." + * }, + * { + * "type": "collectPayments", + * "key": "stripe_collect_payments", + * "name": "Collect Payments", + * "description": "Stripe payments collects outstanding revenue with Stripe customer's default payment method." + * } + * ], + * "installMethods": [ + * "with_oauth2", + * "with_api_key" + * ] + * } + */ + MarketplaceListing: { + /** @description The app's type */ + type: components['schemas']['AppType'] + /** @description The app's name. */ + name: string + /** @description The app's description. */ + description: string + /** @description The app's capabilities. */ + capabilities: components['schemas']['AppCapability'][] + /** + * @description Install methods. + * + * List of methods to install the app. + */ + installMethods: components['schemas']['InstallMethod'][] + } + /** @description Paginated response */ + MarketplaceListingPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['MarketplaceListing'][] + } + /** @description Measure usage from */ + MeasureUsageFrom: + | components['schemas']['MeasureUsageFromPreset'] + | components['schemas']['MeasureUsageFromTime'] + /** + * @description Start of measurement options + * @enum {string} + */ + MeasureUsageFromPreset: 'CURRENT_PERIOD_START' | 'NOW' + /** + * Format: date-time + * @description [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + * @example 2023-01-01T01:01:01.001Z + */ + MeasureUsageFromTime: Date + /** + * @description Set of key-value pairs. + * Metadata can be used to store additional information about a resource. + * @example { + * "externalId": "019142cc-a016-796a-8113-1a942fecd26d" + * } + */ + Metadata: { + [key: string]: string + } + /** + * @description A meter is a configuration that defines how to match and aggregate events. + * @example { + * "id": "01G65Z755AFWAKHE12NY0CQ9FH", + * "slug": "tokens_total", + * "name": "Tokens Total", + * "description": "AI Token Usage", + * "aggregation": "SUM", + * "eventType": "prompt", + * "valueProperty": "$.tokens", + * "groupBy": { + * "model": "$.model", + * "type": "$.type" + * }, + * "createdAt": "2024-01-01T01:01:01.001Z", + * "updatedAt": "2024-01-01T01:01:01.001Z" + * } + */ + Meter: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + * Defaults to the slug if not specified. + */ + name?: string + /** + * @description A unique, human-readable identifier for the meter. + * Must consist only alphanumeric and underscore characters. + * @example tokens_total + */ + slug: string + /** + * @description The aggregation type to use for the meter. + * @example SUM + */ + aggregation: components['schemas']['MeterAggregation'] + /** + * @description The event type to aggregate. + * @example prompt + */ + eventType: string + /** + * Format: date-time + * @description The date since the meter should include events. + * Useful to skip old events. + * If not specified, all historical events are included. + * @example 2023-01-01T01:01:01.001Z + */ + eventFrom?: Date + /** + * @description JSONPath expression to extract the value from the ingested event's data property. + * + * The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + * + * For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + * @example $.tokens + */ + valueProperty?: string + /** + * @description Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + * @example { + * "type": "$.type" + * } + */ + groupBy?: { + [key: string]: string + } + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] | null + } + /** + * @description The aggregation type to use for the meter. + * @enum {string} + */ + MeterAggregation: + | 'SUM' + | 'COUNT' + | 'UNIQUE_COUNT' + | 'AVG' + | 'MIN' + | 'MAX' + | 'LATEST' + /** + * @description A meter create model. + * @example { + * "slug": "tokens_total", + * "name": "Tokens Total", + * "description": "AI Token Usage", + * "aggregation": "SUM", + * "eventType": "prompt", + * "valueProperty": "$.tokens", + * "groupBy": { + * "model": "$.model", + * "type": "$.type" + * } + * } + */ + MeterCreate: { + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + * Defaults to the slug if not specified. + */ + name?: string + /** + * @description A unique, human-readable identifier for the meter. + * Must consist only alphanumeric and underscore characters. + * @example tokens_total + */ + slug: string + /** + * @description The aggregation type to use for the meter. + * @example SUM + */ + aggregation: components['schemas']['MeterAggregation'] + /** + * @description The event type to aggregate. + * @example prompt + */ + eventType: string + /** + * Format: date-time + * @description The date since the meter should include events. + * Useful to skip old events. + * If not specified, all historical events are included. + * @example 2023-01-01T01:01:01.001Z + */ + eventFrom?: Date + /** + * @description JSONPath expression to extract the value from the ingested event's data property. + * + * The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + * + * For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + * @example $.tokens + */ + valueProperty?: string + /** + * @description Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + * @example { + * "type": "$.type" + * } + */ + groupBy?: { + [key: string]: string + } + } + /** + * @description Order by options for meters. + * @enum {string} + */ + MeterOrderBy: 'key' | 'name' | 'aggregation' | 'createdAt' | 'updatedAt' + /** @description A meter query request. */ + MeterQueryRequest: { + /** + * @description Client ID + * Useful to track progress of a query. + * @example f74e58ed-94ce-4041-ae06-cf45420451a3 + */ + clientId?: string + /** + * Format: date-time + * @description Start date-time in RFC 3339 format. + * + * Inclusive. + * @example 2023-01-01T01:01:01.001Z + */ + from?: Date + /** + * Format: date-time + * @description End date-time in RFC 3339 format. + * + * Inclusive. + * @example 2023-01-01T01:01:01.001Z + */ + to?: Date + /** + * @description If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + * @example DAY + */ + windowSize?: components['schemas']['WindowSize'] + /** + * @description The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + * If not specified, the UTC timezone will be used. + * @default UTC + * @example UTC + */ + windowTimeZone?: string + /** + * @description Filtering by multiple subjects. + * @example [ + * "subject-1", + * "subject-2" + * ] + */ + subject?: string[] + /** + * @description Filtering by multiple customers. + * @example [ + * "id-1", + * "id-2" + * ] + */ + filterCustomerId?: string[] + /** + * @description Simple filter for group bys with exact match. + * @example { + * "model": [ + * "gpt-4-turbo", + * "gpt-4o" + * ], + * "type": [ + * "prompt" + * ] + * } + */ + filterGroupBy?: { + [key: string]: string[] + } + /** + * @description Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + * @example { + * "model": { + * "$in": [ + * "gpt-4", + * "gpt-4o" + * ] + * }, + * "type": { + * "$eq": "input" + * } + * } + */ + advancedMeterGroupByFilters?: { + [key: string]: components['schemas']['FilterString'] + } + /** + * @description If not specified a single aggregate will be returned for each subject and time window. + * `subject` is a reserved group by value. + * @example [ + * "model", + * "type" + * ] + */ + groupBy?: string[] + } + /** + * @description The result of a meter query. + * @example { + * "from": "2023-01-01T00:00:00Z", + * "to": "2023-01-02T00:00:00Z", + * "windowSize": "DAY", + * "data": [ + * { + * "value": 12, + * "windowStart": "2023-01-01T00:00:00Z", + * "windowEnd": "2023-01-02T00:00:00Z", + * "subject": "customer-1", + * "groupBy": { + * "model": "gpt-4-turbo", + * "type": "prompt" + * } + * } + * ] + * } + */ + MeterQueryResult: { + /** + * Format: date-time + * @description The start of the period the usage is queried from. + * If not specified, the usage is queried from the beginning of time. + * @example 2023-01-01T01:01:01.001Z + */ + from?: Date + /** + * Format: date-time + * @description The end of the period the usage is queried to. + * If not specified, the usage is queried up to the current time. + * @example 2023-01-01T01:01:01.001Z + */ + to?: Date + /** + * @description The window size that the usage is aggregated. + * If not specified, the usage is aggregated over the entire period. + */ + windowSize?: components['schemas']['WindowSize'] + /** + * @description The usage data. + * If no data is available, an empty array is returned. + */ + data: components['schemas']['MeterQueryRow'][] + } + /** + * @description A row in the result of a meter query. + * @example { + * "value": 12, + * "windowStart": "2023-01-01T00:00:00Z", + * "windowEnd": "2023-01-02T00:00:00Z", + * "subject": "customer-1", + * "groupBy": { + * "model": "gpt-4-turbo", + * "type": "prompt" + * } + * } + */ + MeterQueryRow: { + /** + * Format: double + * @description The aggregated value. + */ + value: number + /** + * Format: date-time + * @description The start of the window the value is aggregated over. + * @example 2023-01-01T01:01:01.001Z + */ + windowStart: Date + /** + * Format: date-time + * @description The end of the window the value is aggregated over. + * @example 2023-01-01T01:01:01.001Z + */ + windowEnd: Date + /** + * @description The subject the value is aggregated over. + * If not specified, the value is aggregated over all subjects. + */ + subject: string | null + /** @description The customer ID the value is aggregated over. */ + customerId?: string + /** @description The group by values the value is aggregated over. */ + groupBy: { + [key: string]: string | null + } + } + /** + * @description A meter update model. + * + * Only the properties that can be updated are included. + * For example, the slug and aggregation cannot be updated. + * @example { + * "name": "Tokens Total", + * "description": "AI Token Usage", + * "groupBy": { + * "model": "$.model", + * "type": "$.type" + * } + * } + */ + MeterUpdate: { + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + * Defaults to the slug if not specified. + */ + name?: string + /** + * @description Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + * @example { + * "type": "$.type" + * } + */ + groupBy?: { + [key: string]: string + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + NotFoundProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** @description The server does not support the functionality required to fulfill the request. */ + NotImplementedProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** @description Notification channel. */ + NotificationChannel: components['schemas']['NotificationChannelWebhook'] + /** @description Union type for requests creating new notification channel with certain type. */ + NotificationChannelCreateRequest: components['schemas']['NotificationChannelWebhookCreateRequest'] + /** @description Metadata only fields of a notification channel. */ + NotificationChannelMeta: { + /** + * Channel Unique Identifier + * @description Identifies the notification channel. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * Channel Type + * @description Notification channel type. + */ + type: components['schemas']['NotificationChannelType'] + } + /** + * @description Order by options for notification channels. + * @enum {string} + */ + NotificationChannelOrderBy: 'id' | 'type' | 'createdAt' | 'updatedAt' + /** @description Paginated response */ + NotificationChannelPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['NotificationChannel'][] + } + /** + * @description Type of the notification channel. + * @enum {string} + */ + NotificationChannelType: 'WEBHOOK' + /** @description Notification channel with webhook type. */ + NotificationChannelWebhook: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Channel Unique Identifier + * @description Identifies the notification channel. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * Channel Type + * @description Notification channel type. + * @enum {string} + */ + type: 'WEBHOOK' + /** + * Channel Name + * @description User friendly name of the channel. + * @example customer-webhook + */ + name: string + /** + * Channel Disabled + * @description Whether the channel is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Webhook URL + * @description Webhook URL where the notification is sent. + * @example https://example.com/webhook + */ + url: string + /** + * Custom HTTP Headers + * @description Custom HTTP headers sent as part of the webhook request. + */ + customHeaders?: { + [key: string]: string + } + /** + * Signing Secret + * @description Signing secret used for webhook request validation on the receiving end. + * + * Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + * @example whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8 + */ + signingSecret?: string + } + /** @description Request with input parameters for creating new notification channel with webhook type. */ + NotificationChannelWebhookCreateRequest: { + /** + * Channel Type + * @description Notification channel type. + * @enum {string} + */ + type: 'WEBHOOK' + /** + * Channel Name + * @description User friendly name of the channel. + * @example customer-webhook + */ + name: string + /** + * Channel Disabled + * @description Whether the channel is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Webhook URL + * @description Webhook URL where the notification is sent. + * @example https://example.com/webhook + */ + url: string + /** + * Custom HTTP Headers + * @description Custom HTTP headers sent as part of the webhook request. + */ + customHeaders?: { + [key: string]: string + } + /** + * Signing Secret + * @description Signing secret used for webhook request validation on the receiving end. + * + * Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + * @example whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8 + */ + signingSecret?: string + } + /** @description Type of the notification event. */ + NotificationEvent: { + /** + * Event Identifier + * @description A unique identifier of the notification event. + * @example 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + */ + readonly id: string + /** + * Event Type + * @description Type of the notification event. + */ + readonly type: components['schemas']['NotificationEventType'] + /** + * Creation Time + * Format: date-time + * @description Timestamp when the notification event was created in RFC 3339 format. + * @example 2023-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** @description The nnotification rule which generated this event. */ + readonly rule: components['schemas']['NotificationRule'] + /** + * Delivery Status + * @description The delivery status of the notification event. + */ + readonly deliveryStatus: components['schemas']['NotificationEventDeliveryStatus'][] + /** @description Timestamp when the notification event was created in RFC 3339 format. */ + readonly payload: components['schemas']['NotificationEventPayload'] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + } + /** @description Payload for notification event with `entitlements.balance.threshold` type. */ + NotificationEventBalanceThresholdPayload: { + /** + * Notification Event Identifier + * @description A unique identifier for the notification event the payload belongs to. + * @example 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + */ + readonly id: string + /** + * @description Type of the notification event. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'entitlements.balance.threshold' + /** + * Creation Time + * Format: date-time + * @description Timestamp when the notification event was created in RFC 3339 format. + * @example 2023-01-01T01:01:01.001Z + */ + readonly timestamp: Date + /** + * Payload Data + * @description The data of the payload. + */ + readonly data: components['schemas']['NotificationEventBalanceThresholdPayloadData'] + } + /** @description Data of the payload for notification event with `entitlements.balance.threshold` type. */ + NotificationEventBalanceThresholdPayloadData: { + /** Entitlement */ + readonly entitlement: components['schemas']['EntitlementMetered'] + /** Feature */ + readonly feature: components['schemas']['Feature'] + /** Subject */ + readonly subject: components['schemas']['Subject'] + /** Entitlement Value */ + readonly value: components['schemas']['EntitlementValue'] + /** Customer */ + readonly customer?: components['schemas']['Customer'] + /** Threshold */ + readonly threshold: components['schemas']['NotificationRuleBalanceThresholdValue'] + } + /** @description The delivery attempt of the notification event. */ + NotificationEventDeliveryAttempt: { + /** + * State of teh delivery attempt + * @description State of teh delivery attempt. + * @example SUCCESS + */ + readonly state: components['schemas']['NotificationEventDeliveryStatusState'] + /** + * Response returned by the notification event recipient + * @description Response returned by the notification event recipient. + */ + readonly response: components['schemas']['EventDeliveryAttemptResponse'] + /** + * Timestamp of the delivery attempt + * Format: date-time + * @description Timestamp of the delivery attempt. + * @example 2023-01-01T01:01:01.001Z + */ + readonly timestamp: Date + } + /** @description The delivery status of the notification event. */ + NotificationEventDeliveryStatus: { + /** + * @description Delivery state of the notification event to the channel. + * @example SUCCESS + */ + readonly state: components['schemas']['NotificationEventDeliveryStatusState'] + /** + * State Reason + * @description The reason of the last deliverry state update. + * @example Failed to dispatch event due to provider error. + */ + readonly reason: string + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the status was last updated in RFC 3339 format. + * @example 2023-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Notification Channel + * @description Notification channel the delivery status associated with. + */ + readonly channel: components['schemas']['NotificationChannelMeta'] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Timestamp of the next delivery attempt + * Format: date-time + * @description Timestamp of the next delivery attempt. If null it means there will be no more delivery attempts. + * @example 2023-01-01T01:01:01.001Z + */ + readonly nextAttempt?: Date + /** + * Delivery Attempts + * @description List of delivery attempts. + */ + readonly attempts: components['schemas']['NotificationEventDeliveryAttempt'][] + } + /** + * Delivery State + * @description The delivery state of the notification event to the channel. + * @enum {string} + */ + NotificationEventDeliveryStatusState: + | 'SUCCESS' + | 'FAILED' + | 'SENDING' + | 'PENDING' + | 'RESENDING' + /** @description Base data for any payload with entitlement entitlement value. */ + NotificationEventEntitlementValuePayloadBase: { + /** Entitlement */ + readonly entitlement: components['schemas']['EntitlementMetered'] + /** Feature */ + readonly feature: components['schemas']['Feature'] + /** Subject */ + readonly subject: components['schemas']['Subject'] + /** Entitlement Value */ + readonly value: components['schemas']['EntitlementValue'] + /** Customer */ + readonly customer?: components['schemas']['Customer'] + } + /** @description Payload for notification event with `invoice.created` type. */ + NotificationEventInvoiceCreatedPayload: { + /** + * Notification Event Identifier + * @description A unique identifier for the notification event the payload belongs to. + * @example 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + */ + readonly id: string + /** + * @description Type of the notification event. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'invoice.created' + /** + * Creation Time + * Format: date-time + * @description Timestamp when the notification event was created in RFC 3339 format. + * @example 2023-01-01T01:01:01.001Z + */ + readonly timestamp: Date + /** + * Payload Data + * @description The data of the payload. + */ + readonly data: components['schemas']['Invoice'] + } + /** @description Payload for notification event with `invoice.updated` type. */ + NotificationEventInvoiceUpdatedPayload: { + /** + * Notification Event Identifier + * @description A unique identifier for the notification event the payload belongs to. + * @example 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + */ + readonly id: string + /** + * @description Type of the notification event. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'invoice.updated' + /** + * Creation Time + * Format: date-time + * @description Timestamp when the notification event was created in RFC 3339 format. + * @example 2023-01-01T01:01:01.001Z + */ + readonly timestamp: Date + /** + * Payload Data + * @description The data of the payload. + */ + readonly data: components['schemas']['Invoice'] + } + /** + * @description Order by options for notification channels. + * @enum {string} + */ + NotificationEventOrderBy: 'id' | 'createdAt' + /** @description Paginated response */ + NotificationEventPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['NotificationEvent'][] + } + /** @description The delivery status of the notification event. */ + NotificationEventPayload: + | components['schemas']['NotificationEventResetPayload'] + | components['schemas']['NotificationEventBalanceThresholdPayload'] + | components['schemas']['NotificationEventInvoiceCreatedPayload'] + | components['schemas']['NotificationEventInvoiceUpdatedPayload'] + /** @description A notification event that will be re-sent. */ + NotificationEventResendRequest: { + /** + * Channels + * @description Notification channels to which the event should be re-sent. + */ + channels?: string[] + } + /** @description Payload for notification event with `entitlements.reset` type. */ + NotificationEventResetPayload: { + /** + * Notification Event Identifier + * @description A unique identifier for the notification event the payload belongs to. + * @example 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + */ + readonly id: string + /** + * @description Type of the notification event. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'entitlements.reset' + /** + * Creation Time + * Format: date-time + * @description Timestamp when the notification event was created in RFC 3339 format. + * @example 2023-01-01T01:01:01.001Z + */ + readonly timestamp: Date + /** + * Payload Data + * @description The data of the payload. + */ + readonly data: components['schemas']['NotificationEventEntitlementValuePayloadBase'] + } + /** + * @description Type of the notification event. + * @enum {string} + */ + NotificationEventType: + | 'entitlements.balance.threshold' + | 'entitlements.reset' + | 'invoice.created' + | 'invoice.updated' + /** @description Notification Rule. */ + NotificationRule: + | components['schemas']['NotificationRuleBalanceThreshold'] + | components['schemas']['NotificationRuleEntitlementReset'] + | components['schemas']['NotificationRuleInvoiceCreated'] + | components['schemas']['NotificationRuleInvoiceUpdated'] + /** @description Notification rule with entitlements.balance.threshold type. */ + NotificationRuleBalanceThreshold: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Rule Unique Identifier + * @description Identifies the notification rule. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'entitlements.balance.threshold' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Channels assigned to Rule + * @description List of notification channels the rule applies to. + */ + channels: components['schemas']['NotificationChannelMeta'][] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Entitlement Balance Thresholds + * @description List of thresholds the rule suppose to be triggered. + */ + thresholds: components['schemas']['NotificationRuleBalanceThresholdValue'][] + /** + * Features + * @description Optional field containing list of features the rule applies to. + */ + features?: components['schemas']['FeatureMeta'][] + } + /** @description Request with input parameters for creating new notification rule with entitlements.balance.threshold type. */ + NotificationRuleBalanceThresholdCreateRequest: { + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'entitlements.balance.threshold' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Entitlement Balance Thresholds + * @description List of thresholds the rule suppose to be triggered. + */ + thresholds: components['schemas']['NotificationRuleBalanceThresholdValue'][] + /** + * Channels + * @description List of notification channels the rule is applied to. + */ + channels: string[] + /** + * Features + * @description Optional field for defining the scope of notification by feature. It may contain features by id or key. + */ + features?: string[] + } + /** @description Threshold value with multiple supported types. */ + NotificationRuleBalanceThresholdValue: { + /** + * Threshold Value + * Format: double + * @description Value of the threshold. + * @example 100 + */ + value: number + /** + * @description Type of the threshold. + * @example usage_value + */ + type: components['schemas']['NotificationRuleBalanceThresholdValueType'] + } + /** + * Notification balance threshold type + * @description Type of the rule in the balance threshold specification: + * * `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period + * * `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period + * * `usage_value`: threshold defined by the usage value in the current usage period + * * `NUMBER` (**deprecated**): see `usage_value` + * * `PERCENT` (**deprecated**): see `usage_percentage` + * @enum {string} + */ + NotificationRuleBalanceThresholdValueType: + | 'PERCENT' + | 'NUMBER' + | 'balance_value' + | 'usage_percentage' + | 'usage_value' + /** @description Union type for requests creating new notification rule with certain type. */ + NotificationRuleCreateRequest: + | components['schemas']['NotificationRuleBalanceThresholdCreateRequest'] + | components['schemas']['NotificationRuleEntitlementResetCreateRequest'] + | components['schemas']['NotificationRuleInvoiceCreatedCreateRequest'] + | components['schemas']['NotificationRuleInvoiceUpdatedCreateRequest'] + /** @description Notification rule with entitlements.reset type. */ + NotificationRuleEntitlementReset: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Rule Unique Identifier + * @description Identifies the notification rule. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'entitlements.reset' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Channels assigned to Rule + * @description List of notification channels the rule applies to. + */ + channels: components['schemas']['NotificationChannelMeta'][] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Features + * @description Optional field containing list of features the rule applies to. + */ + features?: components['schemas']['FeatureMeta'][] + } + /** @description Request with input parameters for creating new notification rule with entitlements.reset type. */ + NotificationRuleEntitlementResetCreateRequest: { + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'entitlements.reset' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Channels + * @description List of notification channels the rule is applied to. + */ + channels: string[] + /** + * Features + * @description Optional field for defining the scope of notification by feature. It may contain features by id or key. + */ + features?: string[] + } + /** @description Notification rule with invoice.created type. */ + NotificationRuleInvoiceCreated: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Rule Unique Identifier + * @description Identifies the notification rule. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'invoice.created' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Channels assigned to Rule + * @description List of notification channels the rule applies to. + */ + channels: components['schemas']['NotificationChannelMeta'][] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + } + /** @description Request with input parameters for creating new notification rule with invoice.created type. */ + NotificationRuleInvoiceCreatedCreateRequest: { + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'invoice.created' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Channels + * @description List of notification channels the rule is applied to. + */ + channels: string[] + } + /** @description Notification rule with invoice.updated type. */ + NotificationRuleInvoiceUpdated: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Rule Unique Identifier + * @description Identifies the notification rule. + * @example 01ARZ3NDEKTSV4RRFFQ69G5FAV + */ + readonly id: string + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'invoice.updated' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Channels assigned to Rule + * @description List of notification channels the rule applies to. + */ + channels: components['schemas']['NotificationChannelMeta'][] + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + } + /** @description Request with input parameters for creating new notification rule with invoice.updated type. */ + NotificationRuleInvoiceUpdatedCreateRequest: { + /** + * @description Notification rule type. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'invoice.updated' + /** + * Rule Name + * @description The user friendly name of the notification rule. + * @example Balance threshold reached + */ + name: string + /** + * Rule Disabled + * @description Whether the rule is disabled or not. + * @default false + * @example true + */ + disabled?: boolean + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Channels + * @description List of notification channels the rule is applied to. + */ + channels: string[] + } + /** + * @description Order by options for notification channels. + * @enum {string} + */ + NotificationRuleOrderBy: 'id' | 'type' | 'createdAt' | 'updatedAt' + /** @description Paginated response */ + NotificationRulePaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['NotificationRule'][] + } + /** @description Numeric represents an arbitrary precision number. */ + Numeric: string + /** + * @description OAuth2 authorization code grant error types. + * @enum {string} + */ + OAuth2AuthorizationCodeGrantErrorType: + | 'invalid_request' + | 'unauthorized_client' + | 'access_denied' + | 'unsupported_response_type' + | 'invalid_scope' + | 'server_error' + | 'temporarily_unavailable' + /** @description Package price with spend commitments. */ + PackagePriceWithCommitments: { + /** + * @description The type of the price. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'package' + /** + * Amount + * @description The price of one package. + */ + amount: components['schemas']['Numeric'] + /** + * Quantity per package + * @description The quantity per package. + */ + quantityPerPackage: components['schemas']['Numeric'] + /** + * Minimum amount + * @description The customer is committed to spend at least the amount. + */ + minimumAmount?: components['schemas']['Numeric'] + /** + * Maximum amount + * @description The customer is limited to spend at most the amount. + */ + maximumAmount?: components['schemas']['Numeric'] + } + /** @description PaymentDueDate contains an amount that should be paid by the given date. */ + PaymentDueDate: { + /** + * Format: date-time + * @description When the payment is due. + * @example 2023-01-01T01:01:01.001Z + */ + readonly dueAt: Date + /** @description Other details to take into account for the due date. */ + readonly notes?: string + /** @description How much needs to be paid by the date. */ + readonly amount: components['schemas']['Numeric'] + /** @description Percentage of the total that should be paid by the date. */ + readonly percent?: components['schemas']['Percentage'] + /** @description If different from the parent document's base currency. */ + readonly currency?: components['schemas']['CurrencyCode'] + } + /** @description PaymentTermDueDate defines the terms for payment on a specific date. */ + PaymentTermDueDate: { + /** + * @description Type of terms to be applied. + * @enum {string} + */ + type: 'due_date' + /** @description Text detail of the chosen payment terms. */ + readonly detail?: string + /** @description Description of the conditions for payment. */ + readonly notes?: string + /** @description When the payment is due. */ + readonly dueAt: components['schemas']['PaymentDueDate'][] + } + /** @description PaymentTermInstant defines the terms for payment on receipt of invoice. */ + PaymentTermInstant: { + /** + * @description Type of terms to be applied. + * @enum {string} + */ + type: 'instant' + /** @description Text detail of the chosen payment terms. */ + readonly detail?: string + /** @description Description of the conditions for payment. */ + readonly notes?: string + } + /** @description PaymentTerms defines the terms for payment. */ + PaymentTerms: + | components['schemas']['PaymentTermInstant'] + | components['schemas']['PaymentTermDueDate'] + /** + * Format: double + * @description Numeric representation of a percentage + * + * 50% is represented as 50 + * @example 50 + */ + Percentage: number + /** @description A period with a start and end time. */ + Period: { + /** + * Format: date-time + * @description Period start time. + * @example 2023-01-01T01:01:01.001Z + */ + from: Date + /** + * Format: date-time + * @description Period end time. + * @example 2023-02-01T01:01:01.001Z + */ + to: Date + } + /** @description Plans provide a template for subscriptions. */ + Plan: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** @description Alignment configuration for the plan. */ + alignment?: components['schemas']['Alignment'] + /** + * Version + * @description Version of the plan. Incremented when the plan is updated. + * @default 1 + */ + readonly version: number + /** + * Currency + * @description The currency code of the plan. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Billing cadence + * Format: duration + * @description The default billing cadence for subscriptions using this plan. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + * @example P1M + */ + billingCadence: string + /** + * Pro-rating configuration + * @description Default pro-rating configuration for subscriptions using this plan. + * @default { + * "enabled": true, + * "mode": "prorate_prices" + * } + */ + proRatingConfig?: components['schemas']['ProRatingConfig'] + /** + * Effective start date + * Format: date-time + * @description The date and time when the plan becomes effective. When not specified, the plan is a draft. + * @example 2023-01-01T01:01:01.001Z + */ + readonly effectiveFrom?: Date + /** + * Effective end date + * Format: date-time + * @description The date and time when the plan is no longer effective. When not specified, the plan is effective indefinitely. + * @example 2023-01-01T01:01:01.001Z + */ + readonly effectiveTo?: Date + /** + * Status + * @description The status of the plan. + * Computed based on the effective start and end dates: + * - draft = no effectiveFrom + * - active = effectiveFrom <= now < effectiveTo + * - archived / inactive = effectiveTo <= now + * - scheduled = now < effectiveFrom < effectiveTo + */ + readonly status: components['schemas']['PlanStatus'] + /** + * Settlement mode + * @description The settlement mode of the plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + * @default credit_then_invoice + */ + settlementMode?: components['schemas']['BillingSettlementMode'] + /** + * Plan phases + * @description The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + * A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + */ + phases: components['schemas']['PlanPhase'][] + /** + * Validation errors + * @description List of validation errors. + */ + readonly validationErrors: + | components['schemas']['ValidationError'][] + | null + } + /** @description The PlanAddon describes the association between a plan and add-on. */ + PlanAddon: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] + /** + * Addon + * @description Add-on object. + */ + readonly addon: components['schemas']['Addon'] + /** + * The plan phase from the add-on becomes purchasable + * @description The key of the plan phase from the add-on becomes available for purchase. + */ + fromPlanPhase: string + /** + * Max quantity of the add-on + * @description The maximum number of times the add-on can be purchased for the plan. + * It is not applicable for add-ons with single instance type. + */ + maxQuantity?: number + /** + * Validation errors + * @description List of validation errors. + */ + readonly validationErrors: + | components['schemas']['ValidationError'][] + | null + } + /** @description A plan add-on assignment create request. */ + PlanAddonCreate: { + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] + /** + * The plan phase from the add-on becomes purchasable + * @description The key of the plan phase from the add-on becomes available for purchase. + */ + fromPlanPhase: string + /** + * Max quantity of the add-on + * @description The maximum number of times the add-on can be purchased for the plan. + * It is not applicable for add-ons with single instance type. + */ + maxQuantity?: number + /** + * Add-on unique identifier + * @description The add-on unique identifier in ULID format. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + addonId: string + } + /** + * @description Order by options for plan add-on assignments. + * @enum {string} + */ + PlanAddonOrderBy: 'id' | 'key' | 'version' | 'created_at' | 'updated_at' + /** @description Paginated response */ + PlanAddonPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['PlanAddon'][] + } + /** @description Resource update operation model. */ + PlanAddonReplaceUpdate: { + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] + /** + * The plan phase from the add-on becomes purchasable + * @description The key of the plan phase from the add-on becomes available for purchase. + */ + fromPlanPhase: string + /** + * Max quantity of the add-on + * @description The maximum number of times the add-on can be purchased for the plan. + * It is not applicable for add-ons with single instance type. + */ + maxQuantity?: number + } + /** @description Resource create operation model. */ + PlanCreate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** @description Alignment configuration for the plan. */ + alignment?: components['schemas']['Alignment'] + /** + * Currency + * @description The currency code of the plan. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Billing cadence + * Format: duration + * @description The default billing cadence for subscriptions using this plan. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + * @example P1M + */ + billingCadence: string + /** + * Pro-rating configuration + * @description Default pro-rating configuration for subscriptions using this plan. + * @default { + * "enabled": true, + * "mode": "prorate_prices" + * } + */ + proRatingConfig?: components['schemas']['ProRatingConfig'] + /** + * Settlement mode + * @description The settlement mode of the plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + * @default credit_then_invoice + */ + settlementMode?: components['schemas']['BillingSettlementMode'] + /** + * Plan phases + * @description The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + * A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + */ + phases: components['schemas']['PlanPhase'][] + } + /** + * @description Order by options for plans. + * @enum {string} + */ + PlanOrderBy: 'id' | 'key' | 'version' | 'created_at' | 'updated_at' + /** @description Paginated response */ + PlanPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Plan'][] + } + /** @description The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. */ + PlanPhase: { + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Duration + * Format: duration + * @description The duration of the phase. + * @example P1Y + */ + duration: string | null + /** + * Rate cards + * @description The rate cards of the plan. + */ + rateCards: components['schemas']['RateCard'][] + } + /** @description References an exact plan. */ + PlanReference: { + /** + * @description The plan ID. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + /** @description The plan key. */ + key: string + /** @description The plan version. */ + version: number + } + /** @description References an exact plan defaulting to the current active version. */ + PlanReferenceInput: { + /** @description The plan key. */ + key: string + /** @description The plan version. */ + version?: number + } + /** @description Resource update operation model. */ + PlanReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** @description Alignment configuration for the plan. */ + alignment?: components['schemas']['Alignment'] + /** + * Billing cadence + * Format: duration + * @description The default billing cadence for subscriptions using this plan. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + * @example P1M + */ + billingCadence: string + /** + * Pro-rating configuration + * @description Default pro-rating configuration for subscriptions using this plan. + * @default { + * "enabled": true, + * "mode": "prorate_prices" + * } + */ + proRatingConfig?: components['schemas']['ProRatingConfig'] + /** + * Settlement mode + * @description The settlement mode of the plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + * @default credit_then_invoice + */ + settlementMode?: components['schemas']['BillingSettlementMode'] + /** + * Plan phases + * @description The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + * A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + */ + phases: components['schemas']['PlanPhase'][] + } + /** + * @description The status of a plan. + * @enum {string} + */ + PlanStatus: 'draft' | 'active' | 'archived' | 'scheduled' + /** @description Change subscription based on plan. */ + PlanSubscriptionChange: { + /** + * @description Timing configuration for the change, when the change should take effect. + * For changing a subscription, the accepted values depend on the subscription configuration. + */ + timing: components['schemas']['SubscriptionTiming'] + /** @description What alignment settings the subscription should have. */ + alignment?: components['schemas']['Alignment'] + /** @description Arbitrary metadata associated with the subscription. */ + metadata?: components['schemas']['Metadata'] + /** @description The plan reference to change to. */ + plan: components['schemas']['PlanReferenceInput'] + /** + * @description The key of the phase to start the subscription in. + * If not provided, the subscription will start in the first phase of the plan. + */ + startingPhase?: string + /** @description The name of the Subscription. If not provided the plan name is used. */ + name?: string + /** @description Description for the Subscription. */ + description?: string + /** + * Format: date-time + * @description The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + * @example 2023-01-01T01:01:01.001Z + */ + billingAnchor?: Date + /** @description The settlement mode of the subscription. */ + settlementMode?: components['schemas']['BillingSettlementMode'] + } + /** + * Create from plan + * @description Create subscription based on plan. + */ + PlanSubscriptionCreate: { + /** @description What alignment settings the subscription should have. */ + alignment?: components['schemas']['Alignment'] + /** @description Arbitrary metadata associated with the subscription. */ + metadata?: components['schemas']['Metadata'] + /** @description The plan reference to change to. */ + plan: components['schemas']['PlanReferenceInput'] + /** + * @description The key of the phase to start the subscription in. + * If not provided, the subscription will start in the first phase of the plan. + */ + startingPhase?: string + /** @description The name of the Subscription. If not provided the plan name is used. */ + name?: string + /** @description Description for the Subscription. */ + description?: string + /** @description The settlement mode of the subscription. */ + settlementMode?: components['schemas']['BillingSettlementMode'] + /** + * @description Timing configuration for the change, when the change should take effect. + * The default is immediate. + * @default immediate + */ + timing?: components['schemas']['SubscriptionTiming'] + /** + * @description The ID of the customer. Provide either the key or ID. Has presedence over the key. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId?: string + /** @description The key of the customer. Provide either the key or ID. */ + customerKey?: string + /** + * Format: date-time + * @description The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + * @example 2023-01-01T01:01:01.001Z + */ + billingAnchor?: Date + } + /** + * @description A consumer portal token. + * + * Validator doesn't obey required for readOnly properties + * See: https://github.com/stoplightio/spectral/issues/1274 + */ + PortalToken: { + /** + * @description ULID (Universally Unique Lexicographically Sortable Identifier). + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id?: string + /** @example customer-1 */ + subject: string + /** + * Format: date-time + * @description [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + * @example 2023-01-01T01:01:01.001Z + */ + readonly expiresAt?: Date + readonly expired?: boolean + /** + * Format: date-time + * @description [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC. + * @example 2023-01-01T01:01:01.001Z + */ + readonly createdAt?: Date + /** + * @description The token is only returned at creation. + * @example om_portal_IAnD3PpWW2A2Wr8m9jfzeHlGX8xmCXwG.y5q4S-AWqFu6qjfaFz0zQq4Ez28RsnyVwJffX5qxMvo + */ + readonly token?: string + /** + * @description Optional, if defined only the specified meters will be allowed. + * @example [ + * "tokens_total" + * ] + */ + allowedMeterSlugs?: string[] + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + PreconditionFailedProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** + * @description The payment term of a flat price. + * One of: in_advance or in_arrears. + * @enum {string} + */ + PricePaymentTerm: 'in_advance' | 'in_arrears' + /** + * @description A price tier. + * At least one price component is required in each tier. + */ + PriceTier: { + /** + * Up to quantity + * @description Up to and including to this quantity will be contained in the tier. + * If null, the tier is open-ended. + */ + upToAmount?: components['schemas']['Numeric'] + /** + * Flat price component + * @description The flat price component of the tier. + */ + flatPrice: components['schemas']['FlatPrice'] | null + /** + * Unit price component + * @description The unit price component of the tier. + */ + unitPrice: components['schemas']['UnitPrice'] | null + } + /** @description Configuration for pro-rating behavior. */ + ProRatingConfig: { + /** + * Enable pro-rating + * @description Whether pro-rating is enabled for this plan. + * @default true + */ + enabled: boolean + /** + * Pro-rating mode + * @description How to handle pro-rating for billing period changes. + * @default prorate_prices + */ + mode: components['schemas']['ProRatingMode'] + } + /** + * @description Pro-rating mode options for handling billing period changes. + * @enum {string} + */ + ProRatingMode: 'prorate_prices' + /** @description Progress describes a progress of a task. */ + Progress: { + /** + * Format: uint64 + * @description Success is the number of items that succeeded + */ + success: number + /** + * Format: uint64 + * @description Failed is the number of items that failed + */ + failed: number + /** + * Format: uint64 + * @description The total number of items to process + */ + total: number + /** + * Format: date-time + * @description The time the progress was last updated + * @example 2023-01-01T01:01:01.001Z + */ + updatedAt: Date + } + /** @description A rate card defines the pricing and entitlement of a feature or service. */ + RateCard: + | components['schemas']['RateCardFlatFee'] + | components['schemas']['RateCardUsageBased'] + /** @description Entitlement template of a boolean entitlement. */ + RateCardBooleanEntitlement: { + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'boolean' + } + /** + * @description Entitlement templates are used to define the entitlements of a plan. + * Features are omitted from the entitlement template, as they are defined in the rate card. + */ + RateCardEntitlement: + | components['schemas']['RateCardMeteredEntitlement'] + | components['schemas']['RateCardStaticEntitlement'] + | components['schemas']['RateCardBooleanEntitlement'] + /** @description A flat fee rate card defines a one-time purchase or a recurring fee. */ + RateCardFlatFee: { + /** + * @description The type of the RateCard. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'flat_fee' + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Feature key + * @description The feature the customer is entitled to use. + */ + featureKey?: string + /** + * @description The entitlement of the rate card. + * Only available when featureKey is set. + */ + entitlementTemplate?: components['schemas']['RateCardEntitlement'] + /** + * Tax config + * @description The tax config of the rate card. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * Billing cadence + * Format: duration + * @description The billing cadence of the rate card. + * When null it means it is a one time fee. + */ + billingCadence: string | null + /** + * Price + * @description The price of the rate card. + * When null, the feature or service is free. + * @example { + * "type": "flat", + * "amount": "100", + * "paymentTerm": "in_arrears" + * } + */ + price: components['schemas']['FlatPriceWithPaymentTerm'] | null + /** + * Discounts + * @description The discount of the rate card. For flat fee rate cards only percentage discounts are supported. + * Only available when price is set. + */ + discounts?: components['schemas']['Discounts'] + } + /** @description The entitlement template with a metered entitlement. */ + RateCardMeteredEntitlement: { + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'metered' + /** + * Soft limit + * @description If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + * @default false + */ + isSoftLimit?: boolean + /** + * Initial grant amount + * Format: double + * @description You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + issueAfterReset?: number + /** + * Issue grant after reset priority + * Format: uint8 + * @description Defines the grant priority for the default grant. + * @default 1 + */ + issueAfterResetPriority?: number + /** + * Preserve overage at reset + * @description If true, the overage is preserved at reset. If false, the usage is reset to 0. + * @default false + */ + preserveOverageAtReset?: boolean + /** + * Usage Period + * Format: duration + * @description The interval of the metered entitlement. + * Defaults to the billing cadence of the rate card. + */ + usagePeriod?: string + } + /** @description Entitlement template of a static entitlement. */ + RateCardStaticEntitlement: { + /** @description Additional metadata for the feature. */ + metadata?: components['schemas']['Metadata'] + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + type: 'static' + /** + * Format: json + * @description The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + * @example { "integrations": ["github"] } + */ + config: string + } + /** @description A usage-based rate card defines a price based on usage. */ + RateCardUsageBased: { + /** + * @description The type of the RateCard. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'usage_based' + /** + * Key + * @description A semi-unique identifier for the resource. + */ + key: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Feature key + * @description The feature the customer is entitled to use. + */ + featureKey?: string + /** + * @description The entitlement of the rate card. + * Only available when featureKey is set. + */ + entitlementTemplate?: components['schemas']['RateCardEntitlement'] + /** + * Tax config + * @description The tax config of the rate card. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + taxConfig?: components['schemas']['TaxConfig'] + /** + * Billing cadence + * Format: duration + * @description The billing cadence of the rate card. + */ + billingCadence: string + /** + * @description The price of the rate card. + * When null, the feature or service is free. + */ + price: components['schemas']['RateCardUsageBasedPrice'] | null + /** + * Discounts + * @description The discounts of the rate card. + * + * Flat fee rate cards only support percentage discounts. + */ + discounts?: components['schemas']['Discounts'] + } + /** @description The price of the usage based rate card. */ + RateCardUsageBasedPrice: + | components['schemas']['FlatPriceWithPaymentTerm'] + | components['schemas']['UnitPriceWithCommitments'] + | components['schemas']['TieredPriceWithCommitments'] + | components['schemas']['DynamicPriceWithCommitments'] + | components['schemas']['PackagePriceWithCommitments'] + /** + * @deprecated + * @description Recurring period with an interval and an anchor. + * @example { + * "interval": "DAY", + * "intervalISO": "P1D", + * "anchor": "2023-01-01T01:01:01.001Z" + * } + */ + RecurringPeriod: { + /** + * Interval + * @description The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + */ + interval: components['schemas']['RecurringPeriodInterval'] + /** + * Anchor time + * Format: date-time + * @description A date-time anchor to base the recurring period on. + * @example 2023-01-01T01:01:01.001Z + */ + anchor: Date + /** + * Format: duration + * @description The unit of time for the interval in ISO8601 format. + */ + intervalISO: string + } + /** + * @description Recurring period with an interval and an anchor. + * @example { + * "interval": "DAY", + * "anchor": "2023-01-01T01:01:01.001Z" + * } + */ + RecurringPeriodCreateInput: { + /** + * Interval + * @description The unit of time for the interval. + */ + interval: components['schemas']['RecurringPeriodInterval'] + /** + * Anchor time + * Format: date-time + * @description A date-time anchor to base the recurring period on. + * @example 2023-01-01T01:01:01.001Z + */ + anchor?: Date + } + /** @description Period duration for the recurrence */ + RecurringPeriodInterval: + | string + | components['schemas']['RecurringPeriodIntervalEnum'] + /** + * @description The unit of time for the interval. + * One of: `day`, `week`, `month`, or `year`. + * @enum {string} + */ + RecurringPeriodIntervalEnum: 'DAY' | 'WEEK' | 'MONTH' | 'YEAR' + /** @description Recurring period with an interval and an anchor. */ + RecurringPeriodV2: { + /** + * Interval + * @description The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + */ + interval: components['schemas']['RecurringPeriodInterval'] + /** + * Anchor time + * Format: date-time + * @description A date-time anchor to base the recurring period on. + * @example 2023-01-01T01:01:01.001Z + */ + anchor: Date + } + /** + * @description The direction of the phase shift when a phase is removed. + * @enum {string} + */ + RemovePhaseShifting: 'next' | 'prev' + /** @description Reset parameters */ + ResetEntitlementUsageInput: { + /** + * Format: date-time + * @description The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored. + * @example 2023-01-01T01:01:01.001Z + */ + effectiveAt?: Date + /** + * @description Determines whether the usage period anchor is retained or reset to the effectiveAt time. + * - If true, the usage period anchor is retained. + * - If false, the usage period anchor is reset to the effectiveAt time. + */ + retainAnchor?: boolean + /** + * @description Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior. + * - If true, the overage is preserved. + * - If false, the overage is forgiven. + */ + preserveOverage?: boolean + } + /** + * @description Sandbox app can be used for testing OpenMeter features. + * + * The app is not creating anything in external systems, thus it is safe to use for + * verifying OpenMeter features. + */ + SandboxApp: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description The marketplace listing that this installed app is based on. */ + readonly listing: components['schemas']['MarketplaceListing'] + /** @description Status of the app connection. */ + readonly status: components['schemas']['AppStatus'] + /** + * @description The app's type is Sandbox. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'sandbox' + } + /** @description Resource update operation model. */ + SandboxAppReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * @description The app's type is Sandbox. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'sandbox' + } + /** @description Sandbox Customer App Data. */ + SandboxCustomerAppData: { + /** @description The installed sandbox app this data belongs to. */ + readonly app?: components['schemas']['SandboxApp'] + /** + * App ID + * @description The app ID. + * If not provided, it will use the global default for the app type. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id?: string + /** + * @description The app name. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'sandbox' + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + ServiceUnavailableProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** + * @description The order direction. + * @enum {string} + */ + SortOrder: 'ASC' | 'DESC' + /** + * @description The Stripe API key input. + * Used to authenticate with the Stripe API. + */ + StripeAPIKeyInput: { + secretAPIKey: string + } + /** + * @description A installed Stripe app object. + * @example { + * "id": "01G65Z755AFWAKHE12NY0CQ9FH", + * "type": "stripe", + * "name": "Stripe", + * "status": "ready", + * "listing": { + * "type": "stripe", + * "name": "Stripe", + * "description": "Stripe integration allows you to collect payments with Stripe.", + * "capabilities": [ + * { + * "type": "calculateTax", + * "key": "stripe_calculate_tax", + * "name": "Calculate Tax", + * "description": "Stripe Tax calculates tax portion of the invoices." + * }, + * { + * "type": "invoiceCustomers", + * "key": "stripe_invoice_customers", + * "name": "Invoice Customers", + * "description": "Stripe invoices customers with due amount." + * }, + * { + * "type": "collectPayments", + * "key": "stripe_collect_payments", + * "name": "Collect Payments", + * "description": "Stripe payments collects outstanding revenue with Stripe customer's default payment method." + * } + * ], + * "installMethods": [ + * "with_oauth2", + * "with_api_key" + * ] + * }, + * "createdAt": "2024-01-01T01:01:01.001Z", + * "updatedAt": "2024-01-01T01:01:01.001Z", + * "stripeAccountId": "acct_123456789", + * "livemode": true, + * "maskedAPIKey": "sk_live_************abc" + * } + */ + StripeApp: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description The marketplace listing that this installed app is based on. */ + readonly listing: components['schemas']['MarketplaceListing'] + /** @description Status of the app connection. */ + readonly status: components['schemas']['AppStatus'] + /** + * @description The app's type is Stripe. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'stripe' + /** @description The Stripe account ID. */ + readonly stripeAccountId: string + /** @description Livemode, true if the app is in production mode. */ + readonly livemode: boolean + /** + * @description The masked API key. + * Only shows the first 8 and last 3 characters. + */ + readonly maskedAPIKey: string + } + /** @description Resource update operation model. */ + StripeAppReplaceUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * @description The app's type is Stripe. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'stripe' + /** + * Format: password + * @description The Stripe API key. + */ + secretAPIKey?: string + } + /** + * @description Stripe CheckoutSession.mode + * @enum {string} + */ + StripeCheckoutSessionMode: 'setup' + /** + * @description Stripe Customer App Data. + * @example { + * "type": "stripe", + * "stripeCustomerId": "cus_xxxxxxxxxxxxxx" + * } + */ + StripeCustomerAppData: { + /** + * App ID + * @description The app ID. + * If not provided, it will use the global default for the app type. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id?: string + /** + * @description The app name. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'stripe' + /** @description The Stripe customer ID. */ + stripeCustomerId: string + /** @description The Stripe default payment method ID. */ + stripeDefaultPaymentMethodId?: string + /** @description The installed stripe app this data belongs to. */ + readonly app?: components['schemas']['StripeApp'] + } + /** @description Stripe Customer App Data Base. */ + StripeCustomerAppDataBase: { + /** @description The Stripe customer ID. */ + stripeCustomerId: string + /** @description The Stripe default payment method ID. */ + stripeDefaultPaymentMethodId?: string + } + /** + * @description Stripe Customer App Data. + * @example { + * "type": "stripe", + * "stripeCustomerId": "cus_xxxxxxxxxxxxxx" + * } + */ + StripeCustomerAppDataCreateOrUpdateItem: { + /** + * App ID + * @description The app ID. + * If not provided, it will use the global default for the app type. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id?: string + /** + * @description The app name. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'stripe' + /** @description The Stripe customer ID. */ + stripeCustomerId: string + /** @description The Stripe default payment method ID. */ + stripeDefaultPaymentMethodId?: string + } + /** + * @description Stripe customer portal session. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object + */ + StripeCustomerPortalSession: { + /** + * @description The ID of the customer portal session. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + */ + id: string + /** @description The ID of the stripe customer. */ + stripeCustomerId: string + /** + * @description Configuration used to customize the customer portal. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + */ + configurationId: string + /** + * @description Livemode. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + */ + livemode: boolean + /** + * Format: date-time + * @description Created at. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + * @example 2023-01-01T01:01:01.001Z + */ + createdAt: Date + /** + * @description Return URL. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + */ + returnUrl: string + /** + * @description Status. + * /** + * The IETF language tag of the locale customer portal is displayed in. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + */ + locale: string + /** + * @description /** + * The ID of the customer.The URL to redirect the customer to after they have completed + * their requested actions. + */ + url: string + } + /** @description The tax config for Stripe. */ + StripeTaxConfig: { + /** + * Tax code + * @description Product tax code. + * + * See: https://docs.stripe.com/tax/tax-codes + * @example txcd_10000000 + */ + code: string + } + /** @description Stripe webhook event. */ + StripeWebhookEvent: { + /** @description The event ID. */ + id: string + /** @description The event type. */ + type: string + /** @description Live mode. */ + livemode: boolean + /** + * Format: int32 + * @description The event created timestamp. + */ + created: number + /** @description The event data. */ + data: { + object: unknown + } + } + /** @description Stripe webhook response. */ + StripeWebhookResponse: { + /** + * @description ULID (Universally Unique Lexicographically Sortable Identifier). + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + namespaceId: string + /** + * @description ULID (Universally Unique Lexicographically Sortable Identifier). + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + appId: string + /** + * @description ULID (Universally Unique Lexicographically Sortable Identifier). + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId?: string + message?: string + } + /** + * @deprecated + * @description A subject is a unique identifier for a usage attribution by its key. + * Subjects only exist in the concept of metering. + * Subjects are optional to create and work as an enrichment for the subject key like displayName, metadata, etc. + * Subjects are useful when you are reporting usage events with your own database ID but want to enrich the subject with a human-readable name or metadata. + * For most use cases, a subject is equivalent to a customer. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + * @example { + * "createdAt": "2025-01-01T01:01:01.001Z", + * "updatedAt": "2025-02-01T01:01:01.001Z", + * "deletedAt": "2025-03-01T01:01:01.001Z", + * "id": "01G65Z755AFWAKHE12NY0CQ9FH", + * "key": "customer-id", + * "displayName": "Customer Name", + * "metadata": { + * "hubspotId": "123456" + * }, + * "stripeCustomerId": "cus_JMOlctsKV8" + * } + */ + Subject: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description A unique identifier for the subject. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * @description A unique, human-readable identifier for the subject. + * This is typically a database ID or a customer key. + * @example customer-db-id-123 + */ + key: string + /** + * @description A human-readable display name for the subject. + * @example Customer Name + */ + displayName?: string | null + /** + * @description Metadata for the subject. + * @example { + * "hubspotId": "123456" + * } + */ + metadata?: { + [key: string]: unknown + } | null + /** + * Format: date-time + * @deprecated + * @description The start of the current period for the subject. + * @example 2023-01-01T00:00:00Z + */ + currentPeriodStart?: Date + /** + * Format: date-time + * @deprecated + * @description The end of the current period for the subject. + * @example 2023-02-01T00:00:00Z + */ + currentPeriodEnd?: Date + /** + * @deprecated + * @description The Stripe customer ID for the subject. + * @example cus_JMOlctsKV8 + */ + stripeCustomerId?: string | null + } + /** + * @deprecated + * @description A subject is a unique identifier for a user or entity. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + * @example { + * "key": "customer-id", + * "displayName": "Customer Name", + * "metadata": { + * "hubspotId": "123456" + * }, + * "stripeCustomerId": "cus_JMOlctsKV8" + * } + */ + SubjectUpsert: { + /** + * @description A unique, human-readable identifier for the subject. + * This is typically a database ID or a customer key. + * @example customer-db-id-123 + */ + key: string + /** + * @description A human-readable display name for the subject. + * @example Customer Name + */ + displayName?: string | null + /** + * @description Metadata for the subject. + * @example { + * "hubspotId": "123456" + * } + */ + metadata?: { + [key: string]: unknown + } | null + /** + * Format: date-time + * @deprecated + * @description The start of the current period for the subject. + * @example 2023-01-01T00:00:00Z + */ + currentPeriodStart?: Date + /** + * Format: date-time + * @deprecated + * @description The end of the current period for the subject. + * @example 2023-02-01T00:00:00Z + */ + currentPeriodEnd?: Date + /** + * @deprecated + * @description The Stripe customer ID for the subject. + * @example cus_JMOlctsKV8 + */ + stripeCustomerId?: string | null + } + /** @description Subscription is an exact subscription instance. */ + Subscription: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** @description Alignment configuration for the plan. */ + alignment?: components['schemas']['Alignment'] + /** @description The status of the subscription. */ + readonly status: components['schemas']['SubscriptionStatus'] + /** + * @description The customer ID of the subscription. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId: string + /** @description The plan of the subscription. */ + plan?: components['schemas']['PlanReference'] + /** + * Currency + * @description The currency code of the subscription. + * Will be revised once we add multi currency support. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Billing cadence + * Format: duration + * @description The billing cadence for the subscriptions. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + * @example P1M + */ + readonly billingCadence: string + /** + * Pro-rating configuration + * @description The pro-rating configuration for the subscriptions. + * @default { + * "enabled": true, + * "mode": "prorate_prices" + * } + */ + readonly proRatingConfig?: components['schemas']['ProRatingConfig'] + /** + * Billing anchor + * Format: date-time + * @description The normalizedbilling anchor of the subscription. + * @example 2023-01-01T01:01:01.001Z + */ + readonly billingAnchor: Date + /** + * Settlement mode + * @description The settlement mode of the subscription. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + * @default credit_then_invoice + */ + readonly settlementMode: components['schemas']['BillingSettlementMode'] + } + /** @description A subscription add-on, represents concrete instances of an add-on for a given subscription. */ + SubscriptionAddon: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + readonly activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + readonly activeTo?: Date + /** + * Addon + * @description Partially populated add-on properties. + */ + addon: { + /** + * ID + * @description The ID of the add-on. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + /** + * Key + * @description A semi-unique identifier for the resource. + */ + readonly key: string + /** + * Version + * @description The version of the Add-on which templates this instance. + * @default 1 + */ + readonly version: number + /** + * InstanceType + * @description The instance type of the add-on. + */ + readonly instanceType: components['schemas']['AddonInstanceType'] + } + /** + * QuantityAt + * Format: date-time + * @description For which point in time the quantity was resolved to. + * @example 2025-01-05T00:00:00Z + */ + readonly quantityAt: Date + /** + * Quantity + * @description The quantity of the add-on. Always 1 for single instance add-ons. + * @example 1 + */ + quantity: number + /** + * Timeline + * @description The timeline of the add-on. The returned periods are sorted and continuous. + * @example [ + * { + * "quantity": 1, + * "activeFrom": "2025-01-01T00:00:00Z", + * "activeTo": "2025-01-02T00:00:00Z" + * }, + * { + * "quantity": 0, + * "activeFrom": "2025-01-02T00:00:00Z", + * "activeTo": "2025-01-03T00:00:00Z" + * }, + * { + * "quantity": 1, + * "activeFrom": "2025-01-03T00:00:00Z" + * } + * ] + */ + readonly timeline: components['schemas']['SubscriptionAddonTimelineSegment'][] + /** + * SubscriptionID + * @description The ID of the subscription. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly subscriptionId: string + /** + * Rate cards + * @description The rate cards of the add-on. + */ + readonly rateCards: components['schemas']['SubscriptionAddonRateCard'][] + } + /** @description A subscription add-on create body. */ + SubscriptionAddonCreate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Quantity + * @description The quantity of the add-on. Always 1 for single instance add-ons. + * @example 1 + */ + quantity: number + /** + * Timing + * @description The timing of the operation. After the create or update, a new entry will be created in the timeline. + */ + timing: components['schemas']['SubscriptionTiming'] + /** + * Addon + * @description The add-on to create. + */ + addon: { + /** + * @description The ID of the add-on. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + id: string + } + } + /** @description A rate card for a subscription add-on. */ + SubscriptionAddonRateCard: { + /** + * Rate card + * @description The rate card. + */ + rateCard: components['schemas']['RateCard'] + /** + * Affected subscription item IDs + * @description The IDs of the subscription items that this rate card belongs to. + */ + readonly affectedSubscriptionItemIds: string[] + } + /** @description A subscription add-on event. */ + SubscriptionAddonTimelineSegment: { + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * Quantity + * @description The quantity of the add-on for the given period. + * @example 1 + */ + readonly quantity: number + } + /** @description Resource create or update operation model. */ + SubscriptionAddonUpdate: { + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name?: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Quantity + * @description The quantity of the add-on. Always 1 for single instance add-ons. + * @example 1 + */ + quantity?: number + /** + * Timing + * @description The timing of the operation. After the create or update, a new entry will be created in the timeline. + */ + timing?: components['schemas']['SubscriptionTiming'] + } + /** @description Alignment details enriched with the current billing period. */ + SubscriptionAlignment: { + /** + * @deprecated + * @description Whether all Billable items and RateCards must align. + * Alignment means the Price's BillingCadence must align for both duration and anchor time. + */ + billablesMustAlign?: boolean + /** @description The current billing period. Only has value if the subscription is aligned and active. */ + currentAlignedBillingPeriod?: components['schemas']['Period'] + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + SubscriptionBadRequestErrorResponse: { + /** + * Format: uri + * @description Type contains a URI that identifies the problem type. + * @default about:blank + * @example about:blank + */ + type: string + /** + * @description A a short, human-readable summary of the problem type. + * @example Bad Request + */ + title: string + /** + * Format: int16 + * @description The HTTP status code generated by the origin server for this occurrence of the problem. + * @example 400 + */ + status?: number + /** + * @description A human-readable explanation specific to this occurrence of the problem. + * @example The request body must be a JSON object. + */ + detail: string + /** + * Format: uri + * @description A URI reference that identifies the specific occurrence of the problem. + * @example urn:request:local/JMOlctsKV8-000001 + */ + instance: string + /** @description Additional properties specific to the problem type may be present. */ + extensions?: components['schemas']['SubscriptionErrorExtensions'] + } + /** @description Change a subscription. */ + SubscriptionChange: + | components['schemas']['PlanSubscriptionChange'] + | components['schemas']['CustomSubscriptionChange'] + /** @description Response body for subscription change. */ + SubscriptionChangeResponseBody: { + /** + * Current subscription + * @description The current subscription before the change. + */ + current: components['schemas']['Subscription'] + /** + * The subscription it will be changed to + * @description The new state of the subscription after the change. + */ + next: components['schemas']['SubscriptionExpanded'] + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + SubscriptionConflictErrorResponse: { + /** + * Format: uri + * @description Type contains a URI that identifies the problem type. + * @default about:blank + * @example about:blank + */ + type: string + /** + * @description A a short, human-readable summary of the problem type. + * @example Bad Request + */ + title: string + /** + * Format: int16 + * @description The HTTP status code generated by the origin server for this occurrence of the problem. + * @example 400 + */ + status?: number + /** + * @description A human-readable explanation specific to this occurrence of the problem. + * @example The request body must be a JSON object. + */ + detail: string + /** + * Format: uri + * @description A URI reference that identifies the specific occurrence of the problem. + * @example urn:request:local/JMOlctsKV8-000001 + */ + instance: string + /** @description Additional properties specific to the problem type may be present. */ + extensions?: components['schemas']['SubscriptionErrorExtensions'] + } + /** @description Create a subscription. */ + SubscriptionCreate: + | components['schemas']['PlanSubscriptionCreate'] + | components['schemas']['CustomSubscriptionCreate'] + /** @description Subscription edit input. */ + SubscriptionEdit: { + /** + * @description Batch processing commands for manipulating running subscriptions. + * The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + */ + customizations: components['schemas']['SubscriptionEditOperation'][] + /** @description Whether the billing period should be restarted.Timing configuration to allow for the changes to take effect at different times. */ + timing?: components['schemas']['SubscriptionTiming'] + } + /** @description The operation to be performed on the subscription. */ + SubscriptionEditOperation: + | components['schemas']['EditSubscriptionAddItem'] + | components['schemas']['EditSubscriptionRemoveItem'] + | components['schemas']['EditSubscriptionAddPhase'] + | components['schemas']['EditSubscriptionRemovePhase'] + | components['schemas']['EditSubscriptionStretchPhase'] + | components['schemas']['EditSubscriptionUnscheduleEdit'] + /** @description Error extensions for the Subscription Errors. */ + SubscriptionErrorExtensions: { + validationErrors: components['schemas']['ErrorExtension'][] + } + /** @description Expanded subscription */ + SubscriptionExpanded: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * Annotations + * @description Set of key-value pairs managed by the system. Cannot be modified by user. + */ + readonly annotations?: components['schemas']['Annotations'] + /** @description The status of the subscription. */ + readonly status: components['schemas']['SubscriptionStatus'] + /** + * @description The customer ID of the subscription. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + customerId: string + /** @description The plan of the subscription. */ + plan?: components['schemas']['PlanReference'] + /** + * Currency + * @description The currency code of the subscription. + * Will be revised once we add multi currency support. + * @default USD + */ + currency: components['schemas']['CurrencyCode'] + /** + * Billing cadence + * Format: duration + * @description The billing cadence for the subscriptions. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + * @example P1M + */ + readonly billingCadence: string + /** + * Pro-rating configuration + * @description The pro-rating configuration for the subscriptions. + * @default { + * "enabled": true, + * "mode": "prorate_prices" + * } + */ + readonly proRatingConfig?: components['schemas']['ProRatingConfig'] + /** + * Billing anchor + * Format: date-time + * @description The normalizedbilling anchor of the subscription. + * @example 2023-01-01T01:01:01.001Z + */ + readonly billingAnchor: Date + /** + * Settlement mode + * @description The settlement mode of the subscription. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + * @default credit_then_invoice + */ + readonly settlementMode: components['schemas']['BillingSettlementMode'] + /** @description Alignment details enriched with the current billing period. */ + alignment?: components['schemas']['SubscriptionAlignment'] + /** @description The phases of the subscription. */ + phases: components['schemas']['SubscriptionPhaseExpanded'][] + } + /** @description The actual contents of the Subscription, what the user gets, what they pay, etc... */ + SubscriptionItem: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * Format: date-time + * @description The cadence start of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The cadence end of the resource. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The identifier of the RateCard. + * SubscriptionItem/RateCard can be identified, it has a reference: + * + * 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + * 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across versions) + * 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version of a Feature + * + * 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + * + * We say "referenced by the Price" regardless of how a price itself is referenced, it colloquially makes sense to say "paying the same price for the same thing". In practice this should be derived from what's printed on the invoice line-item. + */ + key: string + /** @description The feature's key (if present). */ + featureKey?: string + /** + * Billing cadence + * Format: duration + * @description The billing cadence of the rate card. + * When null, the rate card is a one-time purchase. + */ + billingCadence: string | null + /** + * Price + * @description The price of the rate card. + * When null, the feature or service is free. + * @example { + * "type": "flat", + * "amount": "100", + * "paymentTerm": "in_arrears" + * } + */ + price: components['schemas']['RateCardUsageBasedPrice'] | null + /** + * Discounts + * @description The discounts applied to the rate card. + */ + discounts?: components['schemas']['Discounts'] + /** @description Describes what access is gained via the SubscriptionItem */ + included?: components['schemas']['SubscriptionItemIncluded'] + /** + * Tax config + * @description The tax config of the Subscription Item. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + taxConfig?: components['schemas']['TaxConfig'] + } + /** @description Included contents like Entitlement, or the Feature. */ + SubscriptionItemIncluded: { + /** @description The feature the customer is entitled to use. */ + feature: components['schemas']['Feature'] + /** @description The entitlement of the Subscription Item. */ + entitlement?: components['schemas']['Entitlement'] + } + /** @description Paginated response */ + SubscriptionPaginatedResponse: { + /** + * @description The total number of items. + * @example 500 + */ + totalCount: number + /** + * @description The page index. + * @example 1 + */ + page: number + /** + * @description The maximum number of items per page. + * @example 100 + */ + pageSize: number + /** @description The items in the current page. */ + items: components['schemas']['Subscription'][] + } + /** @description Subscription phase create input. */ + SubscriptionPhaseCreate: { + /** + * Start after + * Format: duration + * @description Interval after the subscription starts to transition to the phase. + * When null, the phase starts immediately after the subscription starts. + * @example P1Y + */ + startAfter: string | null + /** + * Duration + * Format: duration + * @description The intended duration of the new phase. + * Duration is required when the phase will not be the last phase. + * @example P1M + */ + duration?: string + /** + * Discounts + * @description The discounts on the plan. + */ + discounts?: components['schemas']['Discounts'] + /** @description A locally unique identifier for the phase. */ + key: string + /** @description The name of the phase. */ + name: string + /** @description The description of the phase. */ + description?: string + } + /** @description Expanded subscription phase */ + SubscriptionPhaseExpanded: { + /** + * ID + * @description A unique identifier for the resource. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** + * Display name + * @description Human-readable name for the resource. Between 1 and 256 characters. + */ + name: string + /** + * Description + * @description Optional description of the resource. Maximum 1024 characters. + */ + description?: string + /** + * Metadata + * @description Additional metadata for the resource. + */ + metadata?: components['schemas']['Metadata'] | null + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** @description A locally unique identifier for the resource. */ + key: string + /** + * Discounts + * @description The discounts on the plan. + */ + discounts?: components['schemas']['Discounts'] + /** + * Format: date-time + * @description The time from which the phase is active. + * @example 2023-01-01T01:01:01.001Z + */ + activeFrom: Date + /** + * Format: date-time + * @description The until which the Phase is active. + * @example 2023-01-01T01:01:01.001Z + */ + activeTo?: Date + /** + * @description The items of the phase. The structure is flattened to better conform to the Plan API. + * The timelines are flattened according to the following rules: + * - for the current phase, the `items` contains only the active item for each key + * - for past phases, the `items` contains only the last item for each key + * - for future phases, the `items` contains only the first version of the item for each key + */ + items: components['schemas']['SubscriptionItem'][] + /** @description Includes all versions of the items on each key, including all edits, scheduled changes, etc... */ + itemTimelines: { + [key: string]: components['schemas']['SubscriptionItem'][] + } + } + /** + * @description Subscription status. + * @enum {string} + */ + SubscriptionStatus: 'active' | 'inactive' | 'canceled' | 'scheduled' + /** + * @description Subscription edit timing defined when the changes should take effect. + * If the provided configuration is not supported by the subscription, an error will be returned. + */ + SubscriptionTiming: components['schemas']['SubscriptionTimingEnum'] | Date + /** + * @description Subscription edit timing. + * When immediate, the requested changes take effect immediately. + * When nextBillingCycle, the requested changes take effect at the next billing cycle. + * @enum {string} + */ + SubscriptionTimingEnum: 'immediate' | 'next_billing_cycle' + /** + * @description Tax behavior. + * + * This enum is used to specify whether tax is included in the price or excluded from the price. + * @enum {string} + */ + TaxBehavior: 'inclusive' | 'exclusive' + /** @description Set of provider specific tax configs. */ + TaxConfig: { + /** + * Tax behavior + * @description Tax behavior. + * + * If not specified the billing profile is used to determine the tax behavior. + * If not specified in the billing profile, the provider's default behavior is used. + */ + behavior?: components['schemas']['TaxBehavior'] + /** + * Stripe tax config + * @deprecated + * @description Stripe tax config. + */ + stripe?: components['schemas']['StripeTaxConfig'] + /** + * Custom invoicing tax config + * @deprecated + * @description Custom invoicing tax config. + */ + customInvoicing?: components['schemas']['CustomInvoicingTaxConfig'] + /** + * Tax code ID + * @description Tax code reference. + * + * When both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence: + * the referenced tax code entity is used and `stripe.code` is ignored. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + taxCodeId?: string + } + /** + * @description The mode of the tiered price. + * @enum {string} + */ + TieredPriceMode: 'volume' | 'graduated' + /** @description Tiered price with spend commitments. */ + TieredPriceWithCommitments: { + /** + * @description The type of the price. + * + * One of: flat, unit, or tiered. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'tiered' + /** + * Mode + * @description Defines if the tiering mode is volume-based or graduated: + * - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + * - In `graduated` tiering, pricing can change as the quantity grows. + */ + mode: components['schemas']['TieredPriceMode'] + /** + * Tiers + * @description The tiers of the tiered price. + * At least one price component is required in each tier. + */ + tiers: components['schemas']['PriceTier'][] + /** + * Minimum amount + * @description The customer is committed to spend at least the amount. + */ + minimumAmount?: components['schemas']['Numeric'] + /** + * Maximum amount + * @description The customer is limited to spend at most the amount. + */ + maximumAmount?: components['schemas']['Numeric'] + } + /** @description ULID (Universally Unique Lexicographically Sortable Identifier) or external unique key. */ + ULIDOrExternalKey: string + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + UnauthorizedProblemResponse: components['schemas']['UnexpectedProblemResponse'] + /** + * @description A Problem Details object (RFC 7807). + * Additional properties specific to the problem type may be present. + */ + UnexpectedProblemResponse: { + /** + * Format: uri + * @description Type contains a URI that identifies the problem type. + * @default about:blank + * @example about:blank + */ + type: string + /** + * @description A a short, human-readable summary of the problem type. + * @example Bad Request + */ + title: string + /** + * Format: int16 + * @description The HTTP status code generated by the origin server for this occurrence of the problem. + * @example 400 + */ + status?: number + /** + * @description A human-readable explanation specific to this occurrence of the problem. + * @example The request body must be a JSON object. + */ + detail: string + /** + * Format: uri + * @description A URI reference that identifies the specific occurrence of the problem. + * @example urn:request:local/JMOlctsKV8-000001 + */ + instance: string + /** + * @description Additional properties specific to the problem type may be present. + * @example { + * "validationErrors": [ + * { + * "code": "validation_error", + * "message": "Validation error" + * } + * ], + * "otherAttribute": "otherValue" + * } + */ + extensions?: { + [key: string]: unknown + } + } & { + [key: string]: unknown + } + /** @description Unit price. */ + UnitPrice: { + /** + * @description The type of the price. + * @enum {string} + */ + type: 'unit' + /** @description The amount of the unit price. */ + amount: components['schemas']['Numeric'] + } + /** @description Unit price with spend commitments. */ + UnitPriceWithCommitments: { + /** + * @description The type of the price. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'unit' + /** @description The amount of the unit price. */ + amount: components['schemas']['Numeric'] + /** + * Minimum amount + * @description The customer is committed to spend at least the amount. + */ + minimumAmount?: components['schemas']['Numeric'] + /** + * Maximum amount + * @description The customer is limited to spend at most the amount. + */ + maximumAmount?: components['schemas']['Numeric'] + } + /** @description Validation errors providing detailed description of the issue. */ + ValidationError: { + /** + * @description The path to the field. + * @example addons/pro/ratecards/token/featureKey + */ + readonly field: string + /** + * @description The machine readable description of the error. + * @example invalid_feature_key + */ + readonly code: string + /** + * @description The human readable description of the error. + * @example not found feature by key + */ + readonly message: string + /** @description Additional attributes. */ + readonly attributes?: components['schemas']['Annotations'] + } + /** + * @description ValidationIssue captures any validation issues related to the invoice. + * + * Issues with severity "critical" will prevent the invoice from being issued. + */ + ValidationIssue: { + /** + * Creation Time + * Format: date-time + * @description Timestamp of when the resource was created. + * @example 2024-01-01T01:01:01.001Z + */ + readonly createdAt: Date + /** + * Last Update Time + * Format: date-time + * @description Timestamp of when the resource was last updated. + * @example 2024-01-01T01:01:01.001Z + */ + readonly updatedAt: Date + /** + * Deletion Time + * Format: date-time + * @description Timestamp of when the resource was permanently deleted. + * @example 2024-01-01T01:01:01.001Z + */ + readonly deletedAt?: Date + /** + * @description ID of the charge or discount. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + readonly id: string + /** @description The severity of the issue. */ + readonly severity: components['schemas']['ValidationIssueSeverity'] + /** @description The field that the issue is related to, if available in JSON path format. */ + readonly field?: string + /** @description Machine indentifiable code for the issue, if available. */ + readonly code?: string + /** @description Component reporting the issue. */ + readonly component: string + /** @description A human-readable description of the issue. */ + readonly message: string + /** @description Additional context for the issue. */ + readonly metadata?: components['schemas']['Metadata'] + } + /** + * @description ValidationIssueSeverity describes the severity of a validation issue. + * + * Issues with severity "critical" will prevent the invoice from being issued. + * @enum {string} + */ + ValidationIssueSeverity: 'critical' | 'warning' + /** @description InvoiceVoidAction describes how to handle the voided line items. */ + VoidInvoiceActionCreate: { + /** @description How much of the total line items to be voided? (e.g. 100% means all charges are voided) */ + percentage: components['schemas']['Percentage'] + /** @description The action to take on the line items. */ + action: components['schemas']['VoidInvoiceLineActionCreate'] + } + /** @description InvoiceVoidAction describes how to handle the voided line items. */ + VoidInvoiceActionCreateItem: { + /** @description How much of the total line items to be voided? (e.g. 100% means all charges are voided) */ + percentage: components['schemas']['Percentage'] + /** @description The action to take on the line items. */ + action: components['schemas']['VoidInvoiceLineActionCreateItem'] + } + /** @description Request to void an invoice */ + VoidInvoiceActionInput: { + /** @description The action to take on the voided line items. */ + action: components['schemas']['VoidInvoiceActionCreate'] + /** @description The reason for voiding the invoice. */ + reason: string + /** + * @description Per line item overrides for the action. + * + * If not specified, the `action` will be applied to all line items. + */ + overrides?: + | components['schemas']['VoidInvoiceActionLineOverride'][] + | null + } + /** @description VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding. */ + VoidInvoiceActionLineOverride: { + /** + * @description The line item ID to override. + * @example 01G65Z755AFWAKHE12NY0CQ9FH + */ + lineId: string + /** @description The action to take on the line item. */ + action: components['schemas']['VoidInvoiceActionCreateItem'] + } + /** @description VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. */ + VoidInvoiceLineActionCreate: + | components['schemas']['VoidInvoiceLineDiscardAction'] + | components['schemas']['VoidInvoiceLinePendingActionCreate'] + /** @description VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. */ + VoidInvoiceLineActionCreateItem: + | components['schemas']['VoidInvoiceLineDiscardAction'] + | components['schemas']['VoidInvoiceLinePendingActionCreateItem'] + /** @description VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. */ + VoidInvoiceLineDiscardAction: { + /** + * @description The action to take on the line item. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'discard' + } + /** @description VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. */ + VoidInvoiceLinePendingActionCreate: { + /** + * @description The action to take on the line item. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'pending' + /** + * Format: date-time + * @description The time at which the line item should be invoiced again. + * + * If not provided, the line item will be re-invoiced now. + * @example 2023-01-01T01:01:01.001Z + */ + nextInvoiceAt?: Date + } + /** @description VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. */ + VoidInvoiceLinePendingActionCreateItem: { + /** + * @description The action to take on the line item. (enum property replaced by openapi-typescript) + * @enum {string} + */ + type: 'pending' + /** + * Format: date-time + * @description The time at which the line item should be invoiced again. + * + * If not provided, the line item will be re-invoiced now. + * @example 2023-01-01T01:01:01.001Z + */ + nextInvoiceAt?: Date + } + /** + * @description Aggregation window size. + * @enum {string} + */ + WindowSize: 'MINUTE' | 'HOUR' | 'DAY' | 'MONTH' + /** @description The windowed balance history. */ + WindowedBalanceHistory: { + /** + * @description The windowed balance history. + * - It only returns rows for windows where there was usage. + * - The windows are inclusive at their start and exclusive at their end. + * - The last window may be smaller than the window size and is inclusive at both ends. + */ + windowedHistory: components['schemas']['BalanceHistoryWindow'][] + /** @description Grant burndown history. */ + burndownHistory: components['schemas']['GrantBurnDownHistorySegment'][] + } + } + responses: never + parameters: { + /** @description The order direction. */ + 'AddonOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'AddonOrderByOrdering.orderBy': components['schemas']['AddonOrderBy'] + /** @description The order direction. */ + 'BillingProfileCustomerOverrideOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'BillingProfileCustomerOverrideOrderByOrdering.orderBy': components['schemas']['BillingProfileCustomerOverrideOrderBy'] + /** @description Filter by billing profile. */ + 'BillingProfileListCustomerOverridesParams.billingProfile': string[] + /** @description Filter by customer id. */ + 'BillingProfileListCustomerOverridesParams.customerId': string[] + /** @description Filter by customer key */ + 'BillingProfileListCustomerOverridesParams.customerKey': string + /** @description Filter by customer name. */ + 'BillingProfileListCustomerOverridesParams.customerName': string + /** @description Filter by customer primary email */ + 'BillingProfileListCustomerOverridesParams.customerPrimaryEmail': string + /** @description Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. */ + 'BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile': boolean + /** @description Expand the response with additional details. */ + 'BillingProfileListCustomerOverridesParams.expand': components['schemas']['BillingProfileCustomerOverrideExpand'][] + /** + * @description Include customers without customer overrides. + * + * If set to false only the customers specifically associated with a billing profile will be returned. + * + * If set to true, in case of the default billing profile, all customers will be returned. + */ + 'BillingProfileListCustomerOverridesParams.includeAllCustomers': boolean + /** @description The order direction. */ + 'BillingProfileOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'BillingProfileOrderByOrdering.orderBy': components['schemas']['BillingProfileOrderBy'] + /** @description The cursor after which to start the pagination. */ + 'CursorPagination.cursor': string + /** @description The limit of the pagination. */ + 'CursorPagination.limit': number + /** @description The order direction. */ + 'CustomerOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'CustomerOrderByOrdering.orderBy': components['schemas']['CustomerOrderBy'] + /** @description The order direction. */ + 'CustomerSubscriptionOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'CustomerSubscriptionOrderByOrdering.orderBy': components['schemas']['CustomerSubscriptionOrderBy'] + /** @description The order direction. */ + 'EntitlementOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'EntitlementOrderByOrdering.orderBy': components['schemas']['EntitlementOrderBy'] + /** @description The order direction. */ + 'FeatureOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'FeatureOrderByOrdering.orderBy': components['schemas']['FeatureOrderBy'] + /** @description The order direction. */ + 'GrantOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'GrantOrderByOrdering.orderBy': components['schemas']['GrantOrderBy'] + /** + * @description Filter by invoice created time. + * Inclusive. + */ + 'InvoiceListParams.createdAfter': Date | string + /** + * @description Filter by invoice created time. + * Inclusive. + */ + 'InvoiceListParams.createdBefore': Date | string + /** @description Filter by customer ID */ + 'InvoiceListParams.customers': string[] + /** @description What parts of the list output to expand in listings */ + 'InvoiceListParams.expand': components['schemas']['InvoiceExpand'][] + /** @description Filter by invoice extended statuses */ + 'InvoiceListParams.extendedStatuses': string[] + /** @description Include deleted invoices */ + 'InvoiceListParams.includeDeleted': boolean + /** + * @description Filter by invoice issued time. + * Inclusive. + */ + 'InvoiceListParams.issuedAfter': Date | string + /** + * @description Filter by invoice issued time. + * Inclusive. + */ + 'InvoiceListParams.issuedBefore': Date | string + /** + * @description Filter by period start time. + * Inclusive. + */ + 'InvoiceListParams.periodStartAfter': Date | string + /** + * @description Filter by period start time. + * Inclusive. + */ + 'InvoiceListParams.periodStartBefore': Date | string + /** @description Filter by the invoice status. */ + 'InvoiceListParams.statuses': components['schemas']['InvoiceStatus'][] + /** @description The order direction. */ + 'InvoiceOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'InvoiceOrderByOrdering.orderBy': components['schemas']['InvoiceOrderBy'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + 'LimitOffset.limit': number + /** + * @description Number of items to skip. + * + * Default is 0. + */ + 'LimitOffset.offset': number + /** @description The type of the app to install. */ + 'MarketplaceApiKeyInstallRequest.type': components['schemas']['AppType'] + /** @description The type of the app to install. */ + 'MarketplaceInstallRequest.type': components['schemas']['AppType'] + /** @description The type of the app to install. */ + 'MarketplaceOAuth2InstallAuthorizeRequest.type': components['schemas']['AppType'] + /** @description The order direction. */ + 'MeterOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'MeterOrderByOrdering.orderBy': components['schemas']['MeterOrderBy'] + /** + * @description Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + */ + 'MeterQuery.advancedMeterGroupByFilters': string + /** + * @description Client ID + * Useful to track progress of a query. + */ + 'MeterQuery.clientId': string + /** + * @description Filtering by multiple customers. + * + * For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + */ + 'MeterQuery.filterCustomerId': string[] + /** + * @deprecated + * @description Simple filter for group bys with exact match. + * + * For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + * + * ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + */ + 'MeterQuery.filterGroupBy': { + [key: string]: string + } + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + 'MeterQuery.from': Date | string + /** + * @description If not specified a single aggregate will be returned for each subject and time window. + * `subject` is a reserved group by value. + * + * For example: ?groupBy=subject&groupBy=model + */ + 'MeterQuery.groupBy': string[] + /** + * @description Filtering by multiple subjects. + * + * For example: ?subject=subject-1&subject=subject-2 + */ + 'MeterQuery.subject': string[] + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + 'MeterQuery.to': Date | string + /** + * @description If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + * + * For example: ?windowSize=DAY + */ + 'MeterQuery.windowSize': components['schemas']['WindowSize'] + /** + * @description The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + * If not specified, the UTC timezone will be used. + * + * For example: ?windowTimeZone=UTC + */ + 'MeterQuery.windowTimeZone': string + /** @description The order direction. */ + 'NotificationChannelOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'NotificationChannelOrderByOrdering.orderBy': components['schemas']['NotificationChannelOrderBy'] + /** @description The order direction. */ + 'NotificationEventOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'NotificationEventOrderByOrdering.orderBy': components['schemas']['NotificationEventOrderBy'] + /** @description The order direction. */ + 'NotificationRuleOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'NotificationRuleOrderByOrdering.orderBy': components['schemas']['NotificationRuleOrderBy'] + /** + * @description Error code. + * Required with the error response. + */ + 'OAuth2AuthorizationCodeGrantErrorParams.error': components['schemas']['OAuth2AuthorizationCodeGrantErrorType'] + /** + * @description Optional human-readable text providing additional information, + * used to assist the client developer in understanding the error that occurred. + */ + 'OAuth2AuthorizationCodeGrantErrorParams.error_description': string + /** + * @description Optional uri identifying a human-readable web page with + * information about the error, used to provide the client + * developer with additional information about the error + */ + 'OAuth2AuthorizationCodeGrantErrorParams.error_uri': string + /** + * @description Authorization code which the client will later exchange for an access token. + * Required with the success response. + */ + 'OAuth2AuthorizationCodeGrantSuccessParams.code': string + /** + * @description Required if the "state" parameter was present in the client authorization request. + * The exact value received from the client: + * + * Unique, randomly generated, opaque, and non-guessable string that is sent + * when starting an authentication request and validated when processing the response. + */ + 'OAuth2AuthorizationCodeGrantSuccessParams.state': string + /** + * @description Page index. + * + * Default is 1. + */ + 'Pagination.page': number + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + 'Pagination.pageSize': number + /** @description The order direction. */ + 'PlanAddonOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'PlanAddonOrderByOrdering.orderBy': components['schemas']['PlanAddonOrderBy'] + /** @description The order direction. */ + 'PlanOrderByOrdering.order': components['schemas']['SortOrder'] + /** @description The order by field. */ + 'PlanOrderByOrdering.orderBy': components['schemas']['PlanOrderBy'] + /** @description Filter customer data by app type. */ + 'listCustomerAppDataParams.type': components['schemas']['AppType'] + /** @description What parts of the customer output to expand */ + queryCustomerGet: components['schemas']['CustomerExpand'][] + /** @description What parts of the list output to expand in listings */ + 'queryCustomerList.expand': components['schemas']['CustomerExpand'][] + /** @description Include deleted customers. */ + 'queryCustomerList.includeDeleted': boolean + /** + * @description Filter customers by key. + * Case-insensitive partial match. + */ + 'queryCustomerList.key': string + /** + * @description Filter customers by name. + * Case-insensitive partial match. + */ + 'queryCustomerList.name': string + /** @description Filter customers by the plan key of their susbcription. */ + 'queryCustomerList.planKey': string + /** + * @description Filter customers by primary email. + * Case-insensitive partial match. + */ + 'queryCustomerList.primaryEmail': string + /** + * @description Filter customers by usage attribution subject. + * Case-insensitive partial match. + */ + 'queryCustomerList.subject': string + /** @description Include deleted meters. */ + 'queryMeterList.includeDeleted': boolean + } + requestBodies: never + headers: never + pathItems: never +} +export type Addon = components['schemas']['Addon'] +export type AddonCreate = components['schemas']['AddonCreate'] +export type AddonInstanceType = components['schemas']['AddonInstanceType'] +export type AddonOrderBy = components['schemas']['AddonOrderBy'] +export type AddonPaginatedResponse = + components['schemas']['AddonPaginatedResponse'] +export type AddonReplaceUpdate = components['schemas']['AddonReplaceUpdate'] +export type AddonStatus = components['schemas']['AddonStatus'] +export type Address = components['schemas']['Address'] +export type Alignment = components['schemas']['Alignment'] +export type Annotations = components['schemas']['Annotations'] +export type App = components['schemas']['App'] +export type AppCapability = components['schemas']['AppCapability'] +export type AppCapabilityType = components['schemas']['AppCapabilityType'] +export type AppPaginatedResponse = components['schemas']['AppPaginatedResponse'] +export type AppReference = components['schemas']['AppReference'] +export type AppReplaceUpdate = components['schemas']['AppReplaceUpdate'] +export type AppStatus = components['schemas']['AppStatus'] +export type AppType = components['schemas']['AppType'] +export type BadRequestProblemResponse = + components['schemas']['BadRequestProblemResponse'] +export type BalanceHistoryWindow = components['schemas']['BalanceHistoryWindow'] +export type BillingCustomerProfile = + components['schemas']['BillingCustomerProfile'] +export type BillingDiscountPercentage = + components['schemas']['BillingDiscountPercentage'] +export type BillingDiscountReason = + components['schemas']['BillingDiscountReason'] +export type BillingDiscountUsage = components['schemas']['BillingDiscountUsage'] +export type BillingDiscounts = components['schemas']['BillingDiscounts'] +export type BillingInvoiceCustomerExtendedDetails = + components['schemas']['BillingInvoiceCustomerExtendedDetails'] +export type BillingParty = components['schemas']['BillingParty'] +export type BillingPartyReplaceUpdate = + components['schemas']['BillingPartyReplaceUpdate'] +export type BillingPartyTaxIdentity = + components['schemas']['BillingPartyTaxIdentity'] +export type BillingProfile = components['schemas']['BillingProfile'] +export type BillingProfileAppReferences = + components['schemas']['BillingProfileAppReferences'] +export type BillingProfileApps = components['schemas']['BillingProfileApps'] +export type BillingProfileAppsCreate = + components['schemas']['BillingProfileAppsCreate'] +export type BillingProfileAppsOrReference = + components['schemas']['BillingProfileAppsOrReference'] +export type BillingProfileCreate = components['schemas']['BillingProfileCreate'] +export type BillingProfileCustomerOverride = + components['schemas']['BillingProfileCustomerOverride'] +export type BillingProfileCustomerOverrideCreate = + components['schemas']['BillingProfileCustomerOverrideCreate'] +export type BillingProfileCustomerOverrideExpand = + components['schemas']['BillingProfileCustomerOverrideExpand'] +export type BillingProfileCustomerOverrideOrderBy = + components['schemas']['BillingProfileCustomerOverrideOrderBy'] +export type BillingProfileCustomerOverrideWithDetails = + components['schemas']['BillingProfileCustomerOverrideWithDetails'] +export type BillingProfileCustomerOverrideWithDetailsPaginatedResponse = + components['schemas']['BillingProfileCustomerOverrideWithDetailsPaginatedResponse'] +export type BillingProfileExpand = components['schemas']['BillingProfileExpand'] +export type BillingProfileOrderBy = + components['schemas']['BillingProfileOrderBy'] +export type BillingProfilePaginatedResponse = + components['schemas']['BillingProfilePaginatedResponse'] +export type BillingProfileReplaceUpdateWithWorkflow = + components['schemas']['BillingProfileReplaceUpdateWithWorkflow'] +export type BillingSettlementMode = + components['schemas']['BillingSettlementMode'] +export type BillingTaxIdentificationCode = + components['schemas']['BillingTaxIdentificationCode'] +export type BillingWorkflow = components['schemas']['BillingWorkflow'] +export type BillingWorkflowCollectionAlignment = + components['schemas']['BillingWorkflowCollectionAlignment'] +export type BillingWorkflowCollectionAlignmentAnchored = + components['schemas']['BillingWorkflowCollectionAlignmentAnchored'] +export type BillingWorkflowCollectionAlignmentSubscription = + components['schemas']['BillingWorkflowCollectionAlignmentSubscription'] +export type BillingWorkflowCollectionSettings = + components['schemas']['BillingWorkflowCollectionSettings'] +export type BillingWorkflowCreate = + components['schemas']['BillingWorkflowCreate'] +export type BillingWorkflowInvoicingSettings = + components['schemas']['BillingWorkflowInvoicingSettings'] +export type BillingWorkflowInvoicingSubscriptionEndProrationMode = + components['schemas']['BillingWorkflowInvoicingSubscriptionEndProrationMode'] +export type BillingWorkflowPaymentSettings = + components['schemas']['BillingWorkflowPaymentSettings'] +export type BillingWorkflowTaxSettings = + components['schemas']['BillingWorkflowTaxSettings'] +export type CheckoutSessionCustomTextAfterSubmitParams = + components['schemas']['CheckoutSessionCustomTextAfterSubmitParams'] +export type CheckoutSessionUiMode = + components['schemas']['CheckoutSessionUIMode'] +export type ClientAppStartResponse = + components['schemas']['ClientAppStartResponse'] +export type CollectionMethod = components['schemas']['CollectionMethod'] +export type ConflictProblemResponse = + components['schemas']['ConflictProblemResponse'] +export type CountryCode = components['schemas']['CountryCode'] +export type CreateCheckoutSessionTaxIdCollection = + components['schemas']['CreateCheckoutSessionTaxIdCollection'] +export type CreateCheckoutSessionTaxIdCollectionRequired = + components['schemas']['CreateCheckoutSessionTaxIdCollectionRequired'] +export type CreateStripeCheckoutSessionBillingAddressCollection = + components['schemas']['CreateStripeCheckoutSessionBillingAddressCollection'] +export type CreateStripeCheckoutSessionConsentCollection = + components['schemas']['CreateStripeCheckoutSessionConsentCollection'] +export type CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement = + components['schemas']['CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement'] +export type CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = + components['schemas']['CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition'] +export type CreateStripeCheckoutSessionConsentCollectionPromotions = + components['schemas']['CreateStripeCheckoutSessionConsentCollectionPromotions'] +export type CreateStripeCheckoutSessionConsentCollectionTermsOfService = + components['schemas']['CreateStripeCheckoutSessionConsentCollectionTermsOfService'] +export type CreateStripeCheckoutSessionCustomerUpdate = + components['schemas']['CreateStripeCheckoutSessionCustomerUpdate'] +export type CreateStripeCheckoutSessionCustomerUpdateBehavior = + components['schemas']['CreateStripeCheckoutSessionCustomerUpdateBehavior'] +export type CreateStripeCheckoutSessionRedirectOnCompletion = + components['schemas']['CreateStripeCheckoutSessionRedirectOnCompletion'] +export type CreateStripeCheckoutSessionRequest = + components['schemas']['CreateStripeCheckoutSessionRequest'] +export type CreateStripeCheckoutSessionRequestOptions = + components['schemas']['CreateStripeCheckoutSessionRequestOptions'] +export type CreateStripeCheckoutSessionResult = + components['schemas']['CreateStripeCheckoutSessionResult'] +export type CreateStripeCustomerPortalSessionParams = + components['schemas']['CreateStripeCustomerPortalSessionParams'] +export type CreditNoteOriginalInvoiceRef = + components['schemas']['CreditNoteOriginalInvoiceRef'] +export type Currency = components['schemas']['Currency'] +export type CurrencyCode = components['schemas']['CurrencyCode'] +export type CustomInvoicingApp = components['schemas']['CustomInvoicingApp'] +export type CustomInvoicingAppReplaceUpdate = + components['schemas']['CustomInvoicingAppReplaceUpdate'] +export type CustomInvoicingCustomerAppData = + components['schemas']['CustomInvoicingCustomerAppData'] +export type CustomInvoicingDraftSynchronizedRequest = + components['schemas']['CustomInvoicingDraftSynchronizedRequest'] +export type CustomInvoicingFinalizedInvoicingRequest = + components['schemas']['CustomInvoicingFinalizedInvoicingRequest'] +export type CustomInvoicingFinalizedPaymentRequest = + components['schemas']['CustomInvoicingFinalizedPaymentRequest'] +export type CustomInvoicingFinalizedRequest = + components['schemas']['CustomInvoicingFinalizedRequest'] +export type CustomInvoicingLineDiscountExternalIdMapping = + components['schemas']['CustomInvoicingLineDiscountExternalIdMapping'] +export type CustomInvoicingLineExternalIdMapping = + components['schemas']['CustomInvoicingLineExternalIdMapping'] +export type CustomInvoicingPaymentTrigger = + components['schemas']['CustomInvoicingPaymentTrigger'] +export type CustomInvoicingSyncResult = + components['schemas']['CustomInvoicingSyncResult'] +export type CustomInvoicingTaxConfig = + components['schemas']['CustomInvoicingTaxConfig'] +export type CustomInvoicingUpdatePaymentStatusRequest = + components['schemas']['CustomInvoicingUpdatePaymentStatusRequest'] +export type CustomPlanInput = components['schemas']['CustomPlanInput'] +export type CustomSubscriptionChange = + components['schemas']['CustomSubscriptionChange'] +export type CustomSubscriptionCreate = + components['schemas']['CustomSubscriptionCreate'] +export type Customer = components['schemas']['Customer'] +export type CustomerAccess = components['schemas']['CustomerAccess'] +export type CustomerAppData = components['schemas']['CustomerAppData'] +export type CustomerAppDataCreateOrUpdateItem = + components['schemas']['CustomerAppDataCreateOrUpdateItem'] +export type CustomerAppDataPaginatedResponse = + components['schemas']['CustomerAppDataPaginatedResponse'] +export type CustomerCreate = components['schemas']['CustomerCreate'] +export type CustomerExpand = components['schemas']['CustomerExpand'] +export type CustomerId = components['schemas']['CustomerId'] +export type CustomerKey = components['schemas']['CustomerKey'] +export type CustomerOrderBy = components['schemas']['CustomerOrderBy'] +export type CustomerPaginatedResponse = + components['schemas']['CustomerPaginatedResponse'] +export type CustomerReplaceUpdate = + components['schemas']['CustomerReplaceUpdate'] +export type CustomerSubscriptionOrderBy = + components['schemas']['CustomerSubscriptionOrderBy'] +export type CustomerUsageAttribution = + components['schemas']['CustomerUsageAttribution'] +export type DiscountPercentage = components['schemas']['DiscountPercentage'] +export type DiscountReasonMaximumSpend = + components['schemas']['DiscountReasonMaximumSpend'] +export type DiscountReasonRatecardPercentage = + components['schemas']['DiscountReasonRatecardPercentage'] +export type DiscountReasonRatecardUsage = + components['schemas']['DiscountReasonRatecardUsage'] +export type DiscountUsage = components['schemas']['DiscountUsage'] +export type Discounts = components['schemas']['Discounts'] +export type DynamicPriceWithCommitments = + components['schemas']['DynamicPriceWithCommitments'] +export type EditSubscriptionAddItem = + components['schemas']['EditSubscriptionAddItem'] +export type EditSubscriptionAddPhase = + components['schemas']['EditSubscriptionAddPhase'] +export type EditSubscriptionRemoveItem = + components['schemas']['EditSubscriptionRemoveItem'] +export type EditSubscriptionRemovePhase = + components['schemas']['EditSubscriptionRemovePhase'] +export type EditSubscriptionStretchPhase = + components['schemas']['EditSubscriptionStretchPhase'] +export type EditSubscriptionUnscheduleEdit = + components['schemas']['EditSubscriptionUnscheduleEdit'] +export type Entitlement = components['schemas']['Entitlement'] +export type EntitlementBoolean = components['schemas']['EntitlementBoolean'] +export type EntitlementBooleanCreateInputs = + components['schemas']['EntitlementBooleanCreateInputs'] +export type EntitlementBooleanV2 = components['schemas']['EntitlementBooleanV2'] +export type EntitlementCreateInputs = + components['schemas']['EntitlementCreateInputs'] +export type EntitlementGrant = components['schemas']['EntitlementGrant'] +export type EntitlementGrantCreateInput = + components['schemas']['EntitlementGrantCreateInput'] +export type EntitlementGrantCreateInputV2 = + components['schemas']['EntitlementGrantCreateInputV2'] +export type EntitlementGrantV2 = components['schemas']['EntitlementGrantV2'] +export type EntitlementMetered = components['schemas']['EntitlementMetered'] +export type EntitlementMeteredCreateInputs = + components['schemas']['EntitlementMeteredCreateInputs'] +export type EntitlementMeteredV2 = components['schemas']['EntitlementMeteredV2'] +export type EntitlementMeteredV2CreateInputs = + components['schemas']['EntitlementMeteredV2CreateInputs'] +export type EntitlementOrderBy = components['schemas']['EntitlementOrderBy'] +export type EntitlementPaginatedResponse = + components['schemas']['EntitlementPaginatedResponse'] +export type EntitlementStatic = components['schemas']['EntitlementStatic'] +export type EntitlementStaticCreateInputs = + components['schemas']['EntitlementStaticCreateInputs'] +export type EntitlementStaticV2 = components['schemas']['EntitlementStaticV2'] +export type EntitlementType = components['schemas']['EntitlementType'] +export type EntitlementV2 = components['schemas']['EntitlementV2'] +export type EntitlementV2CreateInputs = + components['schemas']['EntitlementV2CreateInputs'] +export type EntitlementV2PaginatedResponse = + components['schemas']['EntitlementV2PaginatedResponse'] +export type EntitlementValue = components['schemas']['EntitlementValue'] +export type EntitlementValueV2 = components['schemas']['EntitlementValueV2'] +export type ErrorExtension = components['schemas']['ErrorExtension'] +export type Event = components['schemas']['Event'] +export type EventDeliveryAttemptResponse = + components['schemas']['EventDeliveryAttemptResponse'] +export type ExpirationDuration = components['schemas']['ExpirationDuration'] +export type ExpirationPeriod = components['schemas']['ExpirationPeriod'] +export type Feature = components['schemas']['Feature'] +export type FeatureCreateInputs = components['schemas']['FeatureCreateInputs'] +export type FeatureLlmUnitCost = components['schemas']['FeatureLLMUnitCost'] +export type FeatureLlmUnitCostPricing = + components['schemas']['FeatureLLMUnitCostPricing'] +export type FeatureManualUnitCost = + components['schemas']['FeatureManualUnitCost'] +export type FeatureMeta = components['schemas']['FeatureMeta'] +export type FeatureOrderBy = components['schemas']['FeatureOrderBy'] +export type FeaturePaginatedResponse = + components['schemas']['FeaturePaginatedResponse'] +export type FeatureUnitCost = components['schemas']['FeatureUnitCost'] +export type FilterIdExact = components['schemas']['FilterIDExact'] +export type FilterString = components['schemas']['FilterString'] +export type FilterTime = components['schemas']['FilterTime'] +export type FlatPrice = components['schemas']['FlatPrice'] +export type FlatPriceWithPaymentTerm = + components['schemas']['FlatPriceWithPaymentTerm'] +export type ForbiddenProblemResponse = + components['schemas']['ForbiddenProblemResponse'] +export type GatewayTimeoutProblemResponse = + components['schemas']['GatewayTimeoutProblemResponse'] +export type GrantBurnDownHistorySegment = + components['schemas']['GrantBurnDownHistorySegment'] +export type GrantOrderBy = components['schemas']['GrantOrderBy'] +export type GrantPaginatedResponse = + components['schemas']['GrantPaginatedResponse'] +export type GrantUsageRecord = components['schemas']['GrantUsageRecord'] +export type GrantV2PaginatedResponse = + components['schemas']['GrantV2PaginatedResponse'] +export type IdResource = components['schemas']['IDResource'] +export type IngestEventsBody = components['schemas']['IngestEventsBody'] +export type IngestedEvent = components['schemas']['IngestedEvent'] +export type IngestedEventCursorPaginatedResponse = + components['schemas']['IngestedEventCursorPaginatedResponse'] +export type InstallMethod = components['schemas']['InstallMethod'] +export type InternalServerErrorProblemResponse = + components['schemas']['InternalServerErrorProblemResponse'] +export type Invoice = components['schemas']['Invoice'] +export type InvoiceAppExternalIds = + components['schemas']['InvoiceAppExternalIds'] +export type InvoiceAvailableActionDetails = + components['schemas']['InvoiceAvailableActionDetails'] +export type InvoiceAvailableActionInvoiceDetails = + components['schemas']['InvoiceAvailableActionInvoiceDetails'] +export type InvoiceAvailableActions = + components['schemas']['InvoiceAvailableActions'] +export type InvoiceDetailedLine = components['schemas']['InvoiceDetailedLine'] +export type InvoiceDetailedLineCostCategory = + components['schemas']['InvoiceDetailedLineCostCategory'] +export type InvoiceDetailedLineRateCard = + components['schemas']['InvoiceDetailedLineRateCard'] +export type InvoiceDocumentRef = components['schemas']['InvoiceDocumentRef'] +export type InvoiceDocumentRefType = + components['schemas']['InvoiceDocumentRefType'] +export type InvoiceExpand = components['schemas']['InvoiceExpand'] +export type InvoiceGenericDocumentRef = + components['schemas']['InvoiceGenericDocumentRef'] +export type InvoiceLine = components['schemas']['InvoiceLine'] +export type InvoiceLineAmountDiscount = + components['schemas']['InvoiceLineAmountDiscount'] +export type InvoiceLineAppExternalIds = + components['schemas']['InvoiceLineAppExternalIds'] +export type InvoiceLineCreditAllocation = + components['schemas']['InvoiceLineCreditAllocation'] +export type InvoiceLineDiscounts = components['schemas']['InvoiceLineDiscounts'] +export type InvoiceLineManagedBy = components['schemas']['InvoiceLineManagedBy'] +export type InvoiceLineReplaceUpdate = + components['schemas']['InvoiceLineReplaceUpdate'] +export type InvoiceLineStatus = components['schemas']['InvoiceLineStatus'] +export type InvoiceLineSubscriptionReference = + components['schemas']['InvoiceLineSubscriptionReference'] +export type InvoiceLineTaxBehavior = + components['schemas']['InvoiceLineTaxBehavior'] +export type InvoiceLineTaxItem = components['schemas']['InvoiceLineTaxItem'] +export type InvoiceLineUsageDiscount = + components['schemas']['InvoiceLineUsageDiscount'] +export type InvoiceNumber = components['schemas']['InvoiceNumber'] +export type InvoiceOrderBy = components['schemas']['InvoiceOrderBy'] +export type InvoicePaginatedResponse = + components['schemas']['InvoicePaginatedResponse'] +export type InvoicePaymentTerms = components['schemas']['InvoicePaymentTerms'] +export type InvoicePendingLineCreate = + components['schemas']['InvoicePendingLineCreate'] +export type InvoicePendingLineCreateInput = + components['schemas']['InvoicePendingLineCreateInput'] +export type InvoicePendingLineCreateResponse = + components['schemas']['InvoicePendingLineCreateResponse'] +export type InvoicePendingLinesActionFiltersInput = + components['schemas']['InvoicePendingLinesActionFiltersInput'] +export type InvoicePendingLinesActionInput = + components['schemas']['InvoicePendingLinesActionInput'] +export type InvoiceReference = components['schemas']['InvoiceReference'] +export type InvoiceReplaceUpdate = components['schemas']['InvoiceReplaceUpdate'] +export type InvoiceSimulationInput = + components['schemas']['InvoiceSimulationInput'] +export type InvoiceSimulationLine = + components['schemas']['InvoiceSimulationLine'] +export type InvoiceStatus = components['schemas']['InvoiceStatus'] +export type InvoiceStatusDetails = components['schemas']['InvoiceStatusDetails'] +export type InvoiceTotals = components['schemas']['InvoiceTotals'] +export type InvoiceType = components['schemas']['InvoiceType'] +export type InvoiceUsageBasedRateCard = + components['schemas']['InvoiceUsageBasedRateCard'] +export type InvoiceWorkflowInvoicingSettingsReplaceUpdate = + components['schemas']['InvoiceWorkflowInvoicingSettingsReplaceUpdate'] +export type InvoiceWorkflowReplaceUpdate = + components['schemas']['InvoiceWorkflowReplaceUpdate'] +export type InvoiceWorkflowSettings = + components['schemas']['InvoiceWorkflowSettings'] +export type InvoiceWorkflowSettingsReplaceUpdate = + components['schemas']['InvoiceWorkflowSettingsReplaceUpdate'] +export type IssueAfterReset = components['schemas']['IssueAfterReset'] +export type ListEntitlementsResult = + components['schemas']['ListEntitlementsResult'] +export type ListFeaturesResult = components['schemas']['ListFeaturesResult'] +export type MarketplaceInstallRequestPayload = + components['schemas']['MarketplaceInstallRequestPayload'] +export type MarketplaceInstallResponse = + components['schemas']['MarketplaceInstallResponse'] +export type MarketplaceListing = components['schemas']['MarketplaceListing'] +export type MarketplaceListingPaginatedResponse = + components['schemas']['MarketplaceListingPaginatedResponse'] +export type MeasureUsageFrom = components['schemas']['MeasureUsageFrom'] +export type MeasureUsageFromPreset = + components['schemas']['MeasureUsageFromPreset'] +export type MeasureUsageFromTime = components['schemas']['MeasureUsageFromTime'] +export type Metadata = components['schemas']['Metadata'] +export type Meter = components['schemas']['Meter'] +export type MeterAggregation = components['schemas']['MeterAggregation'] +export type MeterCreate = components['schemas']['MeterCreate'] +export type MeterOrderBy = components['schemas']['MeterOrderBy'] +export type MeterQueryRequest = components['schemas']['MeterQueryRequest'] +export type MeterQueryResult = components['schemas']['MeterQueryResult'] +export type MeterQueryRow = components['schemas']['MeterQueryRow'] +export type MeterUpdate = components['schemas']['MeterUpdate'] +export type NotFoundProblemResponse = + components['schemas']['NotFoundProblemResponse'] +export type NotImplementedProblemResponse = + components['schemas']['NotImplementedProblemResponse'] +export type NotificationChannel = components['schemas']['NotificationChannel'] +export type NotificationChannelCreateRequest = + components['schemas']['NotificationChannelCreateRequest'] +export type NotificationChannelMeta = + components['schemas']['NotificationChannelMeta'] +export type NotificationChannelOrderBy = + components['schemas']['NotificationChannelOrderBy'] +export type NotificationChannelPaginatedResponse = + components['schemas']['NotificationChannelPaginatedResponse'] +export type NotificationChannelType = + components['schemas']['NotificationChannelType'] +export type NotificationChannelWebhook = + components['schemas']['NotificationChannelWebhook'] +export type NotificationChannelWebhookCreateRequest = + components['schemas']['NotificationChannelWebhookCreateRequest'] +export type NotificationEvent = components['schemas']['NotificationEvent'] +export type NotificationEventBalanceThresholdPayload = + components['schemas']['NotificationEventBalanceThresholdPayload'] +export type NotificationEventBalanceThresholdPayloadData = + components['schemas']['NotificationEventBalanceThresholdPayloadData'] +export type NotificationEventDeliveryAttempt = + components['schemas']['NotificationEventDeliveryAttempt'] +export type NotificationEventDeliveryStatus = + components['schemas']['NotificationEventDeliveryStatus'] +export type NotificationEventDeliveryStatusState = + components['schemas']['NotificationEventDeliveryStatusState'] +export type NotificationEventEntitlementValuePayloadBase = + components['schemas']['NotificationEventEntitlementValuePayloadBase'] +export type NotificationEventInvoiceCreatedPayload = + components['schemas']['NotificationEventInvoiceCreatedPayload'] +export type NotificationEventInvoiceUpdatedPayload = + components['schemas']['NotificationEventInvoiceUpdatedPayload'] +export type NotificationEventOrderBy = + components['schemas']['NotificationEventOrderBy'] +export type NotificationEventPaginatedResponse = + components['schemas']['NotificationEventPaginatedResponse'] +export type NotificationEventPayload = + components['schemas']['NotificationEventPayload'] +export type NotificationEventResendRequest = + components['schemas']['NotificationEventResendRequest'] +export type NotificationEventResetPayload = + components['schemas']['NotificationEventResetPayload'] +export type NotificationEventType = + components['schemas']['NotificationEventType'] +export type NotificationRule = components['schemas']['NotificationRule'] +export type NotificationRuleBalanceThreshold = + components['schemas']['NotificationRuleBalanceThreshold'] +export type NotificationRuleBalanceThresholdCreateRequest = + components['schemas']['NotificationRuleBalanceThresholdCreateRequest'] +export type NotificationRuleBalanceThresholdValue = + components['schemas']['NotificationRuleBalanceThresholdValue'] +export type NotificationRuleBalanceThresholdValueType = + components['schemas']['NotificationRuleBalanceThresholdValueType'] +export type NotificationRuleCreateRequest = + components['schemas']['NotificationRuleCreateRequest'] +export type NotificationRuleEntitlementReset = + components['schemas']['NotificationRuleEntitlementReset'] +export type NotificationRuleEntitlementResetCreateRequest = + components['schemas']['NotificationRuleEntitlementResetCreateRequest'] +export type NotificationRuleInvoiceCreated = + components['schemas']['NotificationRuleInvoiceCreated'] +export type NotificationRuleInvoiceCreatedCreateRequest = + components['schemas']['NotificationRuleInvoiceCreatedCreateRequest'] +export type NotificationRuleInvoiceUpdated = + components['schemas']['NotificationRuleInvoiceUpdated'] +export type NotificationRuleInvoiceUpdatedCreateRequest = + components['schemas']['NotificationRuleInvoiceUpdatedCreateRequest'] +export type NotificationRuleOrderBy = + components['schemas']['NotificationRuleOrderBy'] +export type NotificationRulePaginatedResponse = + components['schemas']['NotificationRulePaginatedResponse'] +export type Numeric = components['schemas']['Numeric'] +export type OAuth2AuthorizationCodeGrantErrorType = + components['schemas']['OAuth2AuthorizationCodeGrantErrorType'] +export type PackagePriceWithCommitments = + components['schemas']['PackagePriceWithCommitments'] +export type PaymentDueDate = components['schemas']['PaymentDueDate'] +export type PaymentTermDueDate = components['schemas']['PaymentTermDueDate'] +export type PaymentTermInstant = components['schemas']['PaymentTermInstant'] +export type PaymentTerms = components['schemas']['PaymentTerms'] +export type Percentage = components['schemas']['Percentage'] +export type Period = components['schemas']['Period'] +export type Plan = components['schemas']['Plan'] +export type PlanAddon = components['schemas']['PlanAddon'] +export type PlanAddonCreate = components['schemas']['PlanAddonCreate'] +export type PlanAddonOrderBy = components['schemas']['PlanAddonOrderBy'] +export type PlanAddonPaginatedResponse = + components['schemas']['PlanAddonPaginatedResponse'] +export type PlanAddonReplaceUpdate = + components['schemas']['PlanAddonReplaceUpdate'] +export type PlanCreate = components['schemas']['PlanCreate'] +export type PlanOrderBy = components['schemas']['PlanOrderBy'] +export type PlanPaginatedResponse = + components['schemas']['PlanPaginatedResponse'] +export type PlanPhase = components['schemas']['PlanPhase'] +export type PlanReference = components['schemas']['PlanReference'] +export type PlanReferenceInput = components['schemas']['PlanReferenceInput'] +export type PlanReplaceUpdate = components['schemas']['PlanReplaceUpdate'] +export type PlanStatus = components['schemas']['PlanStatus'] +export type PlanSubscriptionChange = + components['schemas']['PlanSubscriptionChange'] +export type PlanSubscriptionCreate = + components['schemas']['PlanSubscriptionCreate'] +export type PortalToken = components['schemas']['PortalToken'] +export type PreconditionFailedProblemResponse = + components['schemas']['PreconditionFailedProblemResponse'] +export type PricePaymentTerm = components['schemas']['PricePaymentTerm'] +export type PriceTier = components['schemas']['PriceTier'] +export type ProRatingConfig = components['schemas']['ProRatingConfig'] +export type ProRatingMode = components['schemas']['ProRatingMode'] +export type Progress = components['schemas']['Progress'] +export type RateCard = components['schemas']['RateCard'] +export type RateCardBooleanEntitlement = + components['schemas']['RateCardBooleanEntitlement'] +export type RateCardEntitlement = components['schemas']['RateCardEntitlement'] +export type RateCardFlatFee = components['schemas']['RateCardFlatFee'] +export type RateCardMeteredEntitlement = + components['schemas']['RateCardMeteredEntitlement'] +export type RateCardStaticEntitlement = + components['schemas']['RateCardStaticEntitlement'] +export type RateCardUsageBased = components['schemas']['RateCardUsageBased'] +export type RateCardUsageBasedPrice = + components['schemas']['RateCardUsageBasedPrice'] +export type RecurringPeriod = components['schemas']['RecurringPeriod'] +export type RecurringPeriodCreateInput = + components['schemas']['RecurringPeriodCreateInput'] +export type RecurringPeriodInterval = + components['schemas']['RecurringPeriodInterval'] +export type RecurringPeriodIntervalEnum = + components['schemas']['RecurringPeriodIntervalEnum'] +export type RecurringPeriodV2 = components['schemas']['RecurringPeriodV2'] +export type RemovePhaseShifting = components['schemas']['RemovePhaseShifting'] +export type ResetEntitlementUsageInput = + components['schemas']['ResetEntitlementUsageInput'] +export type SandboxApp = components['schemas']['SandboxApp'] +export type SandboxAppReplaceUpdate = + components['schemas']['SandboxAppReplaceUpdate'] +export type SandboxCustomerAppData = + components['schemas']['SandboxCustomerAppData'] +export type ServiceUnavailableProblemResponse = + components['schemas']['ServiceUnavailableProblemResponse'] +export type SortOrder = components['schemas']['SortOrder'] +export type StripeApiKeyInput = components['schemas']['StripeAPIKeyInput'] +export type StripeApp = components['schemas']['StripeApp'] +export type StripeAppReplaceUpdate = + components['schemas']['StripeAppReplaceUpdate'] +export type StripeCheckoutSessionMode = + components['schemas']['StripeCheckoutSessionMode'] +export type StripeCustomerAppData = + components['schemas']['StripeCustomerAppData'] +export type StripeCustomerAppDataBase = + components['schemas']['StripeCustomerAppDataBase'] +export type StripeCustomerAppDataCreateOrUpdateItem = + components['schemas']['StripeCustomerAppDataCreateOrUpdateItem'] +export type StripeCustomerPortalSession = + components['schemas']['StripeCustomerPortalSession'] +export type StripeTaxConfig = components['schemas']['StripeTaxConfig'] +export type StripeWebhookEvent = components['schemas']['StripeWebhookEvent'] +export type StripeWebhookResponse = + components['schemas']['StripeWebhookResponse'] +export type Subject = components['schemas']['Subject'] +export type SubjectUpsert = components['schemas']['SubjectUpsert'] +export type Subscription = components['schemas']['Subscription'] +export type SubscriptionAddon = components['schemas']['SubscriptionAddon'] +export type SubscriptionAddonCreate = + components['schemas']['SubscriptionAddonCreate'] +export type SubscriptionAddonRateCard = + components['schemas']['SubscriptionAddonRateCard'] +export type SubscriptionAddonTimelineSegment = + components['schemas']['SubscriptionAddonTimelineSegment'] +export type SubscriptionAddonUpdate = + components['schemas']['SubscriptionAddonUpdate'] +export type SubscriptionAlignment = + components['schemas']['SubscriptionAlignment'] +export type SubscriptionBadRequestErrorResponse = + components['schemas']['SubscriptionBadRequestErrorResponse'] +export type SubscriptionChange = components['schemas']['SubscriptionChange'] +export type SubscriptionChangeResponseBody = + components['schemas']['SubscriptionChangeResponseBody'] +export type SubscriptionConflictErrorResponse = + components['schemas']['SubscriptionConflictErrorResponse'] +export type SubscriptionCreate = components['schemas']['SubscriptionCreate'] +export type SubscriptionEdit = components['schemas']['SubscriptionEdit'] +export type SubscriptionEditOperation = + components['schemas']['SubscriptionEditOperation'] +export type SubscriptionErrorExtensions = + components['schemas']['SubscriptionErrorExtensions'] +export type SubscriptionExpanded = components['schemas']['SubscriptionExpanded'] +export type SubscriptionItem = components['schemas']['SubscriptionItem'] +export type SubscriptionItemIncluded = + components['schemas']['SubscriptionItemIncluded'] +export type SubscriptionPaginatedResponse = + components['schemas']['SubscriptionPaginatedResponse'] +export type SubscriptionPhaseCreate = + components['schemas']['SubscriptionPhaseCreate'] +export type SubscriptionPhaseExpanded = + components['schemas']['SubscriptionPhaseExpanded'] +export type SubscriptionStatus = components['schemas']['SubscriptionStatus'] +export type SubscriptionTiming = components['schemas']['SubscriptionTiming'] +export type SubscriptionTimingEnum = + components['schemas']['SubscriptionTimingEnum'] +export type TaxBehavior = components['schemas']['TaxBehavior'] +export type TaxConfig = components['schemas']['TaxConfig'] +export type TieredPriceMode = components['schemas']['TieredPriceMode'] +export type TieredPriceWithCommitments = + components['schemas']['TieredPriceWithCommitments'] +export type UlidOrExternalKey = components['schemas']['ULIDOrExternalKey'] +export type UnauthorizedProblemResponse = + components['schemas']['UnauthorizedProblemResponse'] +export type UnexpectedProblemResponse = + components['schemas']['UnexpectedProblemResponse'] +export type UnitPrice = components['schemas']['UnitPrice'] +export type UnitPriceWithCommitments = + components['schemas']['UnitPriceWithCommitments'] +export type ValidationError = components['schemas']['ValidationError'] +export type ValidationIssue = components['schemas']['ValidationIssue'] +export type ValidationIssueSeverity = + components['schemas']['ValidationIssueSeverity'] +export type VoidInvoiceActionCreate = + components['schemas']['VoidInvoiceActionCreate'] +export type VoidInvoiceActionCreateItem = + components['schemas']['VoidInvoiceActionCreateItem'] +export type VoidInvoiceActionInput = + components['schemas']['VoidInvoiceActionInput'] +export type VoidInvoiceActionLineOverride = + components['schemas']['VoidInvoiceActionLineOverride'] +export type VoidInvoiceLineActionCreate = + components['schemas']['VoidInvoiceLineActionCreate'] +export type VoidInvoiceLineActionCreateItem = + components['schemas']['VoidInvoiceLineActionCreateItem'] +export type VoidInvoiceLineDiscardAction = + components['schemas']['VoidInvoiceLineDiscardAction'] +export type VoidInvoiceLinePendingActionCreate = + components['schemas']['VoidInvoiceLinePendingActionCreate'] +export type VoidInvoiceLinePendingActionCreateItem = + components['schemas']['VoidInvoiceLinePendingActionCreateItem'] +export type WindowSize = components['schemas']['WindowSize'] +export type WindowedBalanceHistory = + components['schemas']['WindowedBalanceHistory'] +export type ParameterAddonOrderByOrderingOrder = + components['parameters']['AddonOrderByOrdering.order'] +export type ParameterAddonOrderByOrderingOrderBy = + components['parameters']['AddonOrderByOrdering.orderBy'] +export type ParameterBillingProfileCustomerOverrideOrderByOrderingOrder = + components['parameters']['BillingProfileCustomerOverrideOrderByOrdering.order'] +export type ParameterBillingProfileCustomerOverrideOrderByOrderingOrderBy = + components['parameters']['BillingProfileCustomerOverrideOrderByOrdering.orderBy'] +export type ParameterBillingProfileListCustomerOverridesParamsBillingProfile = + components['parameters']['BillingProfileListCustomerOverridesParams.billingProfile'] +export type ParameterBillingProfileListCustomerOverridesParamsCustomerId = + components['parameters']['BillingProfileListCustomerOverridesParams.customerId'] +export type ParameterBillingProfileListCustomerOverridesParamsCustomerKey = + components['parameters']['BillingProfileListCustomerOverridesParams.customerKey'] +export type ParameterBillingProfileListCustomerOverridesParamsCustomerName = + components['parameters']['BillingProfileListCustomerOverridesParams.customerName'] +export type ParameterBillingProfileListCustomerOverridesParamsCustomerPrimaryEmail = + components['parameters']['BillingProfileListCustomerOverridesParams.customerPrimaryEmail'] +export type ParameterBillingProfileListCustomerOverridesParamsCustomersWithoutPinnedProfile = + components['parameters']['BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile'] +export type ParameterBillingProfileListCustomerOverridesParamsExpand = + components['parameters']['BillingProfileListCustomerOverridesParams.expand'] +export type ParameterBillingProfileListCustomerOverridesParamsIncludeAllCustomers = + components['parameters']['BillingProfileListCustomerOverridesParams.includeAllCustomers'] +export type ParameterBillingProfileOrderByOrderingOrder = + components['parameters']['BillingProfileOrderByOrdering.order'] +export type ParameterBillingProfileOrderByOrderingOrderBy = + components['parameters']['BillingProfileOrderByOrdering.orderBy'] +export type ParameterCursorPaginationCursor = + components['parameters']['CursorPagination.cursor'] +export type ParameterCursorPaginationLimit = + components['parameters']['CursorPagination.limit'] +export type ParameterCustomerOrderByOrderingOrder = + components['parameters']['CustomerOrderByOrdering.order'] +export type ParameterCustomerOrderByOrderingOrderBy = + components['parameters']['CustomerOrderByOrdering.orderBy'] +export type ParameterCustomerSubscriptionOrderByOrderingOrder = + components['parameters']['CustomerSubscriptionOrderByOrdering.order'] +export type ParameterCustomerSubscriptionOrderByOrderingOrderBy = + components['parameters']['CustomerSubscriptionOrderByOrdering.orderBy'] +export type ParameterEntitlementOrderByOrderingOrder = + components['parameters']['EntitlementOrderByOrdering.order'] +export type ParameterEntitlementOrderByOrderingOrderBy = + components['parameters']['EntitlementOrderByOrdering.orderBy'] +export type ParameterFeatureOrderByOrderingOrder = + components['parameters']['FeatureOrderByOrdering.order'] +export type ParameterFeatureOrderByOrderingOrderBy = + components['parameters']['FeatureOrderByOrdering.orderBy'] +export type ParameterGrantOrderByOrderingOrder = + components['parameters']['GrantOrderByOrdering.order'] +export type ParameterGrantOrderByOrderingOrderBy = + components['parameters']['GrantOrderByOrdering.orderBy'] +export type ParameterInvoiceListParamsCreatedAfter = + components['parameters']['InvoiceListParams.createdAfter'] +export type ParameterInvoiceListParamsCreatedBefore = + components['parameters']['InvoiceListParams.createdBefore'] +export type ParameterInvoiceListParamsCustomers = + components['parameters']['InvoiceListParams.customers'] +export type ParameterInvoiceListParamsExpand = + components['parameters']['InvoiceListParams.expand'] +export type ParameterInvoiceListParamsExtendedStatuses = + components['parameters']['InvoiceListParams.extendedStatuses'] +export type ParameterInvoiceListParamsIncludeDeleted = + components['parameters']['InvoiceListParams.includeDeleted'] +export type ParameterInvoiceListParamsIssuedAfter = + components['parameters']['InvoiceListParams.issuedAfter'] +export type ParameterInvoiceListParamsIssuedBefore = + components['parameters']['InvoiceListParams.issuedBefore'] +export type ParameterInvoiceListParamsPeriodStartAfter = + components['parameters']['InvoiceListParams.periodStartAfter'] +export type ParameterInvoiceListParamsPeriodStartBefore = + components['parameters']['InvoiceListParams.periodStartBefore'] +export type ParameterInvoiceListParamsStatuses = + components['parameters']['InvoiceListParams.statuses'] +export type ParameterInvoiceOrderByOrderingOrder = + components['parameters']['InvoiceOrderByOrdering.order'] +export type ParameterInvoiceOrderByOrderingOrderBy = + components['parameters']['InvoiceOrderByOrdering.orderBy'] +export type ParameterLimitOffsetLimit = + components['parameters']['LimitOffset.limit'] +export type ParameterLimitOffsetOffset = + components['parameters']['LimitOffset.offset'] +export type ParameterMarketplaceApiKeyInstallRequestType = + components['parameters']['MarketplaceApiKeyInstallRequest.type'] +export type ParameterMarketplaceInstallRequestType = + components['parameters']['MarketplaceInstallRequest.type'] +export type ParameterMarketplaceOAuth2InstallAuthorizeRequestType = + components['parameters']['MarketplaceOAuth2InstallAuthorizeRequest.type'] +export type ParameterMeterOrderByOrderingOrder = + components['parameters']['MeterOrderByOrdering.order'] +export type ParameterMeterOrderByOrderingOrderBy = + components['parameters']['MeterOrderByOrdering.orderBy'] +export type ParameterMeterQueryAdvancedMeterGroupByFilters = + components['parameters']['MeterQuery.advancedMeterGroupByFilters'] +export type ParameterMeterQueryClientId = + components['parameters']['MeterQuery.clientId'] +export type ParameterMeterQueryFilterCustomerId = + components['parameters']['MeterQuery.filterCustomerId'] +export type ParameterMeterQueryFilterGroupBy = + components['parameters']['MeterQuery.filterGroupBy'] +export type ParameterMeterQueryFrom = + components['parameters']['MeterQuery.from'] +export type ParameterMeterQueryGroupBy = + components['parameters']['MeterQuery.groupBy'] +export type ParameterMeterQuerySubject = + components['parameters']['MeterQuery.subject'] +export type ParameterMeterQueryTo = components['parameters']['MeterQuery.to'] +export type ParameterMeterQueryWindowSize = + components['parameters']['MeterQuery.windowSize'] +export type ParameterMeterQueryWindowTimeZone = + components['parameters']['MeterQuery.windowTimeZone'] +export type ParameterNotificationChannelOrderByOrderingOrder = + components['parameters']['NotificationChannelOrderByOrdering.order'] +export type ParameterNotificationChannelOrderByOrderingOrderBy = + components['parameters']['NotificationChannelOrderByOrdering.orderBy'] +export type ParameterNotificationEventOrderByOrderingOrder = + components['parameters']['NotificationEventOrderByOrdering.order'] +export type ParameterNotificationEventOrderByOrderingOrderBy = + components['parameters']['NotificationEventOrderByOrdering.orderBy'] +export type ParameterNotificationRuleOrderByOrderingOrder = + components['parameters']['NotificationRuleOrderByOrdering.order'] +export type ParameterNotificationRuleOrderByOrderingOrderBy = + components['parameters']['NotificationRuleOrderByOrdering.orderBy'] +export type ParameterOAuth2AuthorizationCodeGrantErrorParamsError = + components['parameters']['OAuth2AuthorizationCodeGrantErrorParams.error'] +export type ParameterOAuth2AuthorizationCodeGrantErrorParamsErrorDescription = + components['parameters']['OAuth2AuthorizationCodeGrantErrorParams.error_description'] +export type ParameterOAuth2AuthorizationCodeGrantErrorParamsErrorUri = + components['parameters']['OAuth2AuthorizationCodeGrantErrorParams.error_uri'] +export type ParameterOAuth2AuthorizationCodeGrantSuccessParamsCode = + components['parameters']['OAuth2AuthorizationCodeGrantSuccessParams.code'] +export type ParameterOAuth2AuthorizationCodeGrantSuccessParamsState = + components['parameters']['OAuth2AuthorizationCodeGrantSuccessParams.state'] +export type ParameterPaginationPage = + components['parameters']['Pagination.page'] +export type ParameterPaginationPageSize = + components['parameters']['Pagination.pageSize'] +export type ParameterPlanAddonOrderByOrderingOrder = + components['parameters']['PlanAddonOrderByOrdering.order'] +export type ParameterPlanAddonOrderByOrderingOrderBy = + components['parameters']['PlanAddonOrderByOrdering.orderBy'] +export type ParameterPlanOrderByOrderingOrder = + components['parameters']['PlanOrderByOrdering.order'] +export type ParameterPlanOrderByOrderingOrderBy = + components['parameters']['PlanOrderByOrdering.orderBy'] +export type ParameterListCustomerAppDataParamsType = + components['parameters']['listCustomerAppDataParams.type'] +export type ParameterQueryCustomerGet = + components['parameters']['queryCustomerGet'] +export type ParameterQueryCustomerListExpand = + components['parameters']['queryCustomerList.expand'] +export type ParameterQueryCustomerListIncludeDeleted = + components['parameters']['queryCustomerList.includeDeleted'] +export type ParameterQueryCustomerListKey = + components['parameters']['queryCustomerList.key'] +export type ParameterQueryCustomerListName = + components['parameters']['queryCustomerList.name'] +export type ParameterQueryCustomerListPlanKey = + components['parameters']['queryCustomerList.planKey'] +export type ParameterQueryCustomerListPrimaryEmail = + components['parameters']['queryCustomerList.primaryEmail'] +export type ParameterQueryCustomerListSubject = + components['parameters']['queryCustomerList.subject'] +export type ParameterQueryMeterListIncludeDeleted = + components['parameters']['queryMeterList.includeDeleted'] +export type $defs = Record +export interface operations { + listAddons: { + parameters: { + query?: { + /** + * @description Include deleted add-ons in response. + * + * Usage: `?includeDeleted=true` + */ + includeDeleted?: boolean + /** @description Filter by addon.id attribute */ + id?: string[] + /** @description Filter by addon.key attribute */ + key?: string[] + /** @description Filter by addon.key and addon.version attributes */ + keyVersion?: { + [key: string]: number[] + } + /** + * @description Only return add-ons with the given status. + * + * Usage: + * - `?status=active`: return only the currently active add-ons + * - `?status=draft`: return only the draft add-ons + * - `?status=archived`: return only the archived add-ons + */ + status?: components['schemas']['AddonStatus'][] + /** @description Filter by addon.currency attribute */ + currency?: components['schemas']['CurrencyCode'][] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['AddonOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['AddonOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['AddonPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createAddon: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['AddonCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Addon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getAddon: { + parameters: { + query?: { + /** + * @description Include latest version of the add-on instead of the version in active state. + * + * Usage: `?includeLatest=true` + */ + includeLatest?: boolean + } + header?: never + path: { + addonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Addon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateAddon: { + parameters: { + query?: never + header?: never + path: { + addonId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['AddonReplaceUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Addon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteAddon: { + parameters: { + query?: never + header?: never + path: { + addonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + archiveAddon: { + parameters: { + query?: never + header?: never + path: { + addonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Addon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + publishAddon: { + parameters: { + query?: never + header?: never + path: { + addonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Addon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listApps: { + parameters: { + query?: { + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['AppPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + appCustomInvoicingDraftSynchronized: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CustomInvoicingDraftSynchronizedRequest'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + appCustomInvoicingIssuingSynchronized: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CustomInvoicingFinalizedRequest'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + appCustomInvoicingUpdatePaymentStatus: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CustomInvoicingUpdatePaymentStatusRequest'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getApp: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['App'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateApp: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['AppReplaceUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['App'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + uninstallApp: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateStripeAPIKey: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['StripeAPIKeyInput'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + appStripeWebhook: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['StripeWebhookEvent'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['StripeWebhookResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listBillingProfileCustomerOverrides: { + parameters: { + query?: { + /** @description Filter by billing profile. */ + billingProfile?: components['parameters']['BillingProfileListCustomerOverridesParams.billingProfile'] + /** @description Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. */ + customersWithoutPinnedProfile?: components['parameters']['BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile'] + /** + * @description Include customers without customer overrides. + * + * If set to false only the customers specifically associated with a billing profile will be returned. + * + * If set to true, in case of the default billing profile, all customers will be returned. + */ + includeAllCustomers?: components['parameters']['BillingProfileListCustomerOverridesParams.includeAllCustomers'] + /** @description Filter by customer id. */ + customerId?: components['parameters']['BillingProfileListCustomerOverridesParams.customerId'] + /** @description Filter by customer name. */ + customerName?: components['parameters']['BillingProfileListCustomerOverridesParams.customerName'] + /** @description Filter by customer key */ + customerKey?: components['parameters']['BillingProfileListCustomerOverridesParams.customerKey'] + /** @description Filter by customer primary email */ + customerPrimaryEmail?: components['parameters']['BillingProfileListCustomerOverridesParams.customerPrimaryEmail'] + /** @description Expand the response with additional details. */ + expand?: components['parameters']['BillingProfileListCustomerOverridesParams.expand'] + /** @description The order direction. */ + order?: components['parameters']['BillingProfileCustomerOverrideOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['BillingProfileCustomerOverrideOrderByOrdering.orderBy'] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfileCustomerOverrideWithDetailsPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getBillingProfileCustomerOverride: { + parameters: { + query?: { + expand?: components['schemas']['BillingProfileCustomerOverrideExpand'][] + } + header?: never + path: { + customerId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfileCustomerOverrideWithDetails'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + upsertBillingProfileCustomerOverride: { + parameters: { + query?: never + header?: never + path: { + customerId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['BillingProfileCustomerOverrideCreate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfileCustomerOverrideWithDetails'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteBillingProfileCustomerOverride: { + parameters: { + query?: never + header?: never + path: { + customerId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createPendingInvoiceLine: { + parameters: { + query?: never + header?: never + path: { + customerId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['InvoicePendingLineCreateInput'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['InvoicePendingLineCreateResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + simulateInvoice: { + parameters: { + query?: never + header?: never + path: { + customerId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['InvoiceSimulationInput'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listInvoices: { + parameters: { + query?: { + /** @description Filter by the invoice status. */ + statuses?: components['parameters']['InvoiceListParams.statuses'] + /** @description Filter by invoice extended statuses */ + extendedStatuses?: components['parameters']['InvoiceListParams.extendedStatuses'] + /** + * @description Filter by invoice issued time. + * Inclusive. + */ + issuedAfter?: components['parameters']['InvoiceListParams.issuedAfter'] + /** + * @description Filter by invoice issued time. + * Inclusive. + */ + issuedBefore?: components['parameters']['InvoiceListParams.issuedBefore'] + /** + * @description Filter by period start time. + * Inclusive. + */ + periodStartAfter?: components['parameters']['InvoiceListParams.periodStartAfter'] + /** + * @description Filter by period start time. + * Inclusive. + */ + periodStartBefore?: components['parameters']['InvoiceListParams.periodStartBefore'] + /** + * @description Filter by invoice created time. + * Inclusive. + */ + createdAfter?: components['parameters']['InvoiceListParams.createdAfter'] + /** + * @description Filter by invoice created time. + * Inclusive. + */ + createdBefore?: components['parameters']['InvoiceListParams.createdBefore'] + /** @description What parts of the list output to expand in listings */ + expand?: components['parameters']['InvoiceListParams.expand'] + /** @description Filter by customer ID */ + customers?: components['parameters']['InvoiceListParams.customers'] + /** @description Include deleted invoices */ + includeDeleted?: components['parameters']['InvoiceListParams.includeDeleted'] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['InvoiceOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['InvoiceOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['InvoicePaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + invoicePendingLinesAction: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['InvoicePendingLinesActionInput'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getInvoice: { + parameters: { + query?: { + expand?: components['schemas']['InvoiceExpand'][] + includeDeletedLines?: boolean + } + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateInvoice: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['InvoiceReplaceUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteInvoice: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + advanceInvoiceAction: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + approveInvoiceAction: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + retryInvoiceAction: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + snapshotQuantitiesInvoiceAction: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + recalculateInvoiceTaxAction: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + voidInvoiceAction: { + parameters: { + query?: never + header?: never + path: { + invoiceId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['VoidInvoiceActionInput'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Invoice'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listBillingProfiles: { + parameters: { + query?: { + includeArchived?: boolean + expand?: components['schemas']['BillingProfileExpand'][] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['BillingProfileOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['BillingProfileOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfilePaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createBillingProfile: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['BillingProfileCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfile'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getBillingProfile: { + parameters: { + query?: { + expand?: components['schemas']['BillingProfileExpand'][] + } + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfile'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateBillingProfile: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['BillingProfileReplaceUpdateWithWorkflow'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['BillingProfile'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteBillingProfile: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listCustomers: { + parameters: { + query?: { + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['CustomerOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['CustomerOrderByOrdering.orderBy'] + /** @description Include deleted customers. */ + includeDeleted?: components['parameters']['queryCustomerList.includeDeleted'] + /** + * @description Filter customers by key. + * Case-insensitive partial match. + */ + key?: components['parameters']['queryCustomerList.key'] + /** + * @description Filter customers by name. + * Case-insensitive partial match. + */ + name?: components['parameters']['queryCustomerList.name'] + /** + * @description Filter customers by primary email. + * Case-insensitive partial match. + */ + primaryEmail?: components['parameters']['queryCustomerList.primaryEmail'] + /** + * @description Filter customers by usage attribution subject. + * Case-insensitive partial match. + */ + subject?: components['parameters']['queryCustomerList.subject'] + /** @description Filter customers by the plan key of their susbcription. */ + planKey?: components['parameters']['queryCustomerList.planKey'] + /** @description What parts of the list output to expand in listings */ + expand?: components['parameters']['queryCustomerList.expand'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['CustomerPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createCustomer: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CustomerCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Customer'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomer: { + parameters: { + query?: { + /** @description What parts of the customer output to expand */ + expand?: components['parameters']['queryCustomerGet'] + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Customer'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateCustomer: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CustomerReplaceUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Customer'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteCustomer: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomerAccess: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['CustomerAccess'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listCustomerAppData: { + parameters: { + query?: { + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description Filter customer data by app type. */ + type?: components['parameters']['listCustomerAppDataParams.type'] + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['CustomerAppDataPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + upsertCustomerAppData: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CustomerAppDataCreateOrUpdateItem'][] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['CustomerAppData'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteCustomerAppData: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + appId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomerEntitlementValue: { + parameters: { + query?: { + time?: Date | string + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + featureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementValue'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomerStripeAppData: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['StripeCustomerAppData'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + upsertCustomerStripeAppData: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['StripeCustomerAppDataBase'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['StripeCustomerAppData'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createCustomerStripePortalSession: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CreateStripeCustomerPortalSessionParams'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['StripeCustomerPortalSession'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listCustomerSubscriptions: { + parameters: { + query?: { + status?: components['schemas']['SubscriptionStatus'][] + /** @description The order direction. */ + order?: components['parameters']['CustomerSubscriptionOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['CustomerSubscriptionOrderByOrdering.orderBy'] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getDebugMetrics: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'text/plain': string + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listEntitlements: { + parameters: { + query?: { + /** + * @description Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + feature?: string[] + /** + * @description Filtering by multiple subjects. + * + * Usage: `?subject=customer-1&subject=customer-2` + */ + subject?: string[] + /** + * @description Filtering by multiple entitlement types. + * + * Usage: `?entitlementType=metered&entitlementType=boolean` + */ + entitlementType?: components['schemas']['EntitlementType'][] + /** @description Exclude inactive entitlements in the response (those scheduled for later or earlier) */ + excludeInactive?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** + * @description Number of items to skip. + * + * Default is 0. + */ + offset?: components['parameters']['LimitOffset.offset'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + limit?: components['parameters']['LimitOffset.limit'] + /** @description The order direction. */ + order?: components['parameters']['EntitlementOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['EntitlementOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['ListEntitlementsResult'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getEntitlementById: { + parameters: { + query?: never + header?: never + path: { + entitlementId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Entitlement'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listEvents: { + parameters: { + query?: { + /** + * @description Client ID + * Useful to track progress of a query. + */ + clientId?: string + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. + */ + ingestedAtFrom?: Date | string + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + */ + ingestedAtTo?: Date | string + /** + * @description The event ID. + * + * Accepts partial ID. + */ + id?: string + /** + * @description The event subject. + * + * Accepts partial subject. + */ + subject?: string + /** @description The event customer ID. */ + customerId?: string[] + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. + */ + from?: Date | string + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + */ + to?: Date | string + /** @description Number of events to return. */ + limit?: number + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['IngestedEvent'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + ingestEvents: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/cloudevents+json': components['schemas']['Event'] + 'application/cloudevents-batch+json': components['schemas']['Event'][] + 'application/json': components['schemas']['IngestEventsBody'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listFeatures: { + parameters: { + query?: { + /** @description Filter by meterSlug */ + meterSlug?: string[] + /** @description Include archived features in response. */ + includeArchived?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** + * @description Number of items to skip. + * + * Default is 0. + */ + offset?: components['parameters']['LimitOffset.offset'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + limit?: components['parameters']['LimitOffset.limit'] + /** @description The order direction. */ + order?: components['parameters']['FeatureOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['FeatureOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['ListFeaturesResult'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createFeature: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['FeatureCreateInputs'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Feature'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getFeature: { + parameters: { + query?: never + header?: never + path: { + featureId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Feature'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteFeature: { + parameters: { + query?: never + header?: never + path: { + featureId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listGrants: { + parameters: { + query?: { + /** + * @description Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + feature?: string[] + /** + * @description Filtering by multiple subjects. + * + * Usage: `?subject=customer-1&subject=customer-2` + */ + subject?: string[] + /** @description Include deleted */ + includeDeleted?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** + * @description Number of items to skip. + * + * Default is 0. + */ + offset?: components['parameters']['LimitOffset.offset'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + limit?: components['parameters']['LimitOffset.limit'] + /** @description The order direction. */ + order?: components['parameters']['GrantOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['GrantOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': + | components['schemas']['EntitlementGrant'][] + | components['schemas']['GrantPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + voidGrant: { + parameters: { + query?: { + /** + * @description The time at which the grant should be voided. + * Must not be in the future and must be within the current usage period of the entitlement. + * Defaults to the current time if not specified. + */ + at?: Date | string + } + header?: never + path: { + grantId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listCurrencies: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Currency'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getProgress: { + parameters: { + query?: never + header?: never + path: { + id: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Progress'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listMarketplaceListings: { + parameters: { + query?: { + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MarketplaceListingPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getMarketplaceListing: { + parameters: { + query?: never + header?: never + path: { + type: components['schemas']['AppType'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MarketplaceListing'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + marketplaceAppInstall: { + parameters: { + query?: never + header?: never + path: { + /** @description The type of the app to install. */ + type: components['parameters']['MarketplaceInstallRequest.type'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['MarketplaceInstallRequestPayload'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MarketplaceInstallResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + marketplaceAppAPIKeyInstall: { + parameters: { + query?: never + header?: never + path: { + /** @description The type of the app to install. */ + type: components['parameters']['MarketplaceApiKeyInstallRequest.type'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': { + /** + * @description Name of the application to install. + * + * If name is not provided defaults to the marketplace listing's name. + */ + name?: string + /** + * @description If true, a billing profile will be created for the app. + * The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + * @default true + */ + createBillingProfile?: boolean + /** + * @description The API key for the provider. + * For example, the Stripe API key. + */ + apiKey: string + } + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MarketplaceInstallResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + marketplaceOAuth2InstallGetURL: { + parameters: { + query?: never + header?: never + path: { + type: components['schemas']['AppType'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['ClientAppStartResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + marketplaceOAuth2InstallAuthorize: { + parameters: { + query?: { + /** + * @description Required if the "state" parameter was present in the client authorization request. + * The exact value received from the client: + * + * Unique, randomly generated, opaque, and non-guessable string that is sent + * when starting an authentication request and validated when processing the response. + */ + state?: components['parameters']['OAuth2AuthorizationCodeGrantSuccessParams.state'] + /** + * @description Authorization code which the client will later exchange for an access token. + * Required with the success response. + */ + code?: components['parameters']['OAuth2AuthorizationCodeGrantSuccessParams.code'] + /** + * @description Error code. + * Required with the error response. + */ + error?: components['parameters']['OAuth2AuthorizationCodeGrantErrorParams.error'] + /** + * @description Optional human-readable text providing additional information, + * used to assist the client developer in understanding the error that occurred. + */ + error_description?: components['parameters']['OAuth2AuthorizationCodeGrantErrorParams.error_description'] + /** + * @description Optional uri identifying a human-readable web page with + * information about the error, used to provide the client + * developer with additional information about the error + */ + error_uri?: components['parameters']['OAuth2AuthorizationCodeGrantErrorParams.error_uri'] + } + header?: never + path: { + /** @description The type of the app to install. */ + type: components['parameters']['MarketplaceOAuth2InstallAuthorizeRequest.type'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description Redirection */ + 303: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listMeters: { + parameters: { + query?: { + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['MeterOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['MeterOrderByOrdering.orderBy'] + /** @description Include deleted meters. */ + includeDeleted?: components['parameters']['queryMeterList.includeDeleted'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Meter'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createMeter: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['MeterCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Meter'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getMeter: { + parameters: { + query?: never + header?: never + path: { + meterIdOrSlug: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Meter'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateMeter: { + parameters: { + query?: never + header?: never + path: { + meterIdOrSlug: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['MeterUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Meter'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteMeter: { + parameters: { + query?: never + header?: never + path: { + meterIdOrSlug: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listMeterGroupByValues: { + parameters: { + query?: { + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. Defaults to 24 hours ago. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + from?: Date | string + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + to?: Date | string + } + header?: never + path: { + meterIdOrSlug: string + groupByKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': string[] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + queryMeter: { + parameters: { + query?: { + /** + * @description Client ID + * Useful to track progress of a query. + */ + clientId?: components['parameters']['MeterQuery.clientId'] + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + from?: components['parameters']['MeterQuery.from'] + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + to?: components['parameters']['MeterQuery.to'] + /** + * @description If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + * + * For example: ?windowSize=DAY + */ + windowSize?: components['parameters']['MeterQuery.windowSize'] + /** + * @description The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + * If not specified, the UTC timezone will be used. + * + * For example: ?windowTimeZone=UTC + */ + windowTimeZone?: components['parameters']['MeterQuery.windowTimeZone'] + /** + * @description Filtering by multiple subjects. + * + * For example: ?subject=subject-1&subject=subject-2 + */ + subject?: components['parameters']['MeterQuery.subject'] + /** + * @description Filtering by multiple customers. + * + * For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + */ + filterCustomerId?: components['parameters']['MeterQuery.filterCustomerId'] + /** + * @deprecated + * @description Simple filter for group bys with exact match. + * + * For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + * + * ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + */ + filterGroupBy?: components['parameters']['MeterQuery.filterGroupBy'] + /** + * @description Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + */ + advancedMeterGroupByFilters?: components['parameters']['MeterQuery.advancedMeterGroupByFilters'] + /** + * @description If not specified a single aggregate will be returned for each subject and time window. + * `subject` is a reserved group by value. + * + * For example: ?groupBy=subject&groupBy=model + */ + groupBy?: components['parameters']['MeterQuery.groupBy'] + } + header?: never + path: { + meterIdOrSlug: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MeterQueryResult'] + 'text/csv': string + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + queryMeterPost: { + parameters: { + query?: never + header?: never + path: { + meterIdOrSlug: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['MeterQueryRequest'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MeterQueryResult'] + 'text/csv': string + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listMeterSubjects: { + parameters: { + query?: { + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. Defaults to the beginning of time. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + from?: Date | string + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + to?: Date | string + } + header?: never + path: { + meterIdOrSlug: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': string[] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listNotificationChannels: { + parameters: { + query?: { + /** + * @description Include deleted notification channels in response. + * + * Usage: `?includeDeleted=true` + */ + includeDeleted?: boolean + /** + * @description Include disabled notification channels in response. + * + * Usage: `?includeDisabled=false` + */ + includeDisabled?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['NotificationChannelOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['NotificationChannelOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationChannelPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createNotificationChannel: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['NotificationChannelCreateRequest'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationChannel'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getNotificationChannel: { + parameters: { + query?: never + header?: never + path: { + channelId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationChannel'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateNotificationChannel: { + parameters: { + query?: never + header?: never + path: { + channelId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['NotificationChannelCreateRequest'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationChannel'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteNotificationChannel: { + parameters: { + query?: never + header?: never + path: { + channelId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listNotificationEvents: { + parameters: { + query?: { + /** + * @description Start date-time in RFC 3339 format. + * Inclusive. + */ + from?: Date | string + /** + * @description End date-time in RFC 3339 format. + * Inclusive. + */ + to?: Date | string + /** + * @description Filtering by multiple feature ids or keys. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + feature?: string[] + /** + * @description Filtering by multiple subject ids or keys. + * + * Usage: `?subject=subject-1&subject=subject-2` + */ + subject?: string[] + /** + * @description Filtering by multiple rule ids. + * + * Usage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5` + */ + rule?: string[] + /** + * @description Filtering by multiple channel ids. + * + * Usage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J` + */ + channel?: string[] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['NotificationEventOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['NotificationEventOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationEventPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getNotificationEvent: { + parameters: { + query?: never + header?: never + path: { + eventId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationEvent'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + resendNotificationEvent: { + parameters: { + query?: never + header?: never + path: { + eventId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['NotificationEventResendRequest'] + } + } + responses: { + /** @description The request has been accepted for processing, but processing has not yet completed. */ + 202: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listNotificationRules: { + parameters: { + query?: { + /** + * @description Include deleted notification rules in response. + * + * Usage: `?includeDeleted=true` + */ + includeDeleted?: boolean + /** + * @description Include disabled notification rules in response. + * + * Usage: `?includeDisabled=false` + */ + includeDisabled?: boolean + /** + * @description Filtering by multiple feature ids/keys. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + feature?: string[] + /** + * @description Filtering by multiple notifiaction channel ids. + * + * Usage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3` + */ + channel?: string[] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['NotificationRuleOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['NotificationRuleOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationRulePaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createNotificationRule: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['NotificationRuleCreateRequest'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationRule'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getNotificationRule: { + parameters: { + query?: never + header?: never + path: { + ruleId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationRule'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateNotificationRule: { + parameters: { + query?: never + header?: never + path: { + ruleId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['NotificationRuleCreateRequest'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationRule'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteNotificationRule: { + parameters: { + query?: never + header?: never + path: { + ruleId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + testNotificationRule: { + parameters: { + query?: never + header?: never + path: { + ruleId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['NotificationEvent'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listPlans: { + parameters: { + query?: { + /** + * @description Include deleted plans in response. + * + * Usage: `?includeDeleted=true` + */ + includeDeleted?: boolean + /** @description Filter by plan.id attribute */ + id?: string[] + /** @description Filter by plan.key attribute */ + key?: string[] + /** @description Filter by plan.key and plan.version attributes */ + keyVersion?: { + [key: string]: number[] + } + /** + * @description Only return plans with the given status. + * + * Usage: + * - `?status=active`: return only the currently active plan + * - `?status=draft`: return only the draft plan + * - `?status=archived`: return only the archived plans + */ + status?: components['schemas']['PlanStatus'][] + /** @description Filter by plan.currency attribute */ + currency?: components['schemas']['CurrencyCode'][] + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['PlanOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['PlanOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PlanPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createPlan: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['PlanCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Plan'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + nextPlan: { + parameters: { + query?: never + header?: never + path: { + planIdOrKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Plan'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getPlan: { + parameters: { + query?: { + /** + * @description Include latest version of the Plan instead of the version in active state. + * + * Usage: `?includeLatest=true` + */ + includeLatest?: boolean + } + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Plan'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updatePlan: { + parameters: { + query?: never + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['PlanReplaceUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Plan'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deletePlan: { + parameters: { + query?: never + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listPlanAddons: { + parameters: { + query?: { + /** + * @description Include deleted plan add-on assignments. + * + * Usage: `?includeDeleted=true` + */ + includeDeleted?: boolean + /** @description Filter by addon.id attribute. */ + id?: string[] + /** @description Filter by addon.key attribute. */ + key?: string[] + /** @description Filter by addon.key and addon.version attributes. */ + keyVersion?: { + [key: string]: number[] + } + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['PlanAddonOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['PlanAddonOrderByOrdering.orderBy'] + } + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PlanAddonPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createPlanAddon: { + parameters: { + query?: never + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['PlanAddonCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PlanAddon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getPlanAddon: { + parameters: { + query?: never + header?: never + path: { + planId: string + planAddonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PlanAddon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updatePlanAddon: { + parameters: { + query?: never + header?: never + path: { + planId: string + planAddonId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['PlanAddonReplaceUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PlanAddon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deletePlanAddon: { + parameters: { + query?: never + header?: never + path: { + planId: string + planAddonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + archivePlan: { + parameters: { + query?: never + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Plan'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + publishPlan: { + parameters: { + query?: never + header?: never + path: { + planId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Plan'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + queryPortalMeter: { + parameters: { + query?: { + /** + * @description Client ID + * Useful to track progress of a query. + */ + clientId?: components['parameters']['MeterQuery.clientId'] + /** + * @description Start date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + from?: components['parameters']['MeterQuery.from'] + /** + * @description End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + to?: components['parameters']['MeterQuery.to'] + /** + * @description If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + * + * For example: ?windowSize=DAY + */ + windowSize?: components['parameters']['MeterQuery.windowSize'] + /** + * @description The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + * If not specified, the UTC timezone will be used. + * + * For example: ?windowTimeZone=UTC + */ + windowTimeZone?: components['parameters']['MeterQuery.windowTimeZone'] + /** + * @description Filtering by multiple customers. + * + * For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + */ + filterCustomerId?: components['parameters']['MeterQuery.filterCustomerId'] + /** + * @deprecated + * @description Simple filter for group bys with exact match. + * + * For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + * + * ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + */ + filterGroupBy?: components['parameters']['MeterQuery.filterGroupBy'] + /** + * @description Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + */ + advancedMeterGroupByFilters?: components['parameters']['MeterQuery.advancedMeterGroupByFilters'] + /** + * @description If not specified a single aggregate will be returned for each subject and time window. + * `subject` is a reserved group by value. + * + * For example: ?groupBy=subject&groupBy=model + */ + groupBy?: components['parameters']['MeterQuery.groupBy'] + } + header?: never + path: { + meterSlug: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['MeterQueryResult'] + 'text/csv': string + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listPortalTokens: { + parameters: { + query?: { + limit?: number + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PortalToken'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createPortalToken: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['PortalToken'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['PortalToken'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + invalidatePortalTokens: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': { + /** @description Invalidate a portal token by ID. */ + id?: string + /** @description Invalidate all portal tokens for a subject. */ + subject?: string + } + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createStripeCheckoutSession: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['CreateStripeCheckoutSessionRequest'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['CreateStripeCheckoutSessionResult'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listSubjects: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subject'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + upsertSubject: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['SubjectUpsert'][] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subject'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getSubject: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subject'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteSubject: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listSubjectEntitlements: { + parameters: { + query?: { + includeDeleted?: boolean + } + header?: never + path: { + subjectIdOrKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Entitlement'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createEntitlement: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['EntitlementCreateInputs'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Entitlement'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listEntitlementGrants: { + parameters: { + query?: { + includeDeleted?: boolean + orderBy?: components['schemas']['GrantOrderBy'] + } + header?: never + path: { + subjectIdOrKey: string + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementGrant'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createGrant: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['EntitlementGrantCreateInput'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementGrant'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + overrideEntitlement: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['EntitlementCreateInputs'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Entitlement'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getEntitlementValue: { + parameters: { + query?: { + time?: Date | string + } + header?: never + path: { + subjectIdOrKey: string + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementValue'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getEntitlement: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + entitlementId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Entitlement'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteEntitlement: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + entitlementId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getEntitlementHistory: { + parameters: { + query: { + /** @description Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. */ + from?: Date | string + /** + * @description End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + * If not now then gets truncated to the granularity of the underlying meter. + */ + to?: Date | string + /** @description Windowsize */ + windowSize: components['schemas']['WindowSize'] + /** @description The timezone used when calculating the windows. */ + windowTimeZone?: string + } + header?: never + path: { + subjectIdOrKey: string + entitlementId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['WindowedBalanceHistory'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + resetEntitlementUsage: { + parameters: { + query?: never + header?: never + path: { + subjectIdOrKey: string + entitlementId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['ResetEntitlementUsageInput'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createSubscription: { + parameters: { + query?: never + header?: never + path?: never + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['SubscriptionCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subscription'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getSubscription: { + parameters: { + query?: { + /** @description The time at which the subscription should be queried. If not provided the current time is used. */ + at?: Date | string + } + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionExpanded'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteSubscription: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + editSubscription: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['SubscriptionEdit'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subscription'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listSubscriptionAddons: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionAddon'][] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createSubscriptionAddon: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['SubscriptionAddonCreate'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionAddon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getSubscriptionAddon: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + subscriptionAddonId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionAddon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + updateSubscriptionAddon: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + subscriptionAddonId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['SubscriptionAddonUpdate'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionAddon'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + cancelSubscription: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': { + /** @description If not provided the subscription is canceled immediately. */ + timing?: components['schemas']['SubscriptionTiming'] + } + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subscription'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + changeSubscription: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['SubscriptionChange'] + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionChangeResponseBody'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + migrateSubscription: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': { + /** + * @description Timing configuration for the migration, when the migration should take effect. + * If not supported by the subscription, 400 will be returned. + * @default immediate + */ + timing?: components['schemas']['SubscriptionTiming'] + /** + * @description The version of the plan to migrate to. + * If not provided, the subscription will migrate to the latest version of the current plan. + */ + targetVersion?: number + /** + * @description The key of the phase to start the subscription in. + * If not provided, the subscription will start in the first phase of the plan. + */ + startingPhase?: string + /** + * Format: date-time + * @description The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + * @example 2023-01-01T01:01:01.001Z + */ + billingAnchor?: Date + } + } + } + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['SubscriptionChangeResponseBody'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + restoreSubscription: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subscription'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + unscheduleCancelation: { + parameters: { + query?: never + header?: never + path: { + subscriptionId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['Subscription'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionBadRequestErrorResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** + * @description The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['SubscriptionConflictErrorResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listCustomerEntitlementsV2: { + parameters: { + query?: { + includeDeleted?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** @description The order direction. */ + order?: components['parameters']['EntitlementOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['EntitlementOrderByOrdering.orderBy'] + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementV2PaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createCustomerEntitlementV2: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['EntitlementV2CreateInputs'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementV2'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomerEntitlementV2: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementV2'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + deleteCustomerEntitlementV2: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listCustomerEntitlementGrantsV2: { + parameters: { + query?: { + includeDeleted?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** + * @description Number of items to skip. + * + * Default is 0. + */ + offset?: components['parameters']['LimitOffset.offset'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + limit?: components['parameters']['LimitOffset.limit'] + /** @description The order direction. */ + order?: components['parameters']['GrantOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['GrantOrderByOrdering.orderBy'] + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['GrantV2PaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + createCustomerEntitlementGrantV2: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['EntitlementGrantCreateInputV2'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementGrantV2'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomerEntitlementHistoryV2: { + parameters: { + query: { + /** @description Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. */ + from?: Date | string + /** + * @description End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + * If not now then gets truncated to the granularity of the underlying meter. + */ + to?: Date | string + /** @description Windowsize */ + windowSize: components['schemas']['WindowSize'] + /** @description The timezone used when calculating the windows. */ + windowTimeZone?: string + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['WindowedBalanceHistory'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + overrideCustomerEntitlementV2: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: components['schemas']['ULIDOrExternalKey'] + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['EntitlementV2CreateInputs'] + } + } + responses: { + /** @description The request has succeeded and a new resource has been created as a result. */ + 201: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementV2'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description The request could not be completed due to a conflict with the current state of the target resource. */ + 409: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ConflictProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + resetCustomerEntitlementUsageV2: { + parameters: { + query?: never + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody: { + content: { + 'application/json': components['schemas']['ResetEntitlementUsageInput'] + } + } + responses: { + /** @description There is no content to send for this request, but the headers may be useful. */ + 204: { + headers: { + [name: string]: unknown + } + content?: never + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getCustomerEntitlementValueV2: { + parameters: { + query?: { + time?: Date | string + } + header?: never + path: { + customerIdOrKey: components['schemas']['ULIDOrExternalKey'] + entitlementIdOrFeatureKey: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementValueV2'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listEntitlementsV2: { + parameters: { + query?: { + /** + * @description Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + feature?: string[] + /** + * @description Filtering by multiple customers. + * + * Usage: `?customerKeys=customer-1&customerKeys=customer-3` + */ + customerKeys?: string[] + /** + * @description Filtering by multiple customers. + * + * Usage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9` + */ + customerIds?: string[] + /** + * @description Filtering by multiple entitlement types. + * + * Usage: `?entitlementType=metered&entitlementType=boolean` + */ + entitlementType?: components['schemas']['EntitlementType'][] + /** @description Exclude inactive entitlements in the response (those scheduled for later or earlier) */ + excludeInactive?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** + * @description Number of items to skip. + * + * Default is 0. + */ + offset?: components['parameters']['LimitOffset.offset'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + limit?: components['parameters']['LimitOffset.limit'] + /** @description The order direction. */ + order?: components['parameters']['EntitlementOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['EntitlementOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementV2PaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + getEntitlementByIdV2: { + parameters: { + query?: never + header?: never + path: { + entitlementId: string + } + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['EntitlementV2'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. */ + 404: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['NotFoundProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listEventsV2: { + parameters: { + query?: { + /** @description The cursor after which to start the pagination. */ + cursor?: components['parameters']['CursorPagination.cursor'] + /** @description The limit of the pagination. */ + limit?: components['parameters']['CursorPagination.limit'] + /** + * @description Client ID + * Useful to track progress of a query. + */ + clientId?: string + /** @description The filter for the events encoded as JSON string. */ + filter?: string + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['IngestedEventCursorPaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } + listGrantsV2: { + parameters: { + query?: { + /** + * @description Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + feature?: string[] + /** + * @description Filtering by multiple customers (either by ID or key). + * + * Usage: `?customer=customer-1&customer=customer-2` + */ + customer?: components['schemas']['ULIDOrExternalKey'][] + /** @description Include deleted */ + includeDeleted?: boolean + /** + * @description Page index. + * + * Default is 1. + */ + page?: components['parameters']['Pagination.page'] + /** + * @description The maximum number of items per page. + * + * Default is 100. + */ + pageSize?: components['parameters']['Pagination.pageSize'] + /** + * @description Number of items to skip. + * + * Default is 0. + */ + offset?: components['parameters']['LimitOffset.offset'] + /** + * @description Number of items to return. + * + * Default is 100. + */ + limit?: components['parameters']['LimitOffset.limit'] + /** @description The order direction. */ + order?: components['parameters']['GrantOrderByOrdering.order'] + /** @description The order by field. */ + orderBy?: components['parameters']['GrantOrderByOrdering.orderBy'] + } + header?: never + path?: never + cookie?: never + } + requestBody?: never + responses: { + /** @description The request has succeeded. */ + 200: { + headers: { + [name: string]: unknown + } + content: { + 'application/json': components['schemas']['GrantV2PaginatedResponse'] + } + } + /** @description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). */ + 400: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['BadRequestProblemResponse'] + } + } + /** @description The request has not been applied because it lacks valid authentication credentials for the target resource. */ + 401: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnauthorizedProblemResponse'] + } + } + /** @description The server understood the request but refuses to authorize it. */ + 403: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ForbiddenProblemResponse'] + } + } + /** @description One or more conditions given in the request header fields evaluated to false when tested on the server. */ + 412: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['PreconditionFailedProblemResponse'] + } + } + /** @description The server encountered an unexpected condition that prevented it from fulfilling the request. */ + 500: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['InternalServerErrorProblemResponse'] + } + } + /** @description The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. */ + 503: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['ServiceUnavailableProblemResponse'] + } + } + /** @description An unexpected error response. */ + default: { + headers: { + [name: string]: unknown + } + content: { + 'application/problem+json': components['schemas']['UnexpectedProblemResponse'] + } + } + } + } +} +type WithRequired = T & { + [P in K]-?: T[P] +} diff --git a/api/client/javascript/src/client/subjects.ts b/api/client/javascript/src/client/subjects.ts new file mode 100644 index 0000000000000000000000000000000000000000..2129e798ec0e4d89c3daf80c66b1fa00fdf16c55 --- /dev/null +++ b/api/client/javascript/src/client/subjects.ts @@ -0,0 +1,89 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { operations, paths, SubjectUpsert } from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Subjects + * @description Subjects are entities that consume resources you wish to meter. These can range from users, servers, and services to devices. The design of subjects is intentionally generic, enabling flexible application across various metering scenarios. Meters are aggregating events for each subject.. + */ +export class Subjects { + constructor(private client: Client) {} + + /** + * Upsert one or multiple subjects + * If the subject does not exist, it will be created, otherwise it will be updated. + * + * @param subjects - The subjects to upsert + * @param signal - An optional abort signal + * @returns The upserted subjects + */ + public async upsert( + subjects: SubjectUpsert | SubjectUpsert[], + options?: RequestOptions, + ) { + const resp = await this.client.POST('/api/v1/subjects', { + body: Array.isArray(subjects) ? subjects : [subjects], + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a subject by ID or key + * @param idOrKey - The ID or key of the subject + * @param signal - An optional abort signal + * @returns The subject + */ + public async get( + idOrKey: operations['getSubject']['parameters']['path']['subjectIdOrKey'], + options?: RequestOptions, + ) { + const resp = await this.client.GET('/api/v1/subjects/{subjectIdOrKey}', { + params: { + path: { + subjectIdOrKey: idOrKey, + }, + }, + ...options, + }) + + return transformResponse(resp) + } + + /** + * List subjects + * @param signal - An optional abort signal + * @returns The subjects + */ + public async list(options?: RequestOptions) { + const resp = await this.client.GET('/api/v1/subjects', { + ...options, + }) + + return transformResponse(resp) + } + + /** + * Delete a subject by ID or key + * @param idOrKey - The ID or key of the subject + * @param signal - An optional abort signal + * @returns The deleted subject + */ + public async delete( + idOrKey: operations['deleteSubject']['parameters']['path']['subjectIdOrKey'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE('/api/v1/subjects/{subjectIdOrKey}', { + params: { + path: { + subjectIdOrKey: idOrKey, + }, + }, + ...options, + }) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/subscription-addons.ts b/api/client/javascript/src/client/subscription-addons.ts new file mode 100644 index 0000000000000000000000000000000000000000..d93af654515f11ea35bb01473925081bb155c5b6 --- /dev/null +++ b/api/client/javascript/src/client/subscription-addons.ts @@ -0,0 +1,99 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { operations, paths } from './schemas.js' +import { transformResponse } from './utils.js' + +export class SubscriptionAddons { + constructor(private client: Client) {} + + /** + * Create a new subscription addon + * @param subscriptionId - The ID of the subscription + * @param addon - The subscription addon to create + * @param options - Optional request options + * @returns The created subscription addon + */ + public async create( + subscriptionId: string, + addon: operations['createSubscriptionAddon']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subscriptions/{subscriptionId}/addons', + { + body: addon, + params: { path: { subscriptionId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * List all addons of a subscription + * @param subscriptionId - The ID of the subscription + * @param options - Optional request options + * @returns A list of subscription addons + */ + public async list(subscriptionId: string, options?: RequestOptions) { + const resp = await this.client.GET( + '/api/v1/subscriptions/{subscriptionId}/addons', + { + params: { path: { subscriptionId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Get a subscription addon by id + * @param subscriptionId - The ID of the subscription + * @param subscriptionAddonId - The ID of the subscription addon + * @param options - Optional request options + * @returns The subscription addon + */ + public async get( + subscriptionId: string, + subscriptionAddonId: string, + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}', + { + params: { path: { subscriptionAddonId, subscriptionId } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Updates a subscription addon + * @param subscriptionId - The ID of the subscription + * @param subscriptionAddonId - The ID of the subscription addon to update + * @param addon - The subscription addon data to update + * @param options - Optional request options + * @returns The updated subscription addon + */ + public async update( + subscriptionId: string, + subscriptionAddonId: string, + addon: operations['updateSubscriptionAddon']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.PATCH( + '/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}', + { + body: addon, + params: { path: { subscriptionAddonId, subscriptionId } }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/subscriptions.ts b/api/client/javascript/src/client/subscriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd8d37bf453f67c7902ffcfdb2902c025f40da78 --- /dev/null +++ b/api/client/javascript/src/client/subscriptions.ts @@ -0,0 +1,196 @@ +import type { Client } from 'openapi-fetch' +import type { RequestOptions } from './common.js' +import type { + operations, + paths, + SubscriptionChange, + SubscriptionCreate, + SubscriptionEdit, +} from './schemas.js' +import { transformResponse } from './utils.js' + +/** + * Subscriptions + */ +export class Subscriptions { + constructor(private readonly client: Client) {} + + /** + * Create a subscription + * @param body - The subscription to create + * @param signal - An optional abort signal + * @returns The created subscription + */ + public async create(body: SubscriptionCreate, options?: RequestOptions) { + const resp = await this.client.POST('/api/v1/subscriptions', { + body, + ...options, + }) + + return transformResponse(resp) + } + + /** + * Get a subscription + * @param id - The subscription ID + * @param signal - An optional abort signal + * @returns The subscription + */ + public async get( + id: operations['getSubscription']['parameters']['path']['subscriptionId'], + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/subscriptions/{subscriptionId}', + { + params: { path: { subscriptionId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Edit a subscription + * @param id - The subscription ID + * @param body - The subscription to edit + * @param signal - An optional abort signal + * @returns The edited subscription + */ + public async edit( + id: operations['editSubscription']['parameters']['path']['subscriptionId'], + body: SubscriptionEdit, + options?: RequestOptions, + ) { + const resp = await this.client.PATCH( + '/api/v1/subscriptions/{subscriptionId}', + { + body, + params: { path: { subscriptionId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Cancel a subscription + * @param id - The subscription ID + * @param body - The subscription to cancel + * @param signal - An optional abort signal + * @returns The canceled subscription + */ + public async cancel( + id: operations['cancelSubscription']['parameters']['path']['subscriptionId'], + body: operations['cancelSubscription']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subscriptions/{subscriptionId}/cancel', + { + body, + params: { path: { subscriptionId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Change a subscription + * @description Closes a running subscription and starts a new one according to the specification. Can be used for upgrades, downgrades, and plan changes. + * @param id - The subscription ID + * @param body - The subscription to change + * @param signal - An optional abort signal + * @returns The changed subscription + */ + public async change( + id: operations['changeSubscription']['parameters']['path']['subscriptionId'], + body: SubscriptionChange, + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subscriptions/{subscriptionId}/change', + { + body, + params: { path: { subscriptionId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Migrate a subscription + * @description Migrates the subscripiton to the provided version of the current plan. + * @param id - The subscription ID + * @param body - The subscription to migrate + * @param signal - An optional abort signal + * @returns The migrated subscription + */ + public async migrate( + id: operations['migrateSubscription']['parameters']['path']['subscriptionId'], + body: operations['migrateSubscription']['requestBody']['content']['application/json'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subscriptions/{subscriptionId}/migrate', + { + body, + params: { path: { subscriptionId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Unschedule a cancelation + * @param id - The subscription ID + * @param signal - An optional abort signal + * @returns The unscheduled subscription + */ + public async unscheduleCancelation( + id: operations['unscheduleCancelation']['parameters']['path']['subscriptionId'], + options?: RequestOptions, + ) { + const resp = await this.client.POST( + '/api/v1/subscriptions/{subscriptionId}/unschedule-cancelation', + { + params: { path: { subscriptionId: id } }, + ...options, + }, + ) + + return transformResponse(resp) + } + + /** + * Delete subscription + * @description Deletes a subscription. Only scheduled subscriptions can be deleted. + * @param subscriptionId - The ID of the subscription to delete + * @param options - Optional request options + * @returns void or standard error response structure + */ + public async delete( + subscriptionId: operations['deleteSubscription']['parameters']['path']['subscriptionId'], + options?: RequestOptions, + ) { + const resp = await this.client.DELETE( + '/api/v1/subscriptions/{subscriptionId}', + { + params: { + path: { subscriptionId }, + }, + ...options, + }, + ) + + return transformResponse(resp) + } +} diff --git a/api/client/javascript/src/client/utils.ts b/api/client/javascript/src/client/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b90d92f270312b52f653fc57cc9959a76951588 --- /dev/null +++ b/api/client/javascript/src/client/utils.ts @@ -0,0 +1,90 @@ +import type { FetchResponse, ParseAsResponse } from 'openapi-fetch' +import type { + MediaType, + ResponseObjectMap, + SuccessResponse, +} from 'openapi-typescript-helpers' +import { HTTPError } from './common.js' + +/** + * Transform a response from the API + * @param resp - The response to transform + * @throws HTTPError if the response is an error + * @returns The transformed response + */ +export function transformResponse< + T extends Record, + Options, + Media extends MediaType, +>( + resp: FetchResponse, +): + | ParseAsResponse, Media>, Options> + | undefined + | never { + // Handle errors + if (resp.error || resp.response.status >= 400) { + throw HTTPError.fromResponse(resp) + } + + // Decode dates + resp.data = decodeDates(resp.data) + return resp.data +} + +const ISODateFormat = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?(?:[-+]\d{2}:?\d{2}|Z)?$/ + +export function isIsoDateString(value: unknown): value is string { + return typeof value === 'string' && ISODateFormat.test(value) +} + +export function decodeDates(data: T): T { + // if it's a date string, return a date + if (isIsoDateString(data)) { + return new Date(data) as T + } + + // if it's not an object or array, return it + if (data === null || data === undefined || typeof data !== 'object') { + return data + } + + // if it's an array, decode each element + if (Array.isArray(data)) { + return data.map((val) => decodeDates(val)) as T + } + + // if it's an object, decode each key + for (const [key, val] of Object.entries(data)) { + // @ts-expect-error we know this will give back the same type + data[key] = decodeDates(val) + } + + return data as T +} + +export function encodeDates(data: T): T { + // if it's a date, return a date string + if (data instanceof Date) { + return data.toISOString() as T + } + + // if it's not an object or array, return it + if (data === null || data === undefined || typeof data !== 'object') { + return data + } + + // if it's an array, encode each element + if (Array.isArray(data)) { + return data.map((val) => encodeDates(val)) as T + } + + // if it's an object, encode each key + for (const [key, val] of Object.entries(data)) { + // @ts-expect-error we know this will give back the same type + data[key] = encodeDates(val) + } + + return data as T +} diff --git a/api/client/javascript/src/portal/index.ts b/api/client/javascript/src/portal/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..de2aaf56c056b64a4d1e4309616f075e4273ba00 --- /dev/null +++ b/api/client/javascript/src/portal/index.ts @@ -0,0 +1,91 @@ +import type { Client, ClientOptions } from 'openapi-fetch' +import createClient, { createQuerySerializer } from 'openapi-fetch' +import type { RequestOptions } from '../client/common.js' +import type { operations, paths } from '../client/schemas.js' +import { encodeDates, transformResponse } from '../client/utils.js' + +/** + * Portal Config + */ +export type Config = Pick< + ClientOptions, + 'baseUrl' | 'headers' | 'fetch' | 'Request' | 'requestInitExt' +> & { + portalToken: string +} + +/** + * OpenMeter Portal Client + * Access to the customer portal. + */ +export class OpenMeter { + private client: Client + + constructor(config: Config) { + this.client = createClient({ + ...config, + headers: { + ...config.headers, + Authorization: `Bearer ${config.portalToken}`, + }, + querySerializer: (q) => + createQuerySerializer({ + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, + })(encodeDates(q)), + }) + } + + /** + * Query usage data for a meter by slug for customer portal. + * This endpoint is publicly exposable to consumers. + * @param meterSlug - The slug of the meter + * @param query - The query parameters + * @param signal - An optional abort signal + * @returns The meter data + */ + public async query( + meterSlug: string, + query?: { + /** @description Start date-time in RFC 3339 format. Inclusive. */ + from?: string | Date + /** @description End date-time in RFC 3339 format. Inclusive. */ + to?: string | Date + /** @description If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. */ + windowSize?: 'MINUTE' | 'HOUR' | 'DAY' + /** @description The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). If not specified, the UTC timezone will be used. */ + windowTimeZone?: string + /** @description Simple filter for group bys with exact match. */ + filterGroupBy?: Record + /** @description If not specified a single aggregate will be returned for each subject and time window. `subject` is a reserved group by value. */ + groupBy?: string[] + }, + options?: RequestOptions, + ) { + const resp = await this.client.GET( + '/api/v1/portal/meters/{meterSlug}/query', + { + headers: { + Accept: 'application/json', + }, + params: { + path: { + meterSlug, + }, + query, + }, + ...options, + }, + ) + + return transformResponse( + resp, + ) as operations['queryPortalMeter']['responses']['200']['content']['application/json'] + } +} diff --git a/api/client/javascript/src/react/context.tsx b/api/client/javascript/src/react/context.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4e5f0ee8df064d2625dd761a4d5fc588dbcb10d5 --- /dev/null +++ b/api/client/javascript/src/react/context.tsx @@ -0,0 +1,30 @@ +'use client' + +import { createContext, useContext } from 'react' +import type { OpenMeter } from '../portal/index.js' + +export * from '../portal/index.js' + +export const OpenMeterContext = createContext(null) + +export type OpenMeterProviderProps = { + children?: React.ReactNode + value: OpenMeter | null +} + +export function OpenMeterProvider({ children, value }: OpenMeterProviderProps) { + return ( + + {children} + + ) +} + +export function useOpenMeter() { + const context = useContext(OpenMeterContext) + if (typeof context === 'undefined') { + throw new Error('useOpenMeter must be used within a OpenMeterProvider') + } + + return context +} diff --git a/api/client/javascript/src/zod/index.ts b/api/client/javascript/src/zod/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e4458dc5ac34ed67d9db993aee6dc440a7c4bf1 --- /dev/null +++ b/api/client/javascript/src/zod/index.ts @@ -0,0 +1,19979 @@ +/** + * Generated by orval v8.15.0 🍺 + * Do not edit manually. + * OpenMeter Cloud API + * OpenMeter is a cloud native usage metering service. + * The OpenMeter API allows you to ingest events, query meter usage, and manage resources. + * OpenAPI spec version: 1.0.0 + */ +import * as zod from 'zod' + +/** + * List all add-ons. + * @summary List add-ons + */ +export const listAddonsQueryIncludeDeletedDefault = false +export const listAddonsQueryIdItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listAddonsQueryKeyItemMax = 64 + +export const listAddonsQueryKeyItemRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const listAddonsQueryCurrencyItemMin = 3 +export const listAddonsQueryCurrencyItemMax = 3 + +export const listAddonsQueryCurrencyItemRegExp = /^[A-Z]{3}$/ +export const listAddonsQueryPageDefault = 1 + +export const listAddonsQueryPageSizeDefault = 100 +export const listAddonsQueryPageSizeMax = 1000 + +export const listAddonsQueryOrderDefault = 'ASC' + +export const ListAddonsQueryParams = zod.object({ + currency: zod + .array( + zod.coerce + .string() + .min(listAddonsQueryCurrencyItemMin) + .max(listAddonsQueryCurrencyItemMax) + .regex(listAddonsQueryCurrencyItemRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ), + ) + .optional() + .describe('Filter by addon.currency attribute'), + id: zod + .array( + zod.coerce + .string() + .regex(listAddonsQueryIdItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Filter by addon.id attribute'), + includeDeleted: zod.coerce + .boolean() + .default(listAddonsQueryIncludeDeletedDefault) + .describe( + 'Include deleted add-ons in response.\n\nUsage: `?includeDeleted=true`', + ), + key: zod + .array( + zod.coerce + .string() + .min(1) + .max(listAddonsQueryKeyItemMax) + .regex(listAddonsQueryKeyItemRegExp) + .describe( + 'A key is a unique string that is used to identify a resource.', + ), + ) + .optional() + .describe('Filter by addon.key attribute'), + keyVersion: zod + .record(zod.string(), zod.array(zod.coerce.number())) + .optional() + .describe('Filter by addon.key and addon.version attributes'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listAddonsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'key', 'version', 'created_at', 'updated_at']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listAddonsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listAddonsQueryPageSizeMax) + .default(listAddonsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + status: zod + .array( + zod + .enum(['draft', 'active', 'archived']) + .describe( + 'The status of the add-on defined by the effectiveFrom and effectiveTo properties.', + ), + ) + .optional() + .describe( + 'Only return add-ons with the given status.\n\nUsage:\n- `?status=active`: return only the currently active add-ons\n- `?status=draft`: return only the draft add-ons\n- `?status=archived`: return only the archived add-ons', + ), +}) + +/** + * Create a new add-on. + * @summary Create an add-on + */ +export const createAddonBodyNameMax = 256 + +export const createAddonBodyDescriptionMax = 1024 + +export const createAddonBodyKeyMax = 64 + +export const createAddonBodyKeyRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createAddonBodyCurrencyOneMin = 3 +export const createAddonBodyCurrencyOneMax = 3 + +export const createAddonBodyCurrencyOneRegExp = /^[A-Z]{3}$/ +export const createAddonBodyCurrencyDefault = 'USD' +export const createAddonBodyRateCardsItemOneKeyMax = 64 + +export const createAddonBodyRateCardsItemOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createAddonBodyRateCardsItemOneNameMax = 256 + +export const createAddonBodyRateCardsItemOneDescriptionMax = 1024 + +export const createAddonBodyRateCardsItemOneFeatureKeyMax = 64 + +export const createAddonBodyRateCardsItemOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const createAddonBodyRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const createAddonBodyRateCardsItemOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createAddonBodyRateCardsItemOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createAddonBodyRateCardsItemOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemOnePriceOnePaymentTermDefault = + 'in_advance' +export const createAddonBodyRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoKeyMax = 64 + +export const createAddonBodyRateCardsItemTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createAddonBodyRateCardsItemTwoNameMax = 256 + +export const createAddonBodyRateCardsItemTwoDescriptionMax = 1024 + +export const createAddonBodyRateCardsItemTwoFeatureKeyMax = 64 + +export const createAddonBodyRateCardsItemTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const createAddonBodyRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const createAddonBodyRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createAddonBodyRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createAddonBodyRateCardsItemTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const createAddonBodyRateCardsItemTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const createAddonBodyRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFourMultiplierDefault = '1' +export const createAddonBodyRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createAddonBodyRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const CreateAddonBody = zod + .object({ + currency: zod.coerce + .string() + .min(createAddonBodyCurrencyOneMin) + .max(createAddonBodyCurrencyOneMax) + .regex(createAddonBodyCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .default(createAddonBodyCurrencyDefault) + .describe('The currency code of the add-on.'), + description: zod.coerce + .string() + .max(createAddonBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + instanceType: zod + .enum(['single', 'multiple']) + .describe( + 'The instanceType of the add-on.\nSingle instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once.', + ) + .describe( + 'The instanceType of the add-ons. Can be "single" or "multiple".', + ), + key: zod.coerce + .string() + .min(1) + .max(createAddonBodyKeyMax) + .regex(createAddonBodyKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createAddonBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + rateCards: zod + .array( + zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max(createAddonBodyRateCardsItemOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + createAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createAddonBodyRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createAddonBodyRateCardsItemOneFeatureKeyMax) + .regex(createAddonBodyRateCardsItemOneFeatureKeyRegExp) + .optional() + .describe('The feature the customer is entitled to use.'), + key: zod.coerce + .string() + .min(1) + .max(createAddonBodyRateCardsItemOneKeyMax) + .regex(createAddonBodyRateCardsItemOneKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createAddonBodyRateCardsItemOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createAddonBodyRateCardsItemOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod.enum(['flat']).describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe('The billing cadence of the rate card.'), + description: zod.coerce + .string() + .max(createAddonBodyRateCardsItemTwoDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + createAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createAddonBodyRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createAddonBodyRateCardsItemTwoFeatureKeyMax) + .regex(createAddonBodyRateCardsItemTwoFeatureKeyRegExp) + .optional() + .describe('The feature the customer is entitled to use.'), + key: zod.coerce + .string() + .min(1) + .max(createAddonBodyRateCardsItemTwoKeyMax) + .regex(createAddonBodyRateCardsItemTwoKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createAddonBodyRateCardsItemTwoNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createAddonBodyRateCardsItemTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + createAddonBodyRateCardsItemTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createAddonBodyRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + ) + .describe('The rate cards of the add-on.'), + }) + .describe('Resource create operation model.') + +/** + * Update add-on by id. + * @summary Update add-on + */ +export const updateAddonPathAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateAddonParams = zod.object({ + addonId: zod.coerce.string().regex(updateAddonPathAddonIdRegExp), +}) + +export const updateAddonBodyNameMax = 256 + +export const updateAddonBodyDescriptionMax = 1024 + +export const updateAddonBodyRateCardsItemOneKeyMax = 64 + +export const updateAddonBodyRateCardsItemOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updateAddonBodyRateCardsItemOneNameMax = 256 + +export const updateAddonBodyRateCardsItemOneDescriptionMax = 1024 + +export const updateAddonBodyRateCardsItemOneFeatureKeyMax = 64 + +export const updateAddonBodyRateCardsItemOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const updateAddonBodyRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const updateAddonBodyRateCardsItemOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updateAddonBodyRateCardsItemOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateAddonBodyRateCardsItemOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemOnePriceOnePaymentTermDefault = + 'in_advance' +export const updateAddonBodyRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoKeyMax = 64 + +export const updateAddonBodyRateCardsItemTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updateAddonBodyRateCardsItemTwoNameMax = 256 + +export const updateAddonBodyRateCardsItemTwoDescriptionMax = 1024 + +export const updateAddonBodyRateCardsItemTwoFeatureKeyMax = 64 + +export const updateAddonBodyRateCardsItemTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const updateAddonBodyRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updateAddonBodyRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateAddonBodyRateCardsItemTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const updateAddonBodyRateCardsItemTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const updateAddonBodyRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFourMultiplierDefault = '1' +export const updateAddonBodyRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateAddonBodyRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const UpdateAddonBody = zod + .object({ + description: zod.coerce + .string() + .max(updateAddonBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + instanceType: zod + .enum(['single', 'multiple']) + .describe( + 'The instanceType of the add-on.\nSingle instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once.', + ) + .describe( + 'The instanceType of the add-ons. Can be "single" or "multiple".', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateAddonBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + rateCards: zod + .array( + zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max(updateAddonBodyRateCardsItemOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + updateAddonBodyRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + updateAddonBodyRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(updateAddonBodyRateCardsItemOneFeatureKeyMax) + .regex(updateAddonBodyRateCardsItemOneFeatureKeyRegExp) + .optional() + .describe('The feature the customer is entitled to use.'), + key: zod.coerce + .string() + .min(1) + .max(updateAddonBodyRateCardsItemOneKeyMax) + .regex(updateAddonBodyRateCardsItemOneKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateAddonBodyRateCardsItemOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + updateAddonBodyRateCardsItemOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod.enum(['flat']).describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe('The billing cadence of the rate card.'), + description: zod.coerce + .string() + .max(updateAddonBodyRateCardsItemTwoDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + updateAddonBodyRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(updateAddonBodyRateCardsItemTwoFeatureKeyMax) + .regex(updateAddonBodyRateCardsItemTwoFeatureKeyRegExp) + .optional() + .describe('The feature the customer is entitled to use.'), + key: zod.coerce + .string() + .min(1) + .max(updateAddonBodyRateCardsItemTwoKeyMax) + .regex(updateAddonBodyRateCardsItemTwoKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateAddonBodyRateCardsItemTwoNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + updateAddonBodyRateCardsItemTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + updateAddonBodyRateCardsItemTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updateAddonBodyRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + ) + .describe('The rate cards of the add-on.'), + }) + .describe('Resource update operation model.') + +/** + * Get add-on by id or key. The latest published version is returned if latter is used. + * @summary Get add-on + */ +export const getAddonPathAddonIdMax = 64 + +export const getAddonPathAddonIdRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetAddonParams = zod.object({ + addonId: zod.coerce + .string() + .min(1) + .max(getAddonPathAddonIdMax) + .regex(getAddonPathAddonIdRegExp), +}) + +export const getAddonQueryIncludeLatestDefault = false + +export const GetAddonQueryParams = zod.object({ + includeLatest: zod.coerce + .boolean() + .default(getAddonQueryIncludeLatestDefault) + .describe( + 'Include latest version of the add-on instead of the version in active state.\n\nUsage: `?includeLatest=true`', + ), +}) + +/** + * Soft delete add-on by id. + * + * Once a add-on is deleted it cannot be undeleted. + * @summary Delete add-on + */ +export const deleteAddonPathAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteAddonParams = zod.object({ + addonId: zod.coerce.string().regex(deleteAddonPathAddonIdRegExp), +}) + +/** + * Archive a add-on version. + * @summary Archive add-on version + */ +export const archiveAddonPathAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ArchiveAddonParams = zod.object({ + addonId: zod.coerce.string().regex(archiveAddonPathAddonIdRegExp), +}) + +/** + * Publish a add-on version. + * @summary Publish add-on + */ +export const publishAddonPathAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const PublishAddonParams = zod.object({ + addonId: zod.coerce.string().regex(publishAddonPathAddonIdRegExp), +}) + +/** + * List apps. + * @summary List apps + */ +export const listAppsQueryPageDefault = 1 + +export const listAppsQueryPageSizeDefault = 100 +export const listAppsQueryPageSizeMax = 1000 + +export const ListAppsQueryParams = zod.object({ + page: zod.coerce + .number() + .min(1) + .default(listAppsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listAppsQueryPageSizeMax) + .default(listAppsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * @summary Submit draft synchronization results + */ +export const appCustomInvoicingDraftSynchronizedPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const AppCustomInvoicingDraftSynchronizedParams = zod.object({ + invoiceId: zod.coerce + .string() + .regex(appCustomInvoicingDraftSynchronizedPathInvoiceIdRegExp), +}) + +export const appCustomInvoicingDraftSynchronizedBodyInvoicingOneInvoiceNumberOneMax = 256 + +export const appCustomInvoicingDraftSynchronizedBodyInvoicingOneLineExternalIdsItemLineIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const appCustomInvoicingDraftSynchronizedBodyInvoicingOneLineDiscountExternalIdsItemLineDiscountIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const AppCustomInvoicingDraftSynchronizedBody = zod + .object({ + invoicing: zod + .object({ + externalId: zod.coerce + .string() + .optional() + .describe( + "If set the invoice's invoicing external ID will be set to this value.", + ), + invoiceNumber: zod.coerce + .string() + .min(1) + .max( + appCustomInvoicingDraftSynchronizedBodyInvoicingOneInvoiceNumberOneMax, + ) + .describe( + 'InvoiceNumber is a unique identifier for the invoice, generated by the\ninvoicing app.\n\nThe uniqueness depends on a lot of factors:\n- app setting (unique per app or unique per customer)\n- multiple app scenarios (multiple apps generating invoices with the same prefix)', + ) + .optional() + .describe("If set the invoice's number will be set to this value."), + lineDiscountExternalIds: zod + .array( + zod + .object({ + externalId: zod.coerce + .string() + .describe( + "The external ID (e.g. custom invoicing system's ID).", + ), + lineDiscountId: zod.coerce + .string() + .regex( + appCustomInvoicingDraftSynchronizedBodyInvoicingOneLineDiscountExternalIdsItemLineDiscountIdRegExp, + ) + .describe('The line discount ID.'), + }) + .describe('Mapping between line discounts and external IDs.'), + ) + .optional() + .describe( + "If set the invoice's line discount external IDs will be set to this value.\n\nThis can be used to reference the external system's entities in the\ninvoice.", + ), + lineExternalIds: zod + .array( + zod + .object({ + externalId: zod.coerce + .string() + .describe( + "The external ID (e.g. custom invoicing system's ID).", + ), + lineId: zod.coerce + .string() + .regex( + appCustomInvoicingDraftSynchronizedBodyInvoicingOneLineExternalIdsItemLineIdRegExp, + ) + .describe('The line ID.'), + }) + .describe('Mapping between lines and external IDs.'), + ) + .optional() + .describe( + "If set the invoice's line external IDs will be set to this value.\n\nThis can be used to reference the external system's entities in the\ninvoice.", + ), + }) + .describe( + "Information to synchronize the invoice.\n\nCan be used to store external app's IDs on the invoice or lines.", + ) + .optional() + .describe('The result of the synchronization.'), + }) + .describe('Information to finalize the draft details of an invoice.') + +/** + * @summary Submit issuing synchronization results + */ +export const appCustomInvoicingIssuingSynchronizedPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const AppCustomInvoicingIssuingSynchronizedParams = zod.object({ + invoiceId: zod.coerce + .string() + .regex(appCustomInvoicingIssuingSynchronizedPathInvoiceIdRegExp), +}) + +export const appCustomInvoicingIssuingSynchronizedBodyInvoicingOneInvoiceNumberOneMax = 256 + +export const AppCustomInvoicingIssuingSynchronizedBody = zod + .object({ + invoicing: zod + .object({ + invoiceNumber: zod.coerce + .string() + .min(1) + .max( + appCustomInvoicingIssuingSynchronizedBodyInvoicingOneInvoiceNumberOneMax, + ) + .describe( + 'InvoiceNumber is a unique identifier for the invoice, generated by the\ninvoicing app.\n\nThe uniqueness depends on a lot of factors:\n- app setting (unique per app or unique per customer)\n- multiple app scenarios (multiple apps generating invoices with the same prefix)', + ) + .optional() + .describe("If set the invoice's number will be set to this value."), + sentToCustomerAt: zod.coerce + .date() + .optional() + .describe( + "If set the invoice's sent to customer at will be set to this value.", + ), + }) + .describe('Information to finalize the invoicing details of an invoice.') + .optional() + .describe('The result of the synchronization.'), + payment: zod + .object({ + externalId: zod.coerce + .string() + .optional() + .describe( + "If set the invoice's payment external ID will be set to this value.", + ), + }) + .describe('Information to finalize the payment details of an invoice.') + .optional() + .describe('The result of the payment synchronization.'), + }) + .describe( + 'Information to finalize the invoice.\n\nIf invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix).', + ) + +/** + * @summary Update payment status + */ +export const appCustomInvoicingUpdatePaymentStatusPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const AppCustomInvoicingUpdatePaymentStatusParams = zod.object({ + invoiceId: zod.coerce + .string() + .regex(appCustomInvoicingUpdatePaymentStatusPathInvoiceIdRegExp), +}) + +export const AppCustomInvoicingUpdatePaymentStatusBody = zod + .object({ + trigger: zod + .enum([ + 'paid', + 'payment_failed', + 'payment_uncollectible', + 'payment_overdue', + 'action_required', + 'void', + ]) + .describe('Payment trigger to execute on a finalized invoice.') + .describe('The trigger to be executed on the invoice.'), + }) + .describe( + "Update payment status request.\n\nCan be used to manipulate invoice's payment status (when custominvoicing app is being used).", + ) + +/** + * Get the app. + * @summary Get app + */ +export const getAppPathIdRegExp = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetAppParams = zod.object({ + id: zod.coerce.string().regex(getAppPathIdRegExp), +}) + +/** + * Update an app. + * @summary Update app + */ +export const updateAppPathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateAppParams = zod.object({ + id: zod.coerce.string().regex(updateAppPathIdRegExp), +}) + +export const updateAppBodyOneNameMax = 256 + +export const updateAppBodyOneDescriptionMax = 1024 + +export const updateAppBodyTwoNameMax = 256 + +export const updateAppBodyTwoDescriptionMax = 1024 + +export const updateAppBodyThreeNameMax = 256 + +export const updateAppBodyThreeDescriptionMax = 1024 + +export const UpdateAppBody = zod + .union([ + zod + .object({ + description: zod.coerce + .string() + .max(updateAppBodyOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateAppBodyOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + secretAPIKey: zod.coerce + .string() + .optional() + .describe('The Stripe API key.'), + type: zod.enum(['stripe']).describe("The app's type is Stripe."), + }) + .describe('Resource update operation model.'), + zod + .object({ + description: zod.coerce + .string() + .max(updateAppBodyTwoDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateAppBodyTwoNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + type: zod.enum(['sandbox']).describe("The app's type is Sandbox."), + }) + .describe('Resource update operation model.'), + zod + .object({ + description: zod.coerce + .string() + .max(updateAppBodyThreeDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + enableDraftSyncHook: zod.coerce + .boolean() + .describe( + 'Enable draft.sync hook.\n\nIf the hook is not enabled, the invoice will be progressed to the next state automatically.', + ), + enableIssuingSyncHook: zod.coerce + .boolean() + .describe( + 'Enable issuing.sync hook.\n\nIf the hook is not enabled, the invoice will be progressed to the next state automatically.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateAppBodyThreeNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + type: zod + .enum(['custom_invoicing']) + .describe("The app's type is CustomInvoicing."), + }) + .describe('Resource update operation model.'), + ]) + .describe('App ReplaceUpdate Model') + +/** + * Uninstall an app. + * @summary Uninstall app + */ +export const uninstallAppPathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UninstallAppParams = zod.object({ + id: zod.coerce.string().regex(uninstallAppPathIdRegExp), +}) + +/** + * Update the Stripe API key. + * + * ⚠️ __Deprecated__: Use [`PUT /api/v1/apps/{id}`](#tag/apps/put/api/v1/apps/{id}) instead. + * @deprecated + * @summary Update Stripe API key + */ +export const updateStripeAPIKeyPathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateStripeAPIKeyParams = zod.object({ + id: zod.coerce.string().regex(updateStripeAPIKeyPathIdRegExp), +}) + +export const UpdateStripeAPIKeyBody = zod + .object({ + secretAPIKey: zod.coerce.string(), + }) + .describe( + 'The Stripe API key input.\nUsed to authenticate with the Stripe API.', + ) + +/** + * Handle stripe webhooks for apps. + * @summary Stripe webhook + */ +export const appStripeWebhookPathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const AppStripeWebhookParams = zod.object({ + id: zod.coerce.string().regex(appStripeWebhookPathIdRegExp), +}) + +export const AppStripeWebhookBody = zod + .object({ + created: zod.coerce.number().describe('The event created timestamp.'), + data: zod + .object({ + object: zod.unknown(), + }) + .describe('The event data.'), + id: zod.coerce.string().describe('The event ID.'), + livemode: zod.coerce.boolean().describe('Live mode.'), + type: zod.coerce.string().describe('The event type.'), + }) + .describe('Stripe webhook event.') + +/** + * List customer overrides using the specified filters. + * + * The response will include the customer override values and the merged billing profile values. + * + * If the includeAllCustomers is set to true, the list contains all customers. This mode is + * useful for getting the current effective billing workflow settings for all users regardless + * if they have customer orverrides or not. + * @summary List customer overrides + */ +export const listBillingProfileCustomerOverridesQueryBillingProfileItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listBillingProfileCustomerOverridesQueryIncludeAllCustomersDefault = true +export const listBillingProfileCustomerOverridesQueryCustomerIdItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listBillingProfileCustomerOverridesQueryOrderDefault = 'ASC' +export const listBillingProfileCustomerOverridesQueryPageDefault = 1 + +export const listBillingProfileCustomerOverridesQueryPageSizeDefault = 100 +export const listBillingProfileCustomerOverridesQueryPageSizeMax = 1000 + +export const ListBillingProfileCustomerOverridesQueryParams = zod.object({ + billingProfile: zod + .array( + zod.coerce + .string() + .regex(listBillingProfileCustomerOverridesQueryBillingProfileItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Filter by billing profile.'), + customerId: zod + .array( + zod.coerce + .string() + .regex(listBillingProfileCustomerOverridesQueryCustomerIdItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Filter by customer id.'), + customerKey: zod.coerce + .string() + .optional() + .describe('Filter by customer key'), + customerName: zod.coerce + .string() + .optional() + .describe('Filter by customer name.'), + customerPrimaryEmail: zod.coerce + .string() + .optional() + .describe('Filter by customer primary email'), + customersWithoutPinnedProfile: zod.coerce + .boolean() + .optional() + .describe( + 'Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true.', + ), + expand: zod + .array( + zod + .enum(['apps', 'customer']) + .describe( + 'CustomerOverrideExpand specifies the parts of the profile to expand.', + ), + ) + .optional() + .describe('Expand the response with additional details.'), + includeAllCustomers: zod.coerce + .boolean() + .default(listBillingProfileCustomerOverridesQueryIncludeAllCustomersDefault) + .describe( + 'Include customers without customer overrides.\n\nIf set to false only the customers specifically associated with a billing profile will be returned.\n\nIf set to true, in case of the default billing profile, all customers will be returned.', + ), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listBillingProfileCustomerOverridesQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum([ + 'customerId', + 'customerName', + 'customerKey', + 'customerPrimaryEmail', + 'customerCreatedAt', + ]) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listBillingProfileCustomerOverridesQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listBillingProfileCustomerOverridesQueryPageSizeMax) + .default(listBillingProfileCustomerOverridesQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * The customer override can be used to pin a given customer to a billing profile + * different from the default one. + * + * This can be used to test the effect of different billing profiles before making them + * the default ones or have different workflow settings for example for enterprise customers. + * @summary Create a new or update a customer override + */ +export const upsertBillingProfileCustomerOverridePathCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpsertBillingProfileCustomerOverrideParams = zod.object({ + customerId: zod.coerce + .string() + .regex(upsertBillingProfileCustomerOverridePathCustomerIdRegExp), +}) + +export const upsertBillingProfileCustomerOverrideBodyBillingProfileIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpsertBillingProfileCustomerOverrideBody = zod + .object({ + billingProfileId: zod.coerce + .string() + .regex(upsertBillingProfileCustomerOverrideBodyBillingProfileIdRegExp) + .optional() + .describe( + 'The billing profile this override is associated with.\n\nIf not provided, the default billing profile is chosen if available.', + ), + }) + .describe( + 'Payload for creating a new or updating an existing customer override.', + ) + +/** + * Get a customer override by customer id. + * + * The response will include the customer override values and the merged billing profile values. + * + * If the customer override is not found, the default billing profile's values are returned. This behavior + * allows for getting a merged profile regardless of the customer override existence. + * @summary Get a customer override + */ +export const getBillingProfileCustomerOverridePathCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetBillingProfileCustomerOverrideParams = zod.object({ + customerId: zod.coerce + .string() + .regex(getBillingProfileCustomerOverridePathCustomerIdRegExp), +}) + +export const GetBillingProfileCustomerOverrideQueryParams = zod.object({ + expand: zod + .array( + zod + .enum(['apps', 'customer']) + .describe( + 'CustomerOverrideExpand specifies the parts of the profile to expand.', + ), + ) + .optional(), +}) + +/** + * Delete a customer override by customer id. + * + * This will remove the customer override and the customer will be subject to the default + * billing profile's settings again. + * @summary Delete a customer override + */ +export const deleteBillingProfileCustomerOverridePathCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteBillingProfileCustomerOverrideParams = zod.object({ + customerId: zod.coerce + .string() + .regex(deleteBillingProfileCustomerOverridePathCustomerIdRegExp), +}) + +/** + * Create a new pending line item (charge). + * + * This call is used to create a new pending line item for the customer if required a new + * gathering invoice will be created. + * + * A new invoice will be created if: + * - there is no invoice in gathering state + * - the currency of the line item doesn't match the currency of any invoices in gathering state + * @summary Create pending line items + */ +export const createPendingInvoiceLinePathCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreatePendingInvoiceLineParams = zod.object({ + customerId: zod.coerce + .string() + .regex(createPendingInvoiceLinePathCustomerIdRegExp), +}) + +export const createPendingInvoiceLineBodyCurrencyOneMin = 3 +export const createPendingInvoiceLineBodyCurrencyOneMax = 3 + +export const createPendingInvoiceLineBodyCurrencyOneRegExp = /^[A-Z]{3}$/ +export const createPendingInvoiceLineBodyLinesItemNameMax = 256 + +export const createPendingInvoiceLineBodyLinesItemDescriptionMax = 1024 + +export const createPendingInvoiceLineBodyLinesItemTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createPendingInvoiceLineBodyLinesItemTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneOnePaymentTermDefault = + 'in_advance' +export const createPendingInvoiceLineBodyLinesItemPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const createPendingInvoiceLineBodyLinesItemPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFourMultiplierDefault = + '1' +export const createPendingInvoiceLineBodyLinesItemPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemFeatureKeyMax = 64 + +export const createPendingInvoiceLineBodyLinesItemFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOneFeatureKeyMax = 64 + +export const createPendingInvoiceLineBodyLinesItemRateCardOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneOnePaymentTermDefault = + 'in_advance' +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMultiplierDefault = + '1' +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOneDiscountsOnePercentageOneCorrelationIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPendingInvoiceLineBodyLinesItemRateCardOneDiscountsOneUsageOneCorrelationIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreatePendingInvoiceLineBody = zod + .object({ + currency: zod.coerce + .string() + .min(createPendingInvoiceLineBodyCurrencyOneMin) + .max(createPendingInvoiceLineBodyCurrencyOneMax) + .regex(createPendingInvoiceLineBodyCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .describe('The currency of the lines to be created.'), + lines: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max(createPendingInvoiceLineBodyLinesItemDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createPendingInvoiceLineBodyLinesItemFeatureKeyMax) + .regex(createPendingInvoiceLineBodyLinesItemFeatureKeyRegExp) + .optional() + .describe('The feature that the usage is based on.'), + invoiceAt: zod.coerce + .date() + .describe('The time this line item should be invoiced.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createPendingInvoiceLineBodyLinesItemNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + period: zod + .object({ + from: zod.coerce.date().describe('Period start time.'), + to: zod.coerce.date().describe('Period end time.'), + }) + .describe('A period with a start and end time.') + .describe( + 'Period of the line item applies to for revenue recognition pruposes.\n\nBilling always treats periods as start being inclusive and end being exclusive.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createPendingInvoiceLineBodyLinesItemPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod.enum(['flat']).describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod.enum(['unit']).describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + createPendingInvoiceLineBodyLinesItemPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .optional() + .describe('Price of the usage-based item being sold.'), + rateCard: zod + .object({ + discounts: zod + .object({ + percentage: zod + .object({ + correlationId: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOneDiscountsOnePercentageOneCorrelationIdRegExp, + ) + .optional() + .describe( + 'Correlation ID for the discount.\n\nThis is used to link discounts across different invoices (progressive billing use case).\n\nIf not provided, the invoicing engine will auto-generate one. When editing an invoice line,\nplease make sure to keep the same correlation ID of the discount or in progressive billing\nsetups the discount amounts might be incorrect.', + ), + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('A percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + correlationId: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOneDiscountsOneUsageOneCorrelationIdRegExp, + ) + .optional() + .describe( + 'Correlation ID for the discount.\n\nThis is used to link discounts across different invoices (progressive billing use case).\n\nIf not provided, the invoicing engine will auto-generate one. When editing an invoice line,\nplease make sure to keep the same correlation ID of the discount or in progressive billing\nsetups the discount amounts might be incorrect.', + ), + quantity: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe('A usage discount.') + .optional() + .describe('The usage discount.'), + }) + .describe('A discount by type.') + .optional() + .describe('The discounts that are applied to the line.'), + featureKey: zod.coerce + .string() + .min(1) + .max( + createPendingInvoiceLineBodyLinesItemRateCardOneFeatureKeyMax, + ) + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOneFeatureKeyRegExp, + ) + .optional() + .describe('The feature the customer is entitled to use.'), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOnePriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemRateCardOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + }) + .describe( + 'InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line.', + ) + .optional() + .describe( + 'The rate card that is used for this line.\n\nThe rate card captures the intent of the price and discounts for the usage-based item.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createPendingInvoiceLineBodyLinesItemTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'Tax config specify the tax configuration for this line.', + ), + }) + .describe( + 'InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage.', + ), + ) + .min(1) + .describe('The lines to be created.'), + }) + .describe( + 'InvoicePendingLineCreate represents the create model for a pending invoice line.', + ) + +/** + * Simulate an invoice for a customer. + * + * This call will simulate an invoice for a customer based on the pending line items. + * + * The call will return the total amount of the invoice and the line items that will be included in the invoice. + * @summary Simulate an invoice for a customer + */ +export const simulateInvoicePathCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const SimulateInvoiceParams = zod.object({ + customerId: zod.coerce.string().regex(simulateInvoicePathCustomerIdRegExp), +}) + +export const simulateInvoiceBodyNumberOneMax = 256 + +export const simulateInvoiceBodyCurrencyOneMin = 3 +export const simulateInvoiceBodyCurrencyOneMax = 3 + +export const simulateInvoiceBodyCurrencyOneRegExp = /^[A-Z]{3}$/ +export const simulateInvoiceBodyLinesItemNameMax = 256 + +export const simulateInvoiceBodyLinesItemDescriptionMax = 1024 + +export const simulateInvoiceBodyLinesItemTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const simulateInvoiceBodyLinesItemTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const simulateInvoiceBodyLinesItemPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneOnePaymentTermDefault = + 'in_advance' +export const simulateInvoiceBodyLinesItemPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const simulateInvoiceBodyLinesItemPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFourMultiplierDefault = '1' +export const simulateInvoiceBodyLinesItemPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemFeatureKeyMax = 64 + +export const simulateInvoiceBodyLinesItemFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const simulateInvoiceBodyLinesItemRateCardOneFeatureKeyMax = 64 + +export const simulateInvoiceBodyLinesItemRateCardOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const simulateInvoiceBodyLinesItemRateCardOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const simulateInvoiceBodyLinesItemRateCardOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneOnePaymentTermDefault = + 'in_advance' +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierDefault = + '1' +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOneDiscountsOnePercentageOneCorrelationIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const simulateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneCorrelationIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const simulateInvoiceBodyLinesItemQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemPreLinePeriodQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const simulateInvoiceBodyLinesItemIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const SimulateInvoiceBody = zod + .object({ + currency: zod.coerce + .string() + .min(simulateInvoiceBodyCurrencyOneMin) + .max(simulateInvoiceBodyCurrencyOneMax) + .regex(simulateInvoiceBodyCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .describe( + 'Currency for all invoice line items.\n\nMulti currency invoices are not supported yet.', + ), + lines: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max(simulateInvoiceBodyLinesItemDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(simulateInvoiceBodyLinesItemFeatureKeyMax) + .regex(simulateInvoiceBodyLinesItemFeatureKeyRegExp) + .optional() + .describe('The feature that the usage is based on.'), + id: zod.coerce + .string() + .regex(simulateInvoiceBodyLinesItemIdRegExp) + .optional() + .describe( + 'ID of the line. If not specified it will be auto-generated.\n\nWhen discounts are specified, this must be provided, so that the discount can reference it.', + ), + invoiceAt: zod.coerce + .date() + .describe('The time this line item should be invoiced.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(simulateInvoiceBodyLinesItemNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + period: zod + .object({ + from: zod.coerce.date().describe('Period start time.'), + to: zod.coerce.date().describe('Period end time.'), + }) + .describe('A period with a start and end time.') + .describe( + 'Period of the line item applies to for revenue recognition pruposes.\n\nBilling always treats periods as start being inclusive and end being exclusive.', + ), + preLinePeriodQuantity: zod.coerce + .string() + .regex(simulateInvoiceBodyLinesItemPreLinePeriodQuantityOneRegExp) + .describe('Numeric represents an arbitrary precision number.') + .optional() + .describe( + "The quantity of the item used before this line's period, if the line is billed progressively.", + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + simulateInvoiceBodyLinesItemPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod.enum(['flat']).describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod.enum(['unit']).describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + simulateInvoiceBodyLinesItemPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .optional() + .describe('Price of the usage-based item being sold.'), + quantity: zod.coerce + .string() + .regex(simulateInvoiceBodyLinesItemQuantityOneRegExp) + .describe('Numeric represents an arbitrary precision number.') + .describe('The quantity of the item being sold.'), + rateCard: zod + .object({ + discounts: zod + .object({ + percentage: zod + .object({ + correlationId: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOneDiscountsOnePercentageOneCorrelationIdRegExp, + ) + .optional() + .describe( + 'Correlation ID for the discount.\n\nThis is used to link discounts across different invoices (progressive billing use case).\n\nIf not provided, the invoicing engine will auto-generate one. When editing an invoice line,\nplease make sure to keep the same correlation ID of the discount or in progressive billing\nsetups the discount amounts might be incorrect.', + ), + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('A percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + correlationId: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneCorrelationIdRegExp, + ) + .optional() + .describe( + 'Correlation ID for the discount.\n\nThis is used to link discounts across different invoices (progressive billing use case).\n\nIf not provided, the invoicing engine will auto-generate one. When editing an invoice line,\nplease make sure to keep the same correlation ID of the discount or in progressive billing\nsetups the discount amounts might be incorrect.', + ), + quantity: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe('A usage discount.') + .optional() + .describe('The usage discount.'), + }) + .describe('A discount by type.') + .optional() + .describe('The discounts that are applied to the line.'), + featureKey: zod.coerce + .string() + .min(1) + .max(simulateInvoiceBodyLinesItemRateCardOneFeatureKeyMax) + .regex( + simulateInvoiceBodyLinesItemRateCardOneFeatureKeyRegExp, + ) + .optional() + .describe('The feature the customer is entitled to use.'), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + simulateInvoiceBodyLinesItemRateCardOnePriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOnePriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemRateCardOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + }) + .describe( + 'InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line.', + ) + .optional() + .describe( + 'The rate card that is used for this line.\n\nThe rate card captures the intent of the price and discounts for the usage-based item.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + simulateInvoiceBodyLinesItemTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'Tax config specify the tax configuration for this line.', + ), + }) + .describe( + 'InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint.', + ), + ) + .describe('Lines to be included in the generated invoice.'), + number: zod.coerce + .string() + .min(1) + .max(simulateInvoiceBodyNumberOneMax) + .describe( + 'InvoiceNumber is a unique identifier for the invoice, generated by the\ninvoicing app.\n\nThe uniqueness depends on a lot of factors:\n- app setting (unique per app or unique per customer)\n- multiple app scenarios (multiple apps generating invoices with the same prefix)', + ) + .optional() + .describe('The number of the invoice.'), + }) + .describe('InvoiceSimulationInput is the input for simulating an invoice.') + +/** + * List invoices based on the specified filters. + * + * The expand option can be used to include additional information (besides the invoice header and totals) + * in the response. For example by adding the expand=lines option the invoice lines will be included in the response. + * + * Gathering invoices will always show the current usage calculated on the fly. + * @summary List invoices + */ +export const listInvoicesQueryCustomersItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listInvoicesQueryPageDefault = 1 + +export const listInvoicesQueryPageSizeDefault = 100 +export const listInvoicesQueryPageSizeMax = 1000 + +export const listInvoicesQueryOrderDefault = 'ASC' + +export const ListInvoicesQueryParams = zod.object({ + createdAfter: zod.coerce + .date() + .optional() + .describe('Filter by invoice created time.\nInclusive.'), + createdBefore: zod.coerce + .date() + .optional() + .describe('Filter by invoice created time.\nInclusive.'), + customers: zod + .array( + zod.coerce + .string() + .regex(listInvoicesQueryCustomersItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Filter by customer ID'), + expand: zod + .array( + zod + .enum(['lines', 'preceding', 'workflow.apps']) + .describe( + 'InvoiceExpand specifies the parts of the invoice to expand in the list output.', + ), + ) + .optional() + .describe('What parts of the list output to expand in listings'), + extendedStatuses: zod + .array(zod.coerce.string()) + .optional() + .describe('Filter by invoice extended statuses'), + includeDeleted: zod.coerce + .boolean() + .optional() + .describe('Include deleted invoices'), + issuedAfter: zod.coerce + .date() + .optional() + .describe('Filter by invoice issued time.\nInclusive.'), + issuedBefore: zod.coerce + .date() + .optional() + .describe('Filter by invoice issued time.\nInclusive.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listInvoicesQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum([ + 'customer.name', + 'issuedAt', + 'status', + 'createdAt', + 'updatedAt', + 'periodStart', + ]) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listInvoicesQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listInvoicesQueryPageSizeMax) + .default(listInvoicesQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + periodStartAfter: zod.coerce + .date() + .optional() + .describe('Filter by period start time.\nInclusive.'), + periodStartBefore: zod.coerce + .date() + .optional() + .describe('Filter by period start time.\nInclusive.'), + statuses: zod + .array( + zod + .enum([ + 'gathering', + 'draft', + 'issuing', + 'issued', + 'payment_processing', + 'overdue', + 'paid', + 'uncollectible', + 'voided', + ]) + .describe('InvoiceStatus describes the status of an invoice.'), + ) + .optional() + .describe('Filter by the invoice status.'), +}) + +/** + * Create a new invoice from the pending line items. + * + * This should be only called if for some reason we need to invoice a customer outside of the normal billing cycle. + * + * When creating an invoice, the pending line items will be marked as invoiced and the invoice will be created with the total amount of the pending items. + * + * New pending line items will be created for the period between now() and the next billing cycle's begining date for any metered item. + * + * The call can return multiple invoices if the pending line items are in different currencies. + * @summary Invoice a customer based on the pending line items + */ +export const invoicePendingLinesActionBodyFiltersOneLineIdsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const invoicePendingLinesActionBodyCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const InvoicePendingLinesActionBody = zod + .object({ + asOf: zod.coerce + .date() + .optional() + .describe( + 'The time as of which the invoice is created.\n\nIf not provided, the current time is used.', + ), + customerId: zod.coerce + .string() + .regex(invoicePendingLinesActionBodyCustomerIdRegExp) + .describe('The customer ID for which to create the invoice.'), + filters: zod + .object({ + lineIds: zod + .array( + zod.coerce + .string() + .regex(invoicePendingLinesActionBodyFiltersOneLineIdsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe( + 'The pending line items to include in the invoice, if not provided:\n- all line items that have invoice_at < asOf will be included\n- [progressive billing only] all usage based line items will be included up to asOf, new\nusage-based line items will be staged for the rest of the billing cycle\n\nAll lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail.', + ), + }) + .describe( + 'InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice.', + ) + .optional() + .describe('Filters to apply when creating the invoice.'), + progressiveBillingOverride: zod.coerce + .boolean() + .optional() + .describe( + "Override the progressive billing setting of the customer.\n\nCan be used to disable/enable progressive billing in case the business logic\nrequires it, if not provided the billing profile's progressive billing setting will be used.", + ), + }) + .describe( + 'BillingInvoiceActionInput is the input for creating an invoice.\n\nInvoice creation is always based on already pending line items created by the billingCreateLineByCustomer\noperation. Empty invoices are not allowed.', + ) + +/** + * Get an invoice by ID. + * + * Gathering invoices will always show the current usage calculated on the fly. + * @summary Get an invoice + */ +export const getInvoicePathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetInvoiceParams = zod.object({ + invoiceId: zod.coerce.string().regex(getInvoicePathInvoiceIdRegExp), +}) + +export const getInvoiceQueryIncludeDeletedLinesDefault = false + +export const GetInvoiceQueryParams = zod.object({ + expand: zod + .array( + zod + .enum(['lines', 'preceding', 'workflow.apps']) + .describe( + 'InvoiceExpand specifies the parts of the invoice to expand in the list output.', + ), + ) + .default(['lines']), + includeDeletedLines: zod.coerce + .boolean() + .default(getInvoiceQueryIncludeDeletedLinesDefault), +}) + +/** + * Delete an invoice + * + * Only invoices that are in the draft (or earlier) status can be deleted. + * + * Invoices that are post finalization can only be voided. + * @summary Delete an invoice + */ +export const deleteInvoicePathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteInvoiceParams = zod.object({ + invoiceId: zod.coerce.string().regex(deleteInvoicePathInvoiceIdRegExp), +}) + +/** + * Update an invoice + * + * Only invoices in draft or earlier status can be updated. + * @summary Update an invoice + */ +export const updateInvoicePathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateInvoiceParams = zod.object({ + invoiceId: zod.coerce.string().regex(updateInvoicePathInvoiceIdRegExp), +}) + +export const updateInvoiceBodyDescriptionMax = 1024 + +export const updateInvoiceBodySupplierOneKeyMax = 256 + +export const updateInvoiceBodySupplierOneTaxIdOneCodeOneMax = 32 + +export const updateInvoiceBodySupplierOneAddressesItemCountryOneMin = 2 +export const updateInvoiceBodySupplierOneAddressesItemCountryOneMax = 2 + +export const updateInvoiceBodySupplierOneAddressesItemCountryOneRegExp = + /^[A-Z]{2}$/ +export const updateInvoiceBodySupplierOneAddressesMax = 1 + +export const updateInvoiceBodyCustomerOneKeyMax = 256 + +export const updateInvoiceBodyCustomerOneTaxIdOneCodeOneMax = 32 + +export const updateInvoiceBodyCustomerOneAddressesItemCountryOneMin = 2 +export const updateInvoiceBodyCustomerOneAddressesItemCountryOneMax = 2 + +export const updateInvoiceBodyCustomerOneAddressesItemCountryOneRegExp = + /^[A-Z]{2}$/ +export const updateInvoiceBodyCustomerOneAddressesMax = 1 + +export const updateInvoiceBodyLinesItemNameMax = 256 + +export const updateInvoiceBodyLinesItemDescriptionMax = 1024 + +export const updateInvoiceBodyLinesItemTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updateInvoiceBodyLinesItemTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateInvoiceBodyLinesItemPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneOnePaymentTermDefault = + 'in_advance' +export const updateInvoiceBodyLinesItemPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const updateInvoiceBodyLinesItemPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFourMultiplierDefault = '1' +export const updateInvoiceBodyLinesItemPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemFeatureKeyMax = 64 + +export const updateInvoiceBodyLinesItemFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updateInvoiceBodyLinesItemRateCardOneFeatureKeyMax = 64 + +export const updateInvoiceBodyLinesItemRateCardOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updateInvoiceBodyLinesItemRateCardOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updateInvoiceBodyLinesItemRateCardOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneOnePaymentTermDefault = + 'in_advance' +export const updateInvoiceBodyLinesItemRateCardOnePriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const updateInvoiceBodyLinesItemRateCardOnePriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierDefault = + '1' +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOnePriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOneDiscountsOnePercentageOneCorrelationIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneCorrelationIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateInvoiceBodyLinesItemIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneAutoAdvanceDefault = true +export const updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDraftPeriodDefault = + 'P0D' +export const updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDueAfterDefault = + 'P30D' +export const updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneSubscriptionEndProrationModeDefault = + 'bill_actual_period' +export const updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDefaultTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDefaultTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateInvoiceBodyWorkflowOneWorkflowOnePaymentOneCollectionMethodDefault = + 'charge_automatically' + +export const UpdateInvoiceBody = zod + .object({ + customer: zod + .object({ + addresses: zod + .array( + zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min(updateInvoiceBodyCustomerOneAddressesItemCountryOneMin) + .max(updateInvoiceBodyCustomerOneAddressesItemCountryOneMax) + .regex( + updateInvoiceBodyCustomerOneAddressesItemCountryOneRegExp, + ) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce + .string() + .optional() + .describe('Phone number.'), + postalCode: zod.coerce + .string() + .optional() + .describe('Postal code.'), + state: zod.coerce + .string() + .optional() + .describe('State or province.'), + }) + .describe('Address'), + ) + .max(updateInvoiceBodyCustomerOneAddressesMax) + .optional() + .describe( + 'Regular post addresses for where information should be sent if needed.', + ), + key: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodyCustomerOneKeyMax) + .optional() + .describe('An optional unique key of the party (if available)'), + name: zod.coerce + .string() + .optional() + .describe('Legal name or representation of the organization.'), + taxId: zod + .object({ + code: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodyCustomerOneTaxIdOneCodeOneMax) + .describe( + 'TaxIdentificationCode is a normalized tax code shown on the original identity document.', + ) + .optional() + .describe( + 'Normalized tax code shown on the original identity document.', + ), + }) + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + .optional() + .describe( + "The entity's legal ID code used for tax purposes. They may have\nother numbers, but we're only interested in those valid for tax purposes.", + ), + }) + .describe('Resource update operation model.') + .describe('The customer the invoice is sent to.'), + description: zod.coerce + .string() + .max(updateInvoiceBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + lines: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max(updateInvoiceBodyLinesItemDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodyLinesItemFeatureKeyMax) + .regex(updateInvoiceBodyLinesItemFeatureKeyRegExp) + .optional() + .describe('The feature that the usage is based on.'), + id: zod.coerce + .string() + .regex(updateInvoiceBodyLinesItemIdRegExp) + .optional() + .describe('The ID of the line.'), + invoiceAt: zod.coerce + .date() + .describe('The time this line item should be invoiced.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodyLinesItemNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + period: zod + .object({ + from: zod.coerce.date().describe('Period start time.'), + to: zod.coerce.date().describe('Period end time.'), + }) + .describe('A period with a start and end time.') + .describe( + 'Period of the line item applies to for revenue recognition pruposes.\n\nBilling always treats periods as start being inclusive and end being exclusive.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + updateInvoiceBodyLinesItemPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod.enum(['flat']).describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod.enum(['unit']).describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + updateInvoiceBodyLinesItemPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .optional() + .describe('Price of the usage-based item being sold.'), + rateCard: zod + .object({ + discounts: zod + .object({ + percentage: zod + .object({ + correlationId: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOneDiscountsOnePercentageOneCorrelationIdRegExp, + ) + .optional() + .describe( + 'Correlation ID for the discount.\n\nThis is used to link discounts across different invoices (progressive billing use case).\n\nIf not provided, the invoicing engine will auto-generate one. When editing an invoice line,\nplease make sure to keep the same correlation ID of the discount or in progressive billing\nsetups the discount amounts might be incorrect.', + ), + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('A percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + correlationId: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneCorrelationIdRegExp, + ) + .optional() + .describe( + 'Correlation ID for the discount.\n\nThis is used to link discounts across different invoices (progressive billing use case).\n\nIf not provided, the invoicing engine will auto-generate one. When editing an invoice line,\nplease make sure to keep the same correlation ID of the discount or in progressive billing\nsetups the discount amounts might be incorrect.', + ), + quantity: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe('A usage discount.') + .optional() + .describe('The usage discount.'), + }) + .describe('A discount by type.') + .optional() + .describe('The discounts that are applied to the line.'), + featureKey: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodyLinesItemRateCardOneFeatureKeyMax) + .regex(updateInvoiceBodyLinesItemRateCardOneFeatureKeyRegExp) + .optional() + .describe('The feature the customer is entitled to use.'), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + updateInvoiceBodyLinesItemRateCardOnePriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + updateInvoiceBodyLinesItemRateCardOnePriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe('Dynamic price with spend commitments.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOnePriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe('Package price with spend commitments.'), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemRateCardOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + }) + .describe( + 'InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line.', + ) + .optional() + .describe( + 'The rate card that is used for this line.\n\nThe rate card captures the intent of the price and discounts for the usage-based item.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updateInvoiceBodyLinesItemTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex(updateInvoiceBodyLinesItemTaxConfigOneTaxCodeIdRegExp) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'Tax config specify the tax configuration for this line.', + ), + }) + .describe( + 'InvoiceLineReplaceUpdate represents the update model for an UBP invoice line.\n\nThis type makes ID optional to allow for creating new lines as part of the update.', + ), + ) + .describe('The lines included in the invoice.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + supplier: zod + .object({ + addresses: zod + .array( + zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min(updateInvoiceBodySupplierOneAddressesItemCountryOneMin) + .max(updateInvoiceBodySupplierOneAddressesItemCountryOneMax) + .regex( + updateInvoiceBodySupplierOneAddressesItemCountryOneRegExp, + ) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce + .string() + .optional() + .describe('Phone number.'), + postalCode: zod.coerce + .string() + .optional() + .describe('Postal code.'), + state: zod.coerce + .string() + .optional() + .describe('State or province.'), + }) + .describe('Address'), + ) + .max(updateInvoiceBodySupplierOneAddressesMax) + .optional() + .describe( + 'Regular post addresses for where information should be sent if needed.', + ), + key: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodySupplierOneKeyMax) + .optional() + .describe('An optional unique key of the party (if available)'), + name: zod.coerce + .string() + .optional() + .describe('Legal name or representation of the organization.'), + taxId: zod + .object({ + code: zod.coerce + .string() + .min(1) + .max(updateInvoiceBodySupplierOneTaxIdOneCodeOneMax) + .describe( + 'TaxIdentificationCode is a normalized tax code shown on the original identity document.', + ) + .optional() + .describe( + 'Normalized tax code shown on the original identity document.', + ), + }) + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + .optional() + .describe( + "The entity's legal ID code used for tax purposes. They may have\nother numbers, but we're only interested in those valid for tax purposes.", + ), + }) + .describe('Resource update operation model.') + .describe('The supplier of the lines included in the invoice.'), + workflow: zod + .object({ + workflow: zod + .object({ + invoicing: zod + .object({ + autoAdvance: zod.coerce + .boolean() + .default( + updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneAutoAdvanceDefault, + ) + .describe( + 'Whether to automatically issue the invoice after the draftPeriod has passed.', + ), + defaultTaxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDefaultTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDefaultTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + "Default tax configuration to apply to the invoices.\n\nSetting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is\ndeprecated and can no longer be added or changed: the organization default tax code is\nused instead. Existing tax-code values may still be removed, and `behavior` remains\nfully supported.", + ), + draftPeriod: zod.coerce + .string() + .default( + updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDraftPeriodDefault, + ) + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + dueAfter: zod.coerce + .string() + .default( + updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneDueAfterDefault, + ) + .describe( + "The period after which the invoice is due.\nWith some payment solutions it's only applicable for manual collection method.", + ), + subscriptionEndProrationMode: zod + .enum(['bill_full_period', 'bill_actual_period']) + .describe('Billing workflow subscription end proration mode.') + .default( + updateInvoiceBodyWorkflowOneWorkflowOneInvoicingOneSubscriptionEndProrationModeDefault, + ) + .describe( + 'Controls how subscription-ending shortened service periods are billed.', + ), + }) + .describe( + 'InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow.', + ) + .describe('The invoicing settings for this workflow'), + payment: zod + .object({ + collectionMethod: zod + .enum(['charge_automatically', 'send_invoice']) + .describe( + 'CollectionMethod specifies how the invoice should be collected (automatic vs manual)', + ) + .default( + updateInvoiceBodyWorkflowOneWorkflowOnePaymentOneCollectionMethodDefault, + ) + .describe('The payment method for the invoice.'), + }) + .describe( + 'BillingWorkflowPaymentSettings represents the payment settings for a billing workflow', + ) + .describe('The payment settings for this workflow'), + }) + .describe( + "Mutable workflow settings for an invoice.\n\nOther fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow\nat creation time.", + ) + .describe('The workflow used for this invoice.'), + }) + .describe( + 'InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow.\n\nFields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings.', + ) + .describe('The workflow settings for the invoice.'), + }) + .describe('InvoiceReplaceUpdate represents the update model for an invoice.') + +/** + * Advance the invoice's state to the next status. + * + * The call doesn't "approve the invoice", it only advances the invoice to the next status if the transition would be automatic. + * + * The action can be called when the invoice's statusDetails' actions field contain the "advance" action. + * @summary Advance the invoice's state to the next status + */ +export const advanceInvoiceActionPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const AdvanceInvoiceActionParams = zod.object({ + invoiceId: zod.coerce.string().regex(advanceInvoiceActionPathInvoiceIdRegExp), +}) + +/** + * Approve an invoice and start executing the payment workflow. + * + * This call instantly sends the invoice to the customer using the configured billing profile app. + * + * This call is valid in two invoice statuses: + * - `draft`: the invoice will be sent to the customer, the invluce state becomes issued + * - `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes issued + * @summary Send the invoice to the customer + */ +export const approveInvoiceActionPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ApproveInvoiceActionParams = zod.object({ + invoiceId: zod.coerce.string().regex(approveInvoiceActionPathInvoiceIdRegExp), +}) + +/** + * Retry advancing the invoice after a failed attempt. + * + * The action can be called when the invoice's statusDetails' actions field contain the "retry" action. + * @summary Retry advancing the invoice after a failed attempt. + */ +export const retryInvoiceActionPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const RetryInvoiceActionParams = zod.object({ + invoiceId: zod.coerce.string().regex(retryInvoiceActionPathInvoiceIdRegExp), +}) + +/** + * Snapshot quantities for usage based line items. + * + * This call will snapshot the quantities for all usage based line items in the invoice. + * + * This call is only valid in `draft.waiting_for_collection` status, where the collection period + * can be skipped using this action. + * @summary Snapshot quantities for usage based line items + */ +export const snapshotQuantitiesInvoiceActionPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const SnapshotQuantitiesInvoiceActionParams = zod.object({ + invoiceId: zod.coerce + .string() + .regex(snapshotQuantitiesInvoiceActionPathInvoiceIdRegExp), +}) + +/** + * Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + * + * Note: charges might apply, depending on the tax provider. + * @summary Recalculate an invoice's tax amounts + */ +export const recalculateInvoiceTaxActionPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const RecalculateInvoiceTaxActionParams = zod.object({ + invoiceId: zod.coerce + .string() + .regex(recalculateInvoiceTaxActionPathInvoiceIdRegExp), +}) + +/** + * Void an invoice + * + * Only invoices that have been alread issued can be voided. + * + * Voiding an invoice will mark it as voided, the user can specify how to handle the voided line items. + * @summary Void an invoice + */ +export const voidInvoiceActionPathInvoiceIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const VoidInvoiceActionParams = zod.object({ + invoiceId: zod.coerce.string().regex(voidInvoiceActionPathInvoiceIdRegExp), +}) + +export const voidInvoiceActionBodyOverridesItemLineIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const VoidInvoiceActionBody = zod + .object({ + action: zod + .object({ + action: zod + .union([ + zod + .object({ + type: zod + .enum(['discard']) + .describe('The action to take on the line item.'), + }) + .describe( + 'VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice.', + ), + zod + .object({ + nextInvoiceAt: zod.coerce + .date() + .optional() + .describe( + 'The time at which the line item should be invoiced again.\n\nIf not provided, the line item will be re-invoiced now.', + ), + type: zod + .enum(['pending']) + .describe('The action to take on the line item.'), + }) + .describe( + 'VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice.', + ), + ]) + .describe( + 'VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding.', + ) + .describe('The action to take on the line items.'), + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe( + 'How much of the total line items to be voided? (e.g. 100% means all charges are voided)', + ), + }) + .describe( + 'InvoiceVoidAction describes how to handle the voided line items.', + ) + .describe('The action to take on the voided line items.'), + overrides: zod + .array( + zod + .object({ + action: zod + .object({ + action: zod + .union([ + zod + .object({ + type: zod + .enum(['discard']) + .describe('The action to take on the line item.'), + }) + .describe( + 'VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice.', + ), + zod + .object({ + nextInvoiceAt: zod.coerce + .date() + .optional() + .describe( + 'The time at which the line item should be invoiced again.\n\nIf not provided, the line item will be re-invoiced now.', + ), + type: zod + .enum(['pending']) + .describe('The action to take on the line item.'), + }) + .describe( + 'VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice.', + ), + ]) + .describe( + 'VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding.', + ) + .describe('The action to take on the line items.'), + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe( + 'How much of the total line items to be voided? (e.g. 100% means all charges are voided)', + ), + }) + .describe( + 'InvoiceVoidAction describes how to handle the voided line items.', + ) + .describe('The action to take on the line item.'), + lineId: zod.coerce + .string() + .regex(voidInvoiceActionBodyOverridesItemLineIdRegExp) + .describe('The line item ID to override.'), + }) + .describe( + 'VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding.', + ), + ) + .nullish() + .describe( + 'Per line item overrides for the action.\n\nIf not specified, the `action` will be applied to all line items.', + ), + reason: zod.coerce.string().describe('The reason for voiding the invoice.'), + }) + .describe('Request to void an invoice') + +/** + * List all billing profiles matching the specified filters. + * + * The expand option can be used to include additional information (besides the billing profile) + * in the response. For example by adding the expand=apps option the apps used by the billing profile + * will be included in the response. + * @summary List billing profiles + */ +export const listBillingProfilesQueryIncludeArchivedDefault = false +export const listBillingProfilesQueryPageDefault = 1 + +export const listBillingProfilesQueryPageSizeDefault = 100 +export const listBillingProfilesQueryPageSizeMax = 1000 + +export const listBillingProfilesQueryOrderDefault = 'ASC' + +export const ListBillingProfilesQueryParams = zod.object({ + expand: zod + .array( + zod + .enum(['apps']) + .describe('BillingProfileExpand details what profile fields to expand'), + ) + .optional(), + includeArchived: zod.coerce + .boolean() + .default(listBillingProfilesQueryIncludeArchivedDefault), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listBillingProfilesQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['createdAt', 'updatedAt', 'default', 'name']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listBillingProfilesQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listBillingProfilesQueryPageSizeMax) + .default(listBillingProfilesQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Create a new billing profile + * + * Billing profiles are representations of a customer's billing information. Customer overrides + * can be applied to a billing profile to customize the billing behavior for a specific customer. + * @summary Create a new billing profile + */ +export const createBillingProfileBodyNameMax = 256 + +export const createBillingProfileBodyDescriptionMax = 1024 + +export const createBillingProfileBodySupplierOneKeyMax = 256 + +export const createBillingProfileBodySupplierOneTaxIdOneCodeOneMax = 32 + +export const createBillingProfileBodySupplierOneAddressesItemCountryOneMin = 2 +export const createBillingProfileBodySupplierOneAddressesItemCountryOneMax = 2 + +export const createBillingProfileBodySupplierOneAddressesItemCountryOneRegExp = + /^[A-Z]{2}$/ +export const createBillingProfileBodySupplierOneAddressesMax = 1 + +export const createBillingProfileBodyWorkflowOneCollectionOneAlignmentOneTwoRecurringPeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createBillingProfileBodyWorkflowOneCollectionOneAlignmentDefault = + { type: 'subscription' as const } as const +export const createBillingProfileBodyWorkflowOneCollectionOneIntervalDefault = + 'PT1H' +export const createBillingProfileBodyWorkflowOneInvoicingOneAutoAdvanceDefault = true +export const createBillingProfileBodyWorkflowOneInvoicingOneDraftPeriodDefault = + 'P0D' +export const createBillingProfileBodyWorkflowOneInvoicingOneDueAfterDefault = + 'P30D' +export const createBillingProfileBodyWorkflowOneInvoicingOneProgressiveBillingDefault = true +export const createBillingProfileBodyWorkflowOneInvoicingOneSubscriptionEndProrationModeDefault = + 'bill_actual_period' +export const createBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createBillingProfileBodyWorkflowOnePaymentOneCollectionMethodDefault = + 'charge_automatically' +export const createBillingProfileBodyWorkflowOneTaxOneEnabledDefault = true +export const createBillingProfileBodyWorkflowOneTaxOneEnforcedDefault = false +export const createBillingProfileBodyAppsOneTaxRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createBillingProfileBodyAppsOneInvoicingRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createBillingProfileBodyAppsOnePaymentRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreateBillingProfileBody = zod + .object({ + apps: zod + .object({ + invoicing: zod.coerce + .string() + .regex(createBillingProfileBodyAppsOneInvoicingRegExp) + .describe('The invoicing app used for this workflow'), + payment: zod.coerce + .string() + .regex(createBillingProfileBodyAppsOnePaymentRegExp) + .describe('The payment app used for this workflow'), + tax: zod.coerce + .string() + .regex(createBillingProfileBodyAppsOneTaxRegExp) + .describe('The tax app used for this workflow'), + }) + .describe( + "BillingProfileAppsCreate represents the input for creating a billing profile's apps", + ) + .describe('The apps used by this billing profile.'), + default: zod.coerce.boolean().describe('Is this the default profile?'), + description: zod.coerce + .string() + .max(createBillingProfileBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createBillingProfileBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + supplier: zod + .object({ + addresses: zod + .array( + zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min( + createBillingProfileBodySupplierOneAddressesItemCountryOneMin, + ) + .max( + createBillingProfileBodySupplierOneAddressesItemCountryOneMax, + ) + .regex( + createBillingProfileBodySupplierOneAddressesItemCountryOneRegExp, + ) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce + .string() + .optional() + .describe('Phone number.'), + postalCode: zod.coerce + .string() + .optional() + .describe('Postal code.'), + state: zod.coerce + .string() + .optional() + .describe('State or province.'), + }) + .describe('Address'), + ) + .max(createBillingProfileBodySupplierOneAddressesMax) + .optional() + .describe( + 'Regular post addresses for where information should be sent if needed.', + ), + id: zod.coerce + .string() + .optional() + .describe('Unique identifier for the party (if available)'), + key: zod.coerce + .string() + .min(1) + .max(createBillingProfileBodySupplierOneKeyMax) + .optional() + .describe('An optional unique key of the party (if available)'), + name: zod.coerce + .string() + .optional() + .describe('Legal name or representation of the organization.'), + taxId: zod + .object({ + code: zod.coerce + .string() + .min(1) + .max(createBillingProfileBodySupplierOneTaxIdOneCodeOneMax) + .describe( + 'TaxIdentificationCode is a normalized tax code shown on the original identity document.', + ) + .optional() + .describe( + 'Normalized tax code shown on the original identity document.', + ), + }) + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + .optional() + .describe( + "The entity's legal ID code used for tax purposes. They may have\nother numbers, but we're only interested in those valid for tax purposes.", + ), + }) + .describe('Party represents a person or business entity.') + .describe( + 'The name and contact information for the supplier this billing profile represents', + ), + workflow: zod + .object({ + collection: zod + .object({ + alignment: zod + .union([ + zod + .object({ + type: zod + .enum(['subscription']) + .describe('The type of alignment.'), + }) + .describe( + 'BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items\ninto an invoice.', + ), + zod + .object({ + recurringPeriod: zod + .object({ + anchor: zod.coerce + .date() + .describe( + 'A date-time anchor to base the recurring period on.', + ), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createBillingProfileBodyWorkflowOneCollectionOneAlignmentOneTwoRecurringPeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe( + 'The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration.', + ), + }) + .describe( + 'Recurring period with an interval and an anchor.', + ) + .describe('The recurring period for the alignment.'), + type: zod + .enum(['anchored']) + .describe('The type of alignment.'), + }) + .describe( + 'BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items\ninto an invoice.', + ), + ]) + .describe( + 'The alignment for collecting the pending line items into an invoice.\n\nDefaults to subscription, which means that we are to create a new invoice every time the\na subscription period starts (for in advance items) or ends (for in arrears items).', + ) + .default( + createBillingProfileBodyWorkflowOneCollectionOneAlignmentDefault, + ) + .describe( + 'The alignment for collecting the pending line items into an invoice.', + ), + interval: zod.coerce + .string() + .default( + createBillingProfileBodyWorkflowOneCollectionOneIntervalDefault, + ) + .describe( + 'This grace period can be used to delay the collection of the pending line items specified in\nalignment.\n\nThis is useful, in case of multiple subscriptions having slightly different billing periods.', + ), + }) + .describe( + 'Workflow collection specifies how to collect the pending line items for an invoice', + ) + .optional() + .describe('The collection settings for this workflow'), + invoicing: zod + .object({ + autoAdvance: zod.coerce + .boolean() + .default( + createBillingProfileBodyWorkflowOneInvoicingOneAutoAdvanceDefault, + ) + .describe( + 'Whether to automatically issue the invoice after the draftPeriod has passed.', + ), + defaultTaxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + "Default tax configuration to apply to the invoices.\n\nSetting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is\ndeprecated and can no longer be added or changed: the organization default tax code is\nused instead. Existing tax-code values may still be removed, and `behavior` remains\nfully supported.", + ), + draftPeriod: zod.coerce + .string() + .default( + createBillingProfileBodyWorkflowOneInvoicingOneDraftPeriodDefault, + ) + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + dueAfter: zod.coerce + .string() + .default( + createBillingProfileBodyWorkflowOneInvoicingOneDueAfterDefault, + ) + .describe( + "The period after which the invoice is due.\nWith some payment solutions it's only applicable for manual collection method.", + ), + progressiveBilling: zod.coerce + .boolean() + .default( + createBillingProfileBodyWorkflowOneInvoicingOneProgressiveBillingDefault, + ) + .describe( + 'Should progressive billing be allowed for this workflow?', + ), + subscriptionEndProrationMode: zod + .enum(['bill_full_period', 'bill_actual_period']) + .describe('Billing workflow subscription end proration mode.') + .default( + createBillingProfileBodyWorkflowOneInvoicingOneSubscriptionEndProrationModeDefault, + ) + .describe( + 'Controls how subscription-ending shortened service periods are billed.', + ), + }) + .describe( + 'BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow', + ) + .optional() + .describe('The invoicing settings for this workflow'), + payment: zod + .object({ + collectionMethod: zod + .enum(['charge_automatically', 'send_invoice']) + .describe( + 'CollectionMethod specifies how the invoice should be collected (automatic vs manual)', + ) + .default( + createBillingProfileBodyWorkflowOnePaymentOneCollectionMethodDefault, + ) + .describe('The payment method for the invoice.'), + }) + .describe( + 'BillingWorkflowPaymentSettings represents the payment settings for a billing workflow', + ) + .optional() + .describe('The payment settings for this workflow'), + tax: zod + .object({ + enabled: zod.coerce + .boolean() + .default(createBillingProfileBodyWorkflowOneTaxOneEnabledDefault) + .describe( + 'Enable automatic tax calculation when tax is supported by the app.\nFor example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax.', + ), + enforced: zod.coerce + .boolean() + .default(createBillingProfileBodyWorkflowOneTaxOneEnforcedDefault) + .describe( + 'Enforce tax calculation when tax is supported by the app.\nWhen enabled, OpenMeter will not allow to create an invoice without tax calculation.\nEnforcement is different per apps, for example, Stripe app requires customer\nto have a tax location when starting a paid subscription.', + ), + }) + .describe( + 'BillingWorkflowTaxSettings represents the tax settings for a billing workflow', + ) + .optional() + .describe('The tax settings for this workflow'), + }) + .describe('Resource create operation model.') + .describe('The billing workflow settings for this profile.'), + }) + .describe( + 'BillingProfileCreate represents the input for creating a billing profile', + ) + +/** + * Delete a billing profile by id. + * + * Only such billing profiles can be deleted that are: + * - not the default one + * - not pinned to any customer using customer overrides + * - only have finalized invoices + * @summary Delete a billing profile + */ +export const deleteBillingProfilePathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteBillingProfileParams = zod.object({ + id: zod.coerce.string().regex(deleteBillingProfilePathIdRegExp), +}) + +/** + * Get a billing profile by id. + * + * The expand option can be used to include additional information (besides the billing profile) + * in the response. For example by adding the expand=apps option the apps used by the billing profile + * will be included in the response. + * @summary Get a billing profile + */ +export const getBillingProfilePathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetBillingProfileParams = zod.object({ + id: zod.coerce.string().regex(getBillingProfilePathIdRegExp), +}) + +export const GetBillingProfileQueryParams = zod.object({ + expand: zod + .array( + zod + .enum(['apps']) + .describe('BillingProfileExpand details what profile fields to expand'), + ) + .optional(), +}) + +/** + * Update a billing profile by id. + * + * The apps field cannot be updated directly, if an app change is desired a new + * profile should be created. + * @summary Update a billing profile + */ +export const updateBillingProfilePathIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateBillingProfileParams = zod.object({ + id: zod.coerce.string().regex(updateBillingProfilePathIdRegExp), +}) + +export const updateBillingProfileBodyNameMax = 256 + +export const updateBillingProfileBodyDescriptionMax = 1024 + +export const updateBillingProfileBodySupplierOneKeyMax = 256 + +export const updateBillingProfileBodySupplierOneTaxIdOneCodeOneMax = 32 + +export const updateBillingProfileBodySupplierOneAddressesItemCountryOneMin = 2 +export const updateBillingProfileBodySupplierOneAddressesItemCountryOneMax = 2 + +export const updateBillingProfileBodySupplierOneAddressesItemCountryOneRegExp = + /^[A-Z]{2}$/ +export const updateBillingProfileBodySupplierOneAddressesMax = 1 + +export const updateBillingProfileBodyWorkflowOneCollectionOneAlignmentOneTwoRecurringPeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const updateBillingProfileBodyWorkflowOneCollectionOneAlignmentDefault = + { type: 'subscription' as const } as const +export const updateBillingProfileBodyWorkflowOneCollectionOneIntervalDefault = + 'PT1H' +export const updateBillingProfileBodyWorkflowOneInvoicingOneAutoAdvanceDefault = true +export const updateBillingProfileBodyWorkflowOneInvoicingOneDraftPeriodDefault = + 'P0D' +export const updateBillingProfileBodyWorkflowOneInvoicingOneDueAfterDefault = + 'P30D' +export const updateBillingProfileBodyWorkflowOneInvoicingOneProgressiveBillingDefault = true +export const updateBillingProfileBodyWorkflowOneInvoicingOneSubscriptionEndProrationModeDefault = + 'bill_actual_period' +export const updateBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updateBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateBillingProfileBodyWorkflowOnePaymentOneCollectionMethodDefault = + 'charge_automatically' +export const updateBillingProfileBodyWorkflowOneTaxOneEnabledDefault = true +export const updateBillingProfileBodyWorkflowOneTaxOneEnforcedDefault = false + +export const UpdateBillingProfileBody = zod + .object({ + default: zod.coerce.boolean().describe('Is this the default profile?'), + description: zod.coerce + .string() + .max(updateBillingProfileBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateBillingProfileBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + supplier: zod + .object({ + addresses: zod + .array( + zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min( + updateBillingProfileBodySupplierOneAddressesItemCountryOneMin, + ) + .max( + updateBillingProfileBodySupplierOneAddressesItemCountryOneMax, + ) + .regex( + updateBillingProfileBodySupplierOneAddressesItemCountryOneRegExp, + ) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce + .string() + .optional() + .describe('Phone number.'), + postalCode: zod.coerce + .string() + .optional() + .describe('Postal code.'), + state: zod.coerce + .string() + .optional() + .describe('State or province.'), + }) + .describe('Address'), + ) + .max(updateBillingProfileBodySupplierOneAddressesMax) + .optional() + .describe( + 'Regular post addresses for where information should be sent if needed.', + ), + id: zod.coerce + .string() + .optional() + .describe('Unique identifier for the party (if available)'), + key: zod.coerce + .string() + .min(1) + .max(updateBillingProfileBodySupplierOneKeyMax) + .optional() + .describe('An optional unique key of the party (if available)'), + name: zod.coerce + .string() + .optional() + .describe('Legal name or representation of the organization.'), + taxId: zod + .object({ + code: zod.coerce + .string() + .min(1) + .max(updateBillingProfileBodySupplierOneTaxIdOneCodeOneMax) + .describe( + 'TaxIdentificationCode is a normalized tax code shown on the original identity document.', + ) + .optional() + .describe( + 'Normalized tax code shown on the original identity document.', + ), + }) + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + .optional() + .describe( + "The entity's legal ID code used for tax purposes. They may have\nother numbers, but we're only interested in those valid for tax purposes.", + ), + }) + .describe('Party represents a person or business entity.') + .describe( + 'The name and contact information for the supplier this billing profile represents', + ), + workflow: zod + .object({ + collection: zod + .object({ + alignment: zod + .union([ + zod + .object({ + type: zod + .enum(['subscription']) + .describe('The type of alignment.'), + }) + .describe( + 'BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items\ninto an invoice.', + ), + zod + .object({ + recurringPeriod: zod + .object({ + anchor: zod.coerce + .date() + .describe( + 'A date-time anchor to base the recurring period on.', + ), + interval: zod + .union([ + zod.coerce + .string() + .regex( + updateBillingProfileBodyWorkflowOneCollectionOneAlignmentOneTwoRecurringPeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe( + 'The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration.', + ), + }) + .describe( + 'Recurring period with an interval and an anchor.', + ) + .describe('The recurring period for the alignment.'), + type: zod + .enum(['anchored']) + .describe('The type of alignment.'), + }) + .describe( + 'BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items\ninto an invoice.', + ), + ]) + .describe( + 'The alignment for collecting the pending line items into an invoice.\n\nDefaults to subscription, which means that we are to create a new invoice every time the\na subscription period starts (for in advance items) or ends (for in arrears items).', + ) + .default( + updateBillingProfileBodyWorkflowOneCollectionOneAlignmentDefault, + ) + .describe( + 'The alignment for collecting the pending line items into an invoice.', + ), + interval: zod.coerce + .string() + .default( + updateBillingProfileBodyWorkflowOneCollectionOneIntervalDefault, + ) + .describe( + 'This grace period can be used to delay the collection of the pending line items specified in\nalignment.\n\nThis is useful, in case of multiple subscriptions having slightly different billing periods.', + ), + }) + .describe( + 'Workflow collection specifies how to collect the pending line items for an invoice', + ) + .optional() + .describe('The collection settings for this workflow'), + invoicing: zod + .object({ + autoAdvance: zod.coerce + .boolean() + .default( + updateBillingProfileBodyWorkflowOneInvoicingOneAutoAdvanceDefault, + ) + .describe( + 'Whether to automatically issue the invoice after the draftPeriod has passed.', + ), + defaultTaxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updateBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updateBillingProfileBodyWorkflowOneInvoicingOneDefaultTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + "Default tax configuration to apply to the invoices.\n\nSetting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is\ndeprecated and can no longer be added or changed: the organization default tax code is\nused instead. Existing tax-code values may still be removed, and `behavior` remains\nfully supported.", + ), + draftPeriod: zod.coerce + .string() + .default( + updateBillingProfileBodyWorkflowOneInvoicingOneDraftPeriodDefault, + ) + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + dueAfter: zod.coerce + .string() + .default( + updateBillingProfileBodyWorkflowOneInvoicingOneDueAfterDefault, + ) + .describe( + "The period after which the invoice is due.\nWith some payment solutions it's only applicable for manual collection method.", + ), + progressiveBilling: zod.coerce + .boolean() + .default( + updateBillingProfileBodyWorkflowOneInvoicingOneProgressiveBillingDefault, + ) + .describe( + 'Should progressive billing be allowed for this workflow?', + ), + subscriptionEndProrationMode: zod + .enum(['bill_full_period', 'bill_actual_period']) + .describe('Billing workflow subscription end proration mode.') + .default( + updateBillingProfileBodyWorkflowOneInvoicingOneSubscriptionEndProrationModeDefault, + ) + .describe( + 'Controls how subscription-ending shortened service periods are billed.', + ), + }) + .describe( + 'BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow', + ) + .optional() + .describe('The invoicing settings for this workflow'), + payment: zod + .object({ + collectionMethod: zod + .enum(['charge_automatically', 'send_invoice']) + .describe( + 'CollectionMethod specifies how the invoice should be collected (automatic vs manual)', + ) + .default( + updateBillingProfileBodyWorkflowOnePaymentOneCollectionMethodDefault, + ) + .describe('The payment method for the invoice.'), + }) + .describe( + 'BillingWorkflowPaymentSettings represents the payment settings for a billing workflow', + ) + .optional() + .describe('The payment settings for this workflow'), + tax: zod + .object({ + enabled: zod.coerce + .boolean() + .default(updateBillingProfileBodyWorkflowOneTaxOneEnabledDefault) + .describe( + 'Enable automatic tax calculation when tax is supported by the app.\nFor example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax.', + ), + enforced: zod.coerce + .boolean() + .default(updateBillingProfileBodyWorkflowOneTaxOneEnforcedDefault) + .describe( + 'Enforce tax calculation when tax is supported by the app.\nWhen enabled, OpenMeter will not allow to create an invoice without tax calculation.\nEnforcement is different per apps, for example, Stripe app requires customer\nto have a tax location when starting a paid subscription.', + ), + }) + .describe( + 'BillingWorkflowTaxSettings represents the tax settings for a billing workflow', + ) + .optional() + .describe('The tax settings for this workflow'), + }) + .describe( + 'BillingWorkflow represents the settings for a billing workflow.', + ) + .describe('The billing workflow settings for this profile.'), + }) + .describe( + 'BillingProfileReplaceUpdate represents the input for updating a billing profile\n\nThe apps field cannot be updated directly, if an app change is desired a new\nprofile should be created.', + ) + +/** + * Create a new customer. + * @summary Create customer + */ +export const createCustomerBodyNameMax = 256 + +export const createCustomerBodyDescriptionMax = 1024 + +export const createCustomerBodyKeyMax = 256 + +export const createCustomerBodyUsageAttributionOneSubjectKeysMin = 0 + +export const createCustomerBodyCurrencyOneMin = 3 +export const createCustomerBodyCurrencyOneMax = 3 + +export const createCustomerBodyCurrencyOneRegExp = /^[A-Z]{3}$/ +export const createCustomerBodyBillingAddressOneCountryOneMin = 2 +export const createCustomerBodyBillingAddressOneCountryOneMax = 2 + +export const createCustomerBodyBillingAddressOneCountryOneRegExp = /^[A-Z]{2}$/ + +export const CreateCustomerBody = zod + .object({ + billingAddress: zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min(createCustomerBodyBillingAddressOneCountryOneMin) + .max(createCustomerBodyBillingAddressOneCountryOneMax) + .regex(createCustomerBodyBillingAddressOneCountryOneRegExp) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce.string().optional().describe('Phone number.'), + postalCode: zod.coerce.string().optional().describe('Postal code.'), + state: zod.coerce.string().optional().describe('State or province.'), + }) + .describe('Address') + .optional() + .describe( + 'The billing address of the customer.\nUsed for tax and invoicing.', + ), + currency: zod.coerce + .string() + .min(createCustomerBodyCurrencyOneMin) + .max(createCustomerBodyCurrencyOneMax) + .regex(createCustomerBodyCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .optional() + .describe( + 'Currency of the customer.\nUsed for billing, tax and invoicing.', + ), + description: zod.coerce + .string() + .max(createCustomerBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + key: zod.coerce + .string() + .min(1) + .max(createCustomerBodyKeyMax) + .optional() + .describe( + 'An optional unique key of the customer.\nEither key or usageAttribution.subjectKeys must be provided.\nUseful to reference the customer in external systems.\nFor example, your database ID.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createCustomerBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + primaryEmail: zod.coerce + .string() + .optional() + .describe('The primary email address of the customer.'), + usageAttribution: zod + .object({ + subjectKeys: zod + .array( + zod.coerce + .string() + .min(1) + .describe( + 'SubjectKey is a key that is used to identify a subject.', + ), + ) + .min(createCustomerBodyUsageAttributionOneSubjectKeysMin) + .describe( + 'The subjects that are attributed to the customer.\nCan be empty when no subjects are associated with the customer.', + ), + }) + .describe( + 'Mapping to attribute metered usage to the customer.\nOne customer can have zero or more subjects,\nbut one subject can only belong to one customer.', + ) + .optional() + .describe( + 'Mapping to attribute metered usage to the customer\nEither key or usageAttribution.subjectKeys must be provided.', + ), + }) + .describe('Resource create operation model.') + +/** + * List customers. + * @summary List customers + */ +export const listCustomersQueryPageDefault = 1 + +export const listCustomersQueryPageSizeDefault = 100 +export const listCustomersQueryPageSizeMax = 1000 + +export const listCustomersQueryOrderDefault = 'ASC' +export const listCustomersQueryIncludeDeletedDefault = false + +export const ListCustomersQueryParams = zod.object({ + expand: zod + .array( + zod + .enum(['subscriptions']) + .describe( + 'CustomerExpand specifies the parts of the customer to expand in the list output.', + ), + ) + .optional() + .describe('What parts of the list output to expand in listings'), + includeDeleted: zod.coerce + .boolean() + .default(listCustomersQueryIncludeDeletedDefault) + .describe('Include deleted customers.'), + key: zod.coerce + .string() + .optional() + .describe('Filter customers by key.\nCase-insensitive partial match.'), + name: zod.coerce + .string() + .optional() + .describe('Filter customers by name.\nCase-insensitive partial match.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listCustomersQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'name', 'createdAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listCustomersQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listCustomersQueryPageSizeMax) + .default(listCustomersQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + planKey: zod.coerce + .string() + .optional() + .describe('Filter customers by the plan key of their susbcription.'), + primaryEmail: zod.coerce + .string() + .optional() + .describe( + 'Filter customers by primary email.\nCase-insensitive partial match.', + ), + subject: zod.coerce + .string() + .optional() + .describe( + 'Filter customers by usage attribution subject.\nCase-insensitive partial match.', + ), +}) + +/** + * Get a customer by ID or key. + * @summary Get customer + */ +export const getCustomerPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerPathCustomerIdOrKeyTwoMax = 256 + +export const GetCustomerParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const GetCustomerQueryParams = zod.object({ + expand: zod + .array( + zod + .enum(['subscriptions']) + .describe( + 'CustomerExpand specifies the parts of the customer to expand in the list output.', + ), + ) + .optional() + .describe('What parts of the customer output to expand'), +}) + +/** + * Update a customer by ID. + * @summary Update customer + */ +export const updateCustomerPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateCustomerPathCustomerIdOrKeyTwoMax = 256 + +export const UpdateCustomerParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(updateCustomerPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(updateCustomerPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const updateCustomerBodyNameMax = 256 + +export const updateCustomerBodyDescriptionMax = 1024 + +export const updateCustomerBodyKeyMax = 256 + +export const updateCustomerBodyUsageAttributionOneSubjectKeysMin = 0 + +export const updateCustomerBodyCurrencyOneMin = 3 +export const updateCustomerBodyCurrencyOneMax = 3 + +export const updateCustomerBodyCurrencyOneRegExp = /^[A-Z]{3}$/ +export const updateCustomerBodyBillingAddressOneCountryOneMin = 2 +export const updateCustomerBodyBillingAddressOneCountryOneMax = 2 + +export const updateCustomerBodyBillingAddressOneCountryOneRegExp = /^[A-Z]{2}$/ + +export const UpdateCustomerBody = zod + .object({ + billingAddress: zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min(updateCustomerBodyBillingAddressOneCountryOneMin) + .max(updateCustomerBodyBillingAddressOneCountryOneMax) + .regex(updateCustomerBodyBillingAddressOneCountryOneRegExp) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce.string().optional().describe('Phone number.'), + postalCode: zod.coerce.string().optional().describe('Postal code.'), + state: zod.coerce.string().optional().describe('State or province.'), + }) + .describe('Address') + .optional() + .describe( + 'The billing address of the customer.\nUsed for tax and invoicing.', + ), + currency: zod.coerce + .string() + .min(updateCustomerBodyCurrencyOneMin) + .max(updateCustomerBodyCurrencyOneMax) + .regex(updateCustomerBodyCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .optional() + .describe( + 'Currency of the customer.\nUsed for billing, tax and invoicing.', + ), + description: zod.coerce + .string() + .max(updateCustomerBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + key: zod.coerce + .string() + .min(1) + .max(updateCustomerBodyKeyMax) + .optional() + .describe( + 'An optional unique key of the customer.\nEither key or usageAttribution.subjectKeys must be provided.\nUseful to reference the customer in external systems.\nFor example, your database ID.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateCustomerBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + primaryEmail: zod.coerce + .string() + .optional() + .describe('The primary email address of the customer.'), + usageAttribution: zod + .object({ + subjectKeys: zod + .array( + zod.coerce + .string() + .min(1) + .describe( + 'SubjectKey is a key that is used to identify a subject.', + ), + ) + .min(updateCustomerBodyUsageAttributionOneSubjectKeysMin) + .describe( + 'The subjects that are attributed to the customer.\nCan be empty when no subjects are associated with the customer.', + ), + }) + .describe( + 'Mapping to attribute metered usage to the customer.\nOne customer can have zero or more subjects,\nbut one subject can only belong to one customer.', + ) + .optional() + .describe( + 'Mapping to attribute metered usage to the customer\nEither key or usageAttribution.subjectKeys must be provided.', + ), + }) + .describe('Resource update operation model.') + +/** + * Delete a customer by ID. + * @summary Delete customer + */ +export const deleteCustomerPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const deleteCustomerPathCustomerIdOrKeyTwoMax = 256 + +export const DeleteCustomerParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(deleteCustomerPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(deleteCustomerPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +/** + * Get the overall access of a customer. + * @summary Get customer access + */ +export const getCustomerAccessPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerAccessPathCustomerIdOrKeyTwoMax = 256 + +export const GetCustomerAccessParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerAccessPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerAccessPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +/** + * List customers app data. + * @summary List customer app data + */ +export const listCustomerAppDataPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listCustomerAppDataPathCustomerIdOrKeyTwoMax = 256 + +export const ListCustomerAppDataParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(listCustomerAppDataPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(listCustomerAppDataPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const listCustomerAppDataQueryPageDefault = 1 + +export const listCustomerAppDataQueryPageSizeDefault = 100 +export const listCustomerAppDataQueryPageSizeMax = 1000 + +export const ListCustomerAppDataQueryParams = zod.object({ + page: zod.coerce + .number() + .min(1) + .default(listCustomerAppDataQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listCustomerAppDataQueryPageSizeMax) + .default(listCustomerAppDataQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + type: zod + .enum(['stripe', 'sandbox', 'custom_invoicing']) + .optional() + .describe('Filter customer data by app type.'), +}) + +/** + * Upsert customer app data. + * @summary Upsert customer app data + */ +export const upsertCustomerAppDataPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const upsertCustomerAppDataPathCustomerIdOrKeyTwoMax = 256 + +export const UpsertCustomerAppDataParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(upsertCustomerAppDataPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(upsertCustomerAppDataPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const upsertCustomerAppDataBodyOneIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const upsertCustomerAppDataBodyTwoAppOneIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const upsertCustomerAppDataBodyTwoAppOneNameMax = 256 + +export const upsertCustomerAppDataBodyTwoAppOneDescriptionMax = 1024 + +export const upsertCustomerAppDataBodyTwoAppOneListingOneCapabilitiesItemKeyMax = 64 + +export const upsertCustomerAppDataBodyTwoAppOneListingOneCapabilitiesItemKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const upsertCustomerAppDataBodyTwoIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const upsertCustomerAppDataBodyThreeAppOneIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const upsertCustomerAppDataBodyThreeAppOneNameMax = 256 + +export const upsertCustomerAppDataBodyThreeAppOneDescriptionMax = 1024 + +export const upsertCustomerAppDataBodyThreeAppOneListingOneCapabilitiesItemKeyMax = 64 + +export const upsertCustomerAppDataBodyThreeAppOneListingOneCapabilitiesItemKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const upsertCustomerAppDataBodyThreeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpsertCustomerAppDataBodyItem = zod + .union([ + zod + .object({ + id: zod.coerce + .string() + .regex(upsertCustomerAppDataBodyOneIdRegExp) + .optional() + .describe( + 'The app ID.\nIf not provided, it will use the global default for the app type.', + ), + stripeCustomerId: zod.coerce + .string() + .describe('The Stripe customer ID.'), + stripeDefaultPaymentMethodId: zod.coerce + .string() + .optional() + .describe('The Stripe default payment method ID.'), + type: zod.enum(['stripe']).describe('The app name.'), + }) + .describe('Stripe Customer App Data.'), + zod + .object({ + app: zod + .object({ + createdAt: zod.coerce + .date() + .describe('Timestamp of when the resource was created.'), + deletedAt: zod.coerce + .date() + .optional() + .describe( + 'Timestamp of when the resource was permanently deleted.', + ), + description: zod.coerce + .string() + .max(upsertCustomerAppDataBodyTwoAppOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + id: zod.coerce + .string() + .regex(upsertCustomerAppDataBodyTwoAppOneIdRegExp) + .describe('A unique identifier for the resource.'), + listing: zod + .object({ + capabilities: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .describe('The capability description.'), + key: zod.coerce + .string() + .min(1) + .max( + upsertCustomerAppDataBodyTwoAppOneListingOneCapabilitiesItemKeyMax, + ) + .regex( + upsertCustomerAppDataBodyTwoAppOneListingOneCapabilitiesItemKeyRegExp, + ) + .describe('Key'), + name: zod.coerce + .string() + .describe('The capability name.'), + type: zod + .enum([ + 'reportUsage', + 'reportEvents', + 'calculateTax', + 'invoiceCustomers', + 'collectPayments', + ]) + .describe('App capability type.') + .describe('The capability type.'), + }) + .describe( + "App capability.\n\nCapabilities only exist in config so they don't extend the Resource model.", + ), + ) + .describe("The app's capabilities."), + description: zod.coerce + .string() + .describe("The app's description."), + installMethods: zod + .array( + zod + .enum([ + 'with_oauth2', + 'with_api_key', + 'no_credentials_required', + ]) + .describe('Install method of the application.'), + ) + .describe( + 'Install methods.\n\nList of methods to install the app.', + ), + name: zod.coerce.string().describe("The app's name."), + type: zod + .enum(['stripe', 'sandbox', 'custom_invoicing']) + .describe('Type of the app.') + .describe("The app's type"), + }) + .describe( + "A marketplace listing.\nRepresent an available app in the app marketplace that can be installed to the organization.\n\nMarketplace apps only exist in config so they don't extend the Resource model.", + ) + .describe( + 'The marketplace listing that this installed app is based on.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(upsertCustomerAppDataBodyTwoAppOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + status: zod + .enum(['ready', 'unauthorized']) + .describe('App installed status.') + .describe('Status of the app connection.'), + type: zod.enum(['sandbox']).describe("The app's type is Sandbox."), + updatedAt: zod.coerce + .date() + .describe('Timestamp of when the resource was last updated.'), + }) + .describe( + 'Sandbox app can be used for testing OpenMeter features.\n\nThe app is not creating anything in external systems, thus it is safe to use for\nverifying OpenMeter features.', + ) + .optional() + .describe('The installed sandbox app this data belongs to.'), + id: zod.coerce + .string() + .regex(upsertCustomerAppDataBodyTwoIdRegExp) + .optional() + .describe( + 'The app ID.\nIf not provided, it will use the global default for the app type.', + ), + type: zod.enum(['sandbox']).describe('The app name.'), + }) + .describe('Sandbox Customer App Data.'), + zod + .object({ + app: zod + .object({ + createdAt: zod.coerce + .date() + .describe('Timestamp of when the resource was created.'), + deletedAt: zod.coerce + .date() + .optional() + .describe( + 'Timestamp of when the resource was permanently deleted.', + ), + description: zod.coerce + .string() + .max(upsertCustomerAppDataBodyThreeAppOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + enableDraftSyncHook: zod.coerce + .boolean() + .describe( + 'Enable draft.sync hook.\n\nIf the hook is not enabled, the invoice will be progressed to the next state automatically.', + ), + enableIssuingSyncHook: zod.coerce + .boolean() + .describe( + 'Enable issuing.sync hook.\n\nIf the hook is not enabled, the invoice will be progressed to the next state automatically.', + ), + id: zod.coerce + .string() + .regex(upsertCustomerAppDataBodyThreeAppOneIdRegExp) + .describe('A unique identifier for the resource.'), + listing: zod + .object({ + capabilities: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .describe('The capability description.'), + key: zod.coerce + .string() + .min(1) + .max( + upsertCustomerAppDataBodyThreeAppOneListingOneCapabilitiesItemKeyMax, + ) + .regex( + upsertCustomerAppDataBodyThreeAppOneListingOneCapabilitiesItemKeyRegExp, + ) + .describe('Key'), + name: zod.coerce + .string() + .describe('The capability name.'), + type: zod + .enum([ + 'reportUsage', + 'reportEvents', + 'calculateTax', + 'invoiceCustomers', + 'collectPayments', + ]) + .describe('App capability type.') + .describe('The capability type.'), + }) + .describe( + "App capability.\n\nCapabilities only exist in config so they don't extend the Resource model.", + ), + ) + .describe("The app's capabilities."), + description: zod.coerce + .string() + .describe("The app's description."), + installMethods: zod + .array( + zod + .enum([ + 'with_oauth2', + 'with_api_key', + 'no_credentials_required', + ]) + .describe('Install method of the application.'), + ) + .describe( + 'Install methods.\n\nList of methods to install the app.', + ), + name: zod.coerce.string().describe("The app's name."), + type: zod + .enum(['stripe', 'sandbox', 'custom_invoicing']) + .describe('Type of the app.') + .describe("The app's type"), + }) + .describe( + "A marketplace listing.\nRepresent an available app in the app marketplace that can be installed to the organization.\n\nMarketplace apps only exist in config so they don't extend the Resource model.", + ) + .describe( + 'The marketplace listing that this installed app is based on.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(upsertCustomerAppDataBodyThreeAppOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + status: zod + .enum(['ready', 'unauthorized']) + .describe('App installed status.') + .describe('Status of the app connection.'), + type: zod + .enum(['custom_invoicing']) + .describe("The app's type is CustomInvoicing."), + updatedAt: zod.coerce + .date() + .describe('Timestamp of when the resource was last updated.'), + }) + .describe( + 'Custom Invoicing app can be used for interface with any invoicing or payment system.\n\nThis app provides ways to manipulate invoices and payments, however the integration\nmust rely on Notifications API to get notified about invoice changes.', + ) + .optional() + .describe('The installed custom invoicing app this data belongs to.'), + id: zod.coerce + .string() + .regex(upsertCustomerAppDataBodyThreeIdRegExp) + .optional() + .describe( + 'The app ID.\nIf not provided, it will use the global default for the app type.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Metadata to be used by the custom invoicing provider.'), + type: zod.enum(['custom_invoicing']).describe('The app name.'), + }) + .describe('Custom Invoicing Customer App Data.'), + ]) + .describe( + 'CustomerAppData\nStores the app specific data for the customer.\nOne of: stripe, sandbox, custom_invoicing', + ) +export const UpsertCustomerAppDataBody = zod.array( + UpsertCustomerAppDataBodyItem, +) + +/** + * Delete customer app data. + * @summary Delete customer app data + */ +export const deleteCustomerAppDataPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const deleteCustomerAppDataPathCustomerIdOrKeyTwoMax = 256 + +export const deleteCustomerAppDataPathAppIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteCustomerAppDataParams = zod.object({ + appId: zod.coerce.string().regex(deleteCustomerAppDataPathAppIdRegExp), + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(deleteCustomerAppDataPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(deleteCustomerAppDataPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +/** + * Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + * @summary Get customer entitlement value + */ +export const getCustomerEntitlementValuePathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerEntitlementValuePathCustomerIdOrKeyTwoMax = 256 + +export const getCustomerEntitlementValuePathFeatureKeyMax = 64 + +export const getCustomerEntitlementValuePathFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ + +export const GetCustomerEntitlementValueParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerEntitlementValuePathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementValuePathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + featureKey: zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementValuePathFeatureKeyMax) + .regex(getCustomerEntitlementValuePathFeatureKeyRegExp), +}) + +export const GetCustomerEntitlementValueQueryParams = zod.object({ + time: zod.coerce.date().optional(), +}) + +/** + * Get stripe app data for a customer. + * Only returns data if the customer billing profile is linked to a stripe app. + * @summary Get customer stripe app data + */ +export const getCustomerStripeAppDataPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerStripeAppDataPathCustomerIdOrKeyTwoMax = 256 + +export const GetCustomerStripeAppDataParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerStripeAppDataPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerStripeAppDataPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +/** + * Upsert stripe app data for a customer. + * Only updates data if the customer billing profile is linked to a stripe app. + * @summary Upsert customer stripe app data + */ +export const upsertCustomerStripeAppDataPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const upsertCustomerStripeAppDataPathCustomerIdOrKeyTwoMax = 256 + +export const UpsertCustomerStripeAppDataParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(upsertCustomerStripeAppDataPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(upsertCustomerStripeAppDataPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const UpsertCustomerStripeAppDataBody = zod + .object({ + stripeCustomerId: zod.coerce.string().describe('The Stripe customer ID.'), + stripeDefaultPaymentMethodId: zod.coerce + .string() + .optional() + .describe('The Stripe default payment method ID.'), + }) + .describe('Stripe Customer App Data Base.') + +/** + * Create Stripe customer portal session. + * Only returns URL if the customer billing profile is linked to a stripe app and customer. + * + * Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + * change their billing address and access their invoice history. + * @summary Create Stripe customer portal session + */ +export const createCustomerStripePortalSessionPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createCustomerStripePortalSessionPathCustomerIdOrKeyTwoMax = 256 + +export const CreateCustomerStripePortalSessionParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(createCustomerStripePortalSessionPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(createCustomerStripePortalSessionPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const CreateCustomerStripePortalSessionBody = zod + .object({ + configurationId: zod.coerce + .string() + .optional() + .describe( + 'The ID of an existing configuration to use for this session,\ndescribing its functionality and features.\nIf not specified, the session uses the default configuration.\n\nSee https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration', + ), + locale: zod.coerce + .string() + .optional() + .describe( + 'The IETF language tag of the locale customer portal is displayed in.\nIf blank or auto, the customer’s preferred_locales or browser’s locale is used.\n\nSee: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale', + ), + returnUrl: zod.coerce + .string() + .optional() + .describe( + 'The URL to redirect the customer to after they have completed\ntheir requested actions.\n\nSee: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url', + ), + }) + .describe('Stripe customer portal request params.') + +/** + * Lists all subscriptions for a customer. + * @summary List customer subscriptions + */ +export const listCustomerSubscriptionsPathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listCustomerSubscriptionsPathCustomerIdOrKeyTwoMax = 256 + +export const ListCustomerSubscriptionsParams = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(listCustomerSubscriptionsPathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(listCustomerSubscriptionsPathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const listCustomerSubscriptionsQueryOrderDefault = 'ASC' +export const listCustomerSubscriptionsQueryPageDefault = 1 + +export const listCustomerSubscriptionsQueryPageSizeDefault = 100 +export const listCustomerSubscriptionsQueryPageSizeMax = 1000 + +export const ListCustomerSubscriptionsQueryParams = zod.object({ + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listCustomerSubscriptionsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['activeFrom', 'activeTo']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listCustomerSubscriptionsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listCustomerSubscriptionsQueryPageSizeMax) + .default(listCustomerSubscriptionsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + status: zod + .array( + zod + .enum(['active', 'inactive', 'canceled', 'scheduled']) + .describe('Subscription status.'), + ) + .optional(), +}) + +/** + * List all entitlements for all the subjects and features. This endpoint is intended for administrative purposes only. + * To fetch the entitlements of a specific subject please use the /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements`](#tag/entitlements/get/api/v2/entitlements) instead. + * @deprecated + * @summary List all entitlements + */ +export const listEntitlementsQueryExcludeInactiveDefault = false +export const listEntitlementsQueryPageDefault = 1 + +export const listEntitlementsQueryPageSizeDefault = 100 +export const listEntitlementsQueryPageSizeMax = 1000 + +export const listEntitlementsQueryOffsetDefault = 0 +export const listEntitlementsQueryOffsetMin = 0 + +export const listEntitlementsQueryLimitDefault = 100 +export const listEntitlementsQueryLimitMax = 1000 + +export const listEntitlementsQueryOrderDefault = 'ASC' + +export const ListEntitlementsQueryParams = zod.object({ + entitlementType: zod + .array( + zod + .enum(['metered', 'boolean', 'static']) + .describe('Type of the entitlement.'), + ) + .optional() + .describe( + 'Filtering by multiple entitlement types.\n\nUsage: `?entitlementType=metered&entitlementType=boolean`', + ), + excludeInactive: zod.coerce + .boolean() + .default(listEntitlementsQueryExcludeInactiveDefault) + .describe( + 'Exclude inactive entitlements in the response (those scheduled for later or earlier)', + ), + feature: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple features.\n\nUsage: `?feature=feature-1&feature=feature-2`', + ), + limit: zod.coerce + .number() + .min(1) + .max(listEntitlementsQueryLimitMax) + .default(listEntitlementsQueryLimitDefault) + .describe('Number of items to return.\n\nDefault is 100.'), + offset: zod.coerce + .number() + .min(listEntitlementsQueryOffsetMin) + .default(listEntitlementsQueryOffsetDefault) + .describe('Number of items to skip.\n\nDefault is 0.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listEntitlementsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listEntitlementsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listEntitlementsQueryPageSizeMax) + .default(listEntitlementsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + subject: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple subjects.\n\nUsage: `?subject=customer-1&subject=customer-2`', + ), +}) + +/** + * Get entitlement by ID. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements/{entitlementId}`](#tag/entitlements/get/api/v2/entitlements/{entitlementId}) instead. + * @deprecated + * @summary Get entitlement by ID + */ +export const getEntitlementByIdPathEntitlementIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetEntitlementByIdParams = zod.object({ + entitlementId: zod.coerce + .string() + .regex(getEntitlementByIdPathEntitlementIdRegExp), +}) + +/** + * List ingested events within a time range. + * + * If the from query param is not provided it defaults to last 72 hours. + * @summary List ingested events + */ +export const listEventsQueryClientIdMax = 36 + +export const listEventsQueryCustomerIdItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listEventsQueryLimitDefault = 100 +export const listEventsQueryLimitMax = 100 + +export const ListEventsQueryParams = zod.object({ + clientId: zod.coerce + .string() + .min(1) + .max(listEventsQueryClientIdMax) + .optional() + .describe('Client ID\nUseful to track progress of a query.'), + customerId: zod + .array( + zod.coerce + .string() + .regex(listEventsQueryCustomerIdItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('The event customer ID.'), + from: zod.coerce + .date() + .optional() + .describe('Start date-time in RFC 3339 format.\n\nInclusive.'), + id: zod.coerce + .string() + .optional() + .describe('The event ID.\n\nAccepts partial ID.'), + ingestedAtFrom: zod.coerce + .date() + .optional() + .describe('Start date-time in RFC 3339 format.\n\nInclusive.'), + ingestedAtTo: zod.coerce + .date() + .optional() + .describe('End date-time in RFC 3339 format.\n\nInclusive.'), + limit: zod.coerce + .number() + .min(1) + .max(listEventsQueryLimitMax) + .default(listEventsQueryLimitDefault) + .describe('Number of events to return.'), + subject: zod.coerce + .string() + .optional() + .describe('The event subject.\n\nAccepts partial subject.'), + to: zod.coerce + .date() + .optional() + .describe('End date-time in RFC 3339 format.\n\nInclusive.'), +}) + +/** + * Ingests an event or batch of events following the CloudEvents specification. + * @summary Ingest events + */ + +export const ingestEventsBodySpecversionDefault = '1.0' + +export const IngestEventsBody = zod + .object({ + data: zod + .record(zod.string(), zod.unknown()) + .nullish() + .describe( + 'The event payload.\nOptional, if present it must be a JSON object.', + ), + datacontenttype: zod + .enum(['application/json']) + .nullish() + .describe( + 'Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP.', + ), + dataschema: zod + .url() + .min(1) + .nullish() + .describe('Identifies the schema that data adheres to.'), + id: zod.coerce.string().min(1).describe('Identifies the event.'), + source: zod.coerce + .string() + .min(1) + .describe('Identifies the context in which an event happened.'), + specversion: zod.coerce + .string() + .min(1) + .default(ingestEventsBodySpecversionDefault) + .describe( + 'The version of the CloudEvents specification which the event uses.', + ), + subject: zod.coerce + .string() + .min(1) + .describe( + 'Describes the subject of the event in the context of the event producer (identified by source).', + ), + time: zod.coerce + .date() + .nullish() + .describe( + 'Timestamp of when the occurrence happened. Must adhere to RFC 3339.', + ), + type: zod.coerce + .string() + .min(1) + .describe( + 'Contains a value describing the type of event related to the originating occurrence.', + ), + }) + .describe( + 'CloudEvents Specification JSON Schema\n\nOptional properties are nullable according to the CloudEvents specification:\nOPTIONAL not omitted attributes MAY be represented as a null JSON value.', + ) + +/** + * List features. + * @summary List features + */ +export const listFeaturesQueryIncludeArchivedDefault = false +export const listFeaturesQueryPageDefault = 1 + +export const listFeaturesQueryPageSizeDefault = 100 +export const listFeaturesQueryPageSizeMax = 1000 + +export const listFeaturesQueryOffsetDefault = 0 +export const listFeaturesQueryOffsetMin = 0 + +export const listFeaturesQueryLimitDefault = 100 +export const listFeaturesQueryLimitMax = 1000 + +export const listFeaturesQueryOrderDefault = 'ASC' + +export const ListFeaturesQueryParams = zod.object({ + includeArchived: zod.coerce + .boolean() + .default(listFeaturesQueryIncludeArchivedDefault) + .describe('Include archived features in response.'), + limit: zod.coerce + .number() + .min(1) + .max(listFeaturesQueryLimitMax) + .default(listFeaturesQueryLimitDefault) + .describe('Number of items to return.\n\nDefault is 100.'), + meterSlug: zod + .array(zod.coerce.string()) + .optional() + .describe('Filter by meterSlug'), + offset: zod.coerce + .number() + .min(listFeaturesQueryOffsetMin) + .default(listFeaturesQueryOffsetDefault) + .describe('Number of items to skip.\n\nDefault is 0.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listFeaturesQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'key', 'name', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listFeaturesQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listFeaturesQueryPageSizeMax) + .default(listFeaturesQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Features are either metered or static. A feature is metered if meterSlug is provided at creation. + * For metered features you can pass additional filters that will be applied when calculating feature usage, based on the meter's groupBy fields. + * Meters with SUM, COUNT, UNIQUE_COUNT and LATEST aggregations are supported for features. + * @summary Create feature + */ +export const createFeatureBodyKeyMax = 64 + +export const createFeatureBodyKeyRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createFeatureBodyMeterSlugMax = 64 + +export const createFeatureBodyMeterSlugRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createFeatureBodyUnitCostOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createFeatureBodyUnitCostOneTwoPricingOneInputPerTokenOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createFeatureBodyUnitCostOneTwoPricingOneOutputPerTokenOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createFeatureBodyUnitCostOneTwoPricingOneCacheReadPerTokenOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createFeatureBodyUnitCostOneTwoPricingOneReasoningPerTokenOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createFeatureBodyUnitCostOneTwoPricingOneCacheWritePerTokenOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const CreateFeatureBody = zod + .object({ + advancedMeterGroupByFilters: zod + .record( + zod.string(), + zod + .object({ + $and: zod + .array(zod.unknown()) + .nullish() + .describe( + 'Provide a list of filters to be combined with a logical AND.', + ), + $eq: zod.coerce + .string() + .nullish() + .describe('The field must be equal to the provided value.'), + $gt: zod.coerce + .string() + .nullish() + .describe('The field must be greater than the provided value.'), + $gte: zod.coerce + .string() + .nullish() + .describe( + 'The field must be greater than or equal to the provided value.', + ), + $ilike: zod.coerce + .string() + .nullish() + .describe( + 'The field must match the provided value, ignoring case.', + ), + $in: zod + .array(zod.coerce.string()) + .nullish() + .describe('The field must be in the provided list of values.'), + $like: zod.coerce + .string() + .nullish() + .describe('The field must match the provided value.'), + $lt: zod.coerce + .string() + .nullish() + .describe('The field must be less than the provided value.'), + $lte: zod.coerce + .string() + .nullish() + .describe( + 'The field must be less than or equal to the provided value.', + ), + $ne: zod.coerce + .string() + .nullish() + .describe('The field must not be equal to the provided value.'), + $nilike: zod.coerce + .string() + .nullish() + .describe( + 'The field must not match the provided value, ignoring case.', + ), + $nin: zod + .array(zod.coerce.string()) + .nullish() + .describe( + 'The field must not be in the provided list of values.', + ), + $nlike: zod.coerce + .string() + .nullish() + .describe('The field must not match the provided value.'), + $or: zod + .array(zod.unknown()) + .nullish() + .describe( + 'Provide a list of filters to be combined with a logical OR.', + ), + }) + .describe('A filter for a string field.'), + ) + .optional() + .describe( + 'Optional advanced meter group by filters.\nYou can use this to filter for values of the meter groupBy fields.', + ), + key: zod.coerce + .string() + .min(1) + .max(createFeatureBodyKeyMax) + .regex(createFeatureBodyKeyRegExp) + .describe( + 'A key is a unique string that is used to identify a resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional(), + meterGroupByFilters: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe( + 'Optional meter group by filters.\nUseful if the meter scope is broader than what feature tracks.\nExample scenario would be a meter tracking all token use with groupBy fields for the model,\nthen the feature could filter for model=gpt-4.\n\n⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead', + ), + meterSlug: zod.coerce + .string() + .min(1) + .max(createFeatureBodyMeterSlugMax) + .regex(createFeatureBodyMeterSlugRegExp) + .optional() + .describe( + 'A key is a unique string that is used to identify a resource.', + ), + name: zod.coerce.string(), + unitCost: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex(createFeatureBodyUnitCostOneOneAmountOneRegExp) + .describe('Numeric represents an arbitrary precision number.') + .describe('Fixed per-unit cost amount in USD.'), + type: zod.enum(['manual']), + }) + .describe('A fixed per-unit cost amount.'), + zod + .object({ + model: zod.coerce + .string() + .optional() + .describe( + 'Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet").\nUse this when the feature tracks a single model.\nMutually exclusive with `modelProperty`.', + ), + modelProperty: zod.coerce + .string() + .optional() + .describe( + 'Meter group-by property that holds the model ID.\nUse this when the meter has a group-by dimension for model.\nMutually exclusive with `model`.', + ), + pricing: zod + .object({ + cacheReadPerToken: zod.coerce + .string() + .regex( + createFeatureBodyUnitCostOneTwoPricingOneCacheReadPerTokenOneRegExp, + ) + .describe('Numeric represents an arbitrary precision number.') + .optional() + .describe('Cost per cache read token in USD.'), + cacheWritePerToken: zod.coerce + .string() + .regex( + createFeatureBodyUnitCostOneTwoPricingOneCacheWritePerTokenOneRegExp, + ) + .describe('Numeric represents an arbitrary precision number.') + .optional() + .describe('Cost per cache write token in USD.'), + inputPerToken: zod.coerce + .string() + .regex( + createFeatureBodyUnitCostOneTwoPricingOneInputPerTokenOneRegExp, + ) + .describe('Numeric represents an arbitrary precision number.') + .describe('Cost per input token in USD.'), + outputPerToken: zod.coerce + .string() + .regex( + createFeatureBodyUnitCostOneTwoPricingOneOutputPerTokenOneRegExp, + ) + .describe('Numeric represents an arbitrary precision number.') + .describe('Cost per output token in USD.'), + reasoningPerToken: zod.coerce + .string() + .regex( + createFeatureBodyUnitCostOneTwoPricingOneReasoningPerTokenOneRegExp, + ) + .describe('Numeric represents an arbitrary precision number.') + .optional() + .describe('Cost per reasoning token in USD.'), + }) + .describe( + 'Resolved per-token pricing from the LLM cost database.', + ) + .optional() + .describe( + "Resolved per-token pricing from the LLM cost database.\nOnly populated in responses when the feature's meter group-by filters\nspecify exact provider and model values.", + ), + provider: zod.coerce + .string() + .optional() + .describe( + 'Static LLM provider value (e.g., "openai", "anthropic").\nUse this when the feature tracks a single provider.\nMutually exclusive with `providerProperty`.', + ), + providerProperty: zod.coerce + .string() + .optional() + .describe( + 'Meter group-by property that holds the LLM provider.\nUse this when the meter has a group-by dimension for provider.\nMutually exclusive with `provider`.', + ), + tokenType: zod.coerce + .string() + .optional() + .describe( + 'Static token type value.\nUse this when the feature tracks a single token type (e.g., only input tokens).\nExpected values: input, output, cache_read, reasoning, cache_write, request, response.\n`request` is an alias for `input`, `response` is an alias for `output`.\nMutually exclusive with `tokenTypeProperty`.', + ), + tokenTypeProperty: zod.coerce + .string() + .optional() + .describe( + 'Meter group-by property that holds the token type.\nUse this when the meter has a group-by dimension for token type.\nMutually exclusive with `tokenType`.', + ), + type: zod.enum(['llm']), + }) + .describe( + 'LLM cost lookup configuration.\nMaps meter group-by dimensions to LLM cost database fields.', + ), + ]) + .describe( + 'Per-unit cost configuration for a feature.\nEither a fixed manual amount or a dynamic LLM cost lookup.', + ) + .optional() + .describe( + 'Optional per-unit cost configuration.\nUse "manual" for a fixed per-unit cost, or "llm" to look up cost\nfrom the LLM cost database based on meter group-by properties.', + ), + }) + .describe( + 'Represents a feature that can be enabled or disabled for a plan.\nUsed both for product catalog and entitlements.', + ) + +/** + * Get a feature by ID. + * @summary Get feature + */ +export const GetFeatureParams = zod.object({ + featureId: zod.coerce.string(), +}) + +/** + * Archive a feature by ID. + * + * Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements cannot be created for it, but archiving the feature does not affect existing entitlements. + * This means, if you want to create a new feature with the same key, and then create entitlements for it, the previous entitlements have to be deleted first on a per subject basis. + * @summary Delete feature + */ +export const DeleteFeatureParams = zod.object({ + featureId: zod.coerce.string(), +}) + +/** + * List all grants for all the subjects and entitlements. This endpoint is intended for administrative purposes only. + * To fetch the grants of a specific entitlement please use the /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/grants`](#tag/entitlements/get/api/v2/grants) instead. + * @deprecated + * @summary List grants + */ +export const listGrantsQueryIncludeDeletedDefault = false +export const listGrantsQueryPageDefault = 1 + +export const listGrantsQueryPageSizeDefault = 100 +export const listGrantsQueryPageSizeMax = 1000 + +export const listGrantsQueryOffsetDefault = 0 +export const listGrantsQueryOffsetMin = 0 + +export const listGrantsQueryLimitDefault = 100 +export const listGrantsQueryLimitMax = 1000 + +export const listGrantsQueryOrderDefault = 'ASC' + +export const ListGrantsQueryParams = zod.object({ + feature: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple features.\n\nUsage: `?feature=feature-1&feature=feature-2`', + ), + includeDeleted: zod.coerce + .boolean() + .default(listGrantsQueryIncludeDeletedDefault) + .describe('Include deleted'), + limit: zod.coerce + .number() + .min(1) + .max(listGrantsQueryLimitMax) + .default(listGrantsQueryLimitDefault) + .describe('Number of items to return.\n\nDefault is 100.'), + offset: zod.coerce + .number() + .min(listGrantsQueryOffsetMin) + .default(listGrantsQueryOffsetDefault) + .describe('Number of items to skip.\n\nDefault is 0.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listGrantsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listGrantsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listGrantsQueryPageSizeMax) + .default(listGrantsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + subject: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple subjects.\n\nUsage: `?subject=customer-1&subject=customer-2`', + ), +}) + +/** + * Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed to the grant will remain, but future usage cannot be burnt down from the grant. + * For example, if you have a single grant for your metered entitlement with an initial amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous usage will not be affected. + * @summary Void grant + */ +export const VoidGrantParams = zod.object({ + grantId: zod.coerce.string(), +}) + +export const VoidGrantQueryParams = zod.object({ + at: zod.coerce + .date() + .optional() + .describe( + 'The time at which the grant should be voided.\nMust not be in the future and must be within the current usage period of the entitlement.\nDefaults to the current time if not specified.', + ), +}) + +/** + * Get progress + * @summary Get progress + */ +export const GetProgressParams = zod.object({ + id: zod.coerce.string(), +}) + +/** + * List available apps of the app marketplace. + * @summary List available apps + */ +export const listMarketplaceListingsQueryPageDefault = 1 + +export const listMarketplaceListingsQueryPageSizeDefault = 100 +export const listMarketplaceListingsQueryPageSizeMax = 1000 + +export const ListMarketplaceListingsQueryParams = zod.object({ + page: zod.coerce + .number() + .min(1) + .default(listMarketplaceListingsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listMarketplaceListingsQueryPageSizeMax) + .default(listMarketplaceListingsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Get a marketplace listing by type. + * @summary Get app details by type + */ +export const GetMarketplaceListingParams = zod.object({ + type: zod.enum(['stripe', 'sandbox', 'custom_invoicing']), +}) + +/** + * Install an app from the marketplace. + * @summary Install app + */ +export const MarketplaceAppInstallParams = zod.object({ + type: zod + .enum(['stripe', 'sandbox', 'custom_invoicing']) + .describe('The type of the app to install.'), +}) + +export const marketplaceAppInstallBodyCreateBillingProfileDefault = true + +export const MarketplaceAppInstallBody = zod + .object({ + createBillingProfile: zod.coerce + .boolean() + .default(marketplaceAppInstallBodyCreateBillingProfileDefault) + .describe( + 'If true, a billing profile will be created for the app.\nThe Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + name: zod.coerce + .string() + .optional() + .describe( + "Name of the application to install.\n\nIf name is not provided defaults to the marketplace listing's name.", + ), + }) + .describe('Marketplace install request payload.') + +/** + * Install an marketplace app via API Key. + * @summary Install app via API key + */ +export const MarketplaceAppAPIKeyInstallParams = zod.object({ + type: zod + .enum(['stripe', 'sandbox', 'custom_invoicing']) + .describe('The type of the app to install.'), +}) + +export const marketplaceAppAPIKeyInstallBodyCreateBillingProfileDefault = true + +export const MarketplaceAppAPIKeyInstallBody = zod.object({ + apiKey: zod.coerce + .string() + .describe( + 'The API key for the provider.\nFor example, the Stripe API key.', + ), + createBillingProfile: zod.coerce + .boolean() + .default(marketplaceAppAPIKeyInstallBodyCreateBillingProfileDefault) + .describe( + 'If true, a billing profile will be created for the app.\nThe Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + name: zod.coerce + .string() + .optional() + .describe( + "Name of the application to install.\n\nIf name is not provided defaults to the marketplace listing's name.", + ), +}) + +/** + * Install an app via OAuth. + * Returns a URL to start the OAuth 2.0 flow. + * @summary Get OAuth2 install URL + */ +export const MarketplaceOAuth2InstallGetURLParams = zod.object({ + type: zod.enum(['stripe', 'sandbox', 'custom_invoicing']), +}) + +/** + * Authorize OAuth2 code. + * Verifies the OAuth code and exchanges it for a token and refresh token + * @summary Install app via OAuth2 + */ +export const MarketplaceOAuth2InstallAuthorizeParams = zod.object({ + type: zod + .enum(['stripe', 'sandbox', 'custom_invoicing']) + .describe('The type of the app to install.'), +}) + +export const MarketplaceOAuth2InstallAuthorizeQueryParams = zod.object({ + code: zod.coerce + .string() + .optional() + .describe( + 'Authorization code which the client will later exchange for an access token.\nRequired with the success response.', + ), + error: zod + .enum([ + 'invalid_request', + 'unauthorized_client', + 'access_denied', + 'unsupported_response_type', + 'invalid_scope', + 'server_error', + 'temporarily_unavailable', + ]) + .optional() + .describe('Error code.\nRequired with the error response.'), + error_description: zod.coerce + .string() + .optional() + .describe( + 'Optional human-readable text providing additional information,\nused to assist the client developer in understanding the error that occurred.', + ), + error_uri: zod.coerce + .string() + .optional() + .describe( + 'Optional uri identifying a human-readable web page with\ninformation about the error, used to provide the client\ndeveloper with additional information about the error', + ), + state: zod.coerce + .string() + .optional() + .describe( + 'Required if the "state" parameter was present in the client authorization request.\nThe exact value received from the client:\n\nUnique, randomly generated, opaque, and non-guessable string that is sent\nwhen starting an authentication request and validated when processing the response.', + ), +}) + +/** + * List meters. + * @summary List meters + */ +export const listMetersQueryPageDefault = 1 + +export const listMetersQueryPageSizeDefault = 100 +export const listMetersQueryPageSizeMax = 1000 + +export const listMetersQueryOrderDefault = 'ASC' +export const listMetersQueryIncludeDeletedDefault = false + +export const ListMetersQueryParams = zod.object({ + includeDeleted: zod.coerce + .boolean() + .default(listMetersQueryIncludeDeletedDefault) + .describe('Include deleted meters.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listMetersQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['key', 'name', 'aggregation', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listMetersQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listMetersQueryPageSizeMax) + .default(listMetersQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Create a meter. + * @summary Create meter + */ +export const createMeterBodyDescriptionMax = 1024 + +export const createMeterBodyNameMax = 256 + +export const createMeterBodySlugMax = 64 + +export const createMeterBodySlugRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ + +export const CreateMeterBody = zod + .object({ + aggregation: zod + .enum(['SUM', 'COUNT', 'UNIQUE_COUNT', 'AVG', 'MIN', 'MAX', 'LATEST']) + .describe('The aggregation type to use for the meter.') + .describe('The aggregation type to use for the meter.'), + description: zod.coerce + .string() + .max(createMeterBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + eventFrom: zod.coerce + .date() + .optional() + .describe( + 'The date since the meter should include events.\nUseful to skip old events.\nIf not specified, all historical events are included.', + ), + eventType: zod.coerce + .string() + .min(1) + .describe('The event type to aggregate.'), + groupBy: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe( + 'Named JSONPath expressions to extract the group by values from the event data.\n\nKeys must be unique and consist only alphanumeric and underscore characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createMeterBodyNameMax) + .optional() + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.\nDefaults to the slug if not specified.', + ), + slug: zod.coerce + .string() + .min(1) + .max(createMeterBodySlugMax) + .regex(createMeterBodySlugRegExp) + .describe( + 'A unique, human-readable identifier for the meter.\nMust consist only alphanumeric and underscore characters.', + ), + valueProperty: zod.coerce + .string() + .min(1) + .optional() + .describe( + "JSONPath expression to extract the value from the ingested event's data property.\n\nThe ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number.\n\nFor UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored.", + ), + }) + .describe('A meter create model.') + +/** + * Get a meter by ID or slug. + * @summary Get meter + */ +export const getMeterPathMeterIdOrSlugMax = 64 + +export const getMeterPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetMeterParams = zod.object({ + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(getMeterPathMeterIdOrSlugMax) + .regex(getMeterPathMeterIdOrSlugRegExp), +}) + +/** + * Update a meter. + * @summary Update meter + */ +export const updateMeterPathMeterIdOrSlugMax = 64 + +export const updateMeterPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateMeterParams = zod.object({ + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(updateMeterPathMeterIdOrSlugMax) + .regex(updateMeterPathMeterIdOrSlugRegExp), +}) + +export const updateMeterBodyDescriptionMax = 1024 + +export const updateMeterBodyNameMax = 256 + +export const UpdateMeterBody = zod + .object({ + description: zod.coerce + .string() + .max(updateMeterBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + groupBy: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe( + 'Named JSONPath expressions to extract the group by values from the event data.\n\nKeys must be unique and consist only alphanumeric and underscore characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateMeterBodyNameMax) + .optional() + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.\nDefaults to the slug if not specified.', + ), + }) + .describe( + 'A meter update model.\n\nOnly the properties that can be updated are included.\nFor example, the slug and aggregation cannot be updated.', + ) + +/** + * Delete a meter. + * @summary Delete meter + */ +export const deleteMeterPathMeterIdOrSlugMax = 64 + +export const deleteMeterPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteMeterParams = zod.object({ + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(deleteMeterPathMeterIdOrSlugMax) + .regex(deleteMeterPathMeterIdOrSlugRegExp), +}) + +/** + * List meter group by values. + * @summary List meter group by values + */ +export const listMeterGroupByValuesPathMeterIdOrSlugMax = 64 + +export const listMeterGroupByValuesPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ListMeterGroupByValuesParams = zod.object({ + groupByKey: zod.coerce.string(), + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(listMeterGroupByValuesPathMeterIdOrSlugMax) + .regex(listMeterGroupByValuesPathMeterIdOrSlugRegExp), +}) + +export const ListMeterGroupByValuesQueryParams = zod.object({ + from: zod.coerce + .date() + .optional() + .describe( + 'Start date-time in RFC 3339 format.\n\nInclusive. Defaults to 24 hours ago.\n\nFor example: ?from=2025-01-01T00%3A00%3A00.000Z', + ), + to: zod.coerce + .date() + .optional() + .describe( + 'End date-time in RFC 3339 format.\n\nInclusive.\n\nFor example: ?to=2025-02-01T00%3A00%3A00.000Z', + ), +}) + +/** + * Query meter for usage. + * @summary Query meter + */ +export const queryMeterPathMeterIdOrSlugMax = 64 + +export const queryMeterPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const QueryMeterParams = zod.object({ + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(queryMeterPathMeterIdOrSlugMax) + .regex(queryMeterPathMeterIdOrSlugRegExp), +}) + +export const queryMeterQueryClientIdMax = 36 + +export const queryMeterQueryWindowTimeZoneDefault = 'UTC' +export const queryMeterQueryFilterCustomerIdMax = 100 + +export const QueryMeterQueryParams = zod.object({ + clientId: zod.coerce + .string() + .min(1) + .max(queryMeterQueryClientIdMax) + .optional() + .describe('Client ID\nUseful to track progress of a query.'), + filterCustomerId: zod + .array(zod.coerce.string()) + .max(queryMeterQueryFilterCustomerIdMax) + .optional() + .describe( + 'Filtering by multiple customers.\n\nFor example: ?filterCustomerId=customer-1&filterCustomerId=customer-2', + ), + filterGroupBy: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe( + 'Simple filter for group bys with exact match.\n\nFor example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo\n\n⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead', + ), + from: zod.coerce + .date() + .optional() + .describe( + 'Start date-time in RFC 3339 format.\n\nInclusive.\n\nFor example: ?from=2025-01-01T00%3A00%3A00.000Z', + ), + groupBy: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'If not specified a single aggregate will be returned for each subject and time window.\n`subject` is a reserved group by value.\n\nFor example: ?groupBy=subject&groupBy=model', + ), + subject: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple subjects.\n\nFor example: ?subject=subject-1&subject=subject-2', + ), + to: zod.coerce + .date() + .optional() + .describe( + 'End date-time in RFC 3339 format.\n\nInclusive.\n\nFor example: ?to=2025-02-01T00%3A00%3A00.000Z', + ), + windowSize: zod + .enum(['MINUTE', 'HOUR', 'DAY', 'MONTH']) + .optional() + .describe( + 'If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group.\n\nFor example: ?windowSize=DAY', + ), + windowTimeZone: zod.coerce + .string() + .default(queryMeterQueryWindowTimeZoneDefault) + .describe( + 'The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones).\nIf not specified, the UTC timezone will be used.\n\nFor example: ?windowTimeZone=UTC', + ), +}) + +/** + * @summary Query meter + */ +export const queryMeterPostPathMeterIdOrSlugMax = 64 + +export const queryMeterPostPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const QueryMeterPostParams = zod.object({ + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(queryMeterPostPathMeterIdOrSlugMax) + .regex(queryMeterPostPathMeterIdOrSlugRegExp), +}) + +export const queryMeterPostBodyClientIdMax = 36 + +export const queryMeterPostBodyWindowTimeZoneDefault = 'UTC' +export const queryMeterPostBodySubjectMax = 100 + +export const queryMeterPostBodyFilterCustomerIdMax = 100 + +export const queryMeterPostBodyGroupByMax = 100 + +export const QueryMeterPostBody = zod + .object({ + advancedMeterGroupByFilters: zod + .record( + zod.string(), + zod + .object({ + $and: zod + .array(zod.unknown()) + .nullish() + .describe( + 'Provide a list of filters to be combined with a logical AND.', + ), + $eq: zod.coerce + .string() + .nullish() + .describe('The field must be equal to the provided value.'), + $gt: zod.coerce + .string() + .nullish() + .describe('The field must be greater than the provided value.'), + $gte: zod.coerce + .string() + .nullish() + .describe( + 'The field must be greater than or equal to the provided value.', + ), + $ilike: zod.coerce + .string() + .nullish() + .describe( + 'The field must match the provided value, ignoring case.', + ), + $in: zod + .array(zod.coerce.string()) + .nullish() + .describe('The field must be in the provided list of values.'), + $like: zod.coerce + .string() + .nullish() + .describe('The field must match the provided value.'), + $lt: zod.coerce + .string() + .nullish() + .describe('The field must be less than the provided value.'), + $lte: zod.coerce + .string() + .nullish() + .describe( + 'The field must be less than or equal to the provided value.', + ), + $ne: zod.coerce + .string() + .nullish() + .describe('The field must not be equal to the provided value.'), + $nilike: zod.coerce + .string() + .nullish() + .describe( + 'The field must not match the provided value, ignoring case.', + ), + $nin: zod + .array(zod.coerce.string()) + .nullish() + .describe( + 'The field must not be in the provided list of values.', + ), + $nlike: zod.coerce + .string() + .nullish() + .describe('The field must not match the provided value.'), + $or: zod + .array(zod.unknown()) + .nullish() + .describe( + 'Provide a list of filters to be combined with a logical OR.', + ), + }) + .describe('A filter for a string field.'), + ) + .optional() + .describe( + 'Optional advanced meter group by filters.\nYou can use this to filter for values of the meter groupBy fields.', + ), + clientId: zod.coerce + .string() + .min(1) + .max(queryMeterPostBodyClientIdMax) + .optional() + .describe('Client ID\nUseful to track progress of a query.'), + filterCustomerId: zod + .array(zod.coerce.string()) + .max(queryMeterPostBodyFilterCustomerIdMax) + .optional() + .describe('Filtering by multiple customers.'), + filterGroupBy: zod + .record(zod.string(), zod.array(zod.coerce.string())) + .optional() + .describe('Simple filter for group bys with exact match.'), + from: zod.coerce + .date() + .optional() + .describe('Start date-time in RFC 3339 format.\n\nInclusive.'), + groupBy: zod + .array(zod.coerce.string()) + .max(queryMeterPostBodyGroupByMax) + .optional() + .describe( + 'If not specified a single aggregate will be returned for each subject and time window.\n`subject` is a reserved group by value.', + ), + subject: zod + .array(zod.coerce.string()) + .max(queryMeterPostBodySubjectMax) + .optional() + .describe('Filtering by multiple subjects.'), + to: zod.coerce + .date() + .optional() + .describe('End date-time in RFC 3339 format.\n\nInclusive.'), + windowSize: zod + .enum(['MINUTE', 'HOUR', 'DAY', 'MONTH']) + .describe('Aggregation window size.') + .optional() + .describe( + 'If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group.', + ), + windowTimeZone: zod.coerce + .string() + .default(queryMeterPostBodyWindowTimeZoneDefault) + .describe( + 'The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones).\nIf not specified, the UTC timezone will be used.', + ), + }) + .describe('A meter query request.') + +/** + * List subjects for a meter. + * @summary List meter subjects + */ +export const listMeterSubjectsPathMeterIdOrSlugMax = 64 + +export const listMeterSubjectsPathMeterIdOrSlugRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ListMeterSubjectsParams = zod.object({ + meterIdOrSlug: zod.coerce + .string() + .min(1) + .max(listMeterSubjectsPathMeterIdOrSlugMax) + .regex(listMeterSubjectsPathMeterIdOrSlugRegExp), +}) + +export const ListMeterSubjectsQueryParams = zod.object({ + from: zod.coerce + .date() + .optional() + .describe( + 'Start date-time in RFC 3339 format.\n\nInclusive. Defaults to the beginning of time.\n\nFor example: ?from=2025-01-01T00%3A00%3A00.000Z', + ), + to: zod.coerce + .date() + .optional() + .describe( + 'End date-time in RFC 3339 format.\n\nInclusive.\n\nFor example: ?to=2025-02-01T00%3A00%3A00.000Z', + ), +}) + +/** + * List all notification channels. + * @summary List notification channels + */ +export const listNotificationChannelsQueryIncludeDeletedDefault = false +export const listNotificationChannelsQueryIncludeDisabledDefault = false +export const listNotificationChannelsQueryPageDefault = 1 + +export const listNotificationChannelsQueryPageSizeDefault = 100 +export const listNotificationChannelsQueryPageSizeMax = 1000 + +export const listNotificationChannelsQueryOrderDefault = 'ASC' + +export const ListNotificationChannelsQueryParams = zod.object({ + includeDeleted: zod.coerce + .boolean() + .default(listNotificationChannelsQueryIncludeDeletedDefault) + .describe( + 'Include deleted notification channels in response.\n\nUsage: `?includeDeleted=true`', + ), + includeDisabled: zod.coerce + .boolean() + .default(listNotificationChannelsQueryIncludeDisabledDefault) + .describe( + 'Include disabled notification channels in response.\n\nUsage: `?includeDisabled=false`', + ), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listNotificationChannelsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'type', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listNotificationChannelsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listNotificationChannelsQueryPageSizeMax) + .default(listNotificationChannelsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Create a new notification channel. + * @summary Create a notification channel + */ +export const createNotificationChannelBodyOneNameMax = 256 + +export const createNotificationChannelBodyOneDisabledDefault = false +export const createNotificationChannelBodyOneSigningSecretRegExp = + /^(whsec_)?[a-zA-Z0-9+/=]{32,100}$/ + +export const CreateNotificationChannelBody = zod + .object({ + customHeaders: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe('Custom HTTP headers sent as part of the webhook request.'), + disabled: zod.coerce + .boolean() + .default(createNotificationChannelBodyOneDisabledDefault) + .describe('Whether the channel is disabled or not.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createNotificationChannelBodyOneNameMax) + .describe('User friendly name of the channel.'), + signingSecret: zod.coerce + .string() + .regex(createNotificationChannelBodyOneSigningSecretRegExp) + .optional() + .describe( + 'Signing secret used for webhook request validation on the receiving end.\n\nFormat: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24', + ), + type: zod.enum(['WEBHOOK']).describe('Notification channel type.'), + url: zod.coerce + .string() + .describe('Webhook URL where the notification is sent.'), + }) + .describe( + 'Request with input parameters for creating new notification channel with webhook type.', + ) + .describe( + 'Union type for requests creating new notification channel with certain type.', + ) + +/** + * Update notification channel. + * @summary Update a notification channel + */ +export const updateNotificationChannelPathChannelIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateNotificationChannelParams = zod.object({ + channelId: zod.coerce + .string() + .regex(updateNotificationChannelPathChannelIdRegExp), +}) + +export const updateNotificationChannelBodyOneNameMax = 256 + +export const updateNotificationChannelBodyOneDisabledDefault = false +export const updateNotificationChannelBodyOneSigningSecretRegExp = + /^(whsec_)?[a-zA-Z0-9+/=]{32,100}$/ + +export const UpdateNotificationChannelBody = zod + .object({ + customHeaders: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe('Custom HTTP headers sent as part of the webhook request.'), + disabled: zod.coerce + .boolean() + .default(updateNotificationChannelBodyOneDisabledDefault) + .describe('Whether the channel is disabled or not.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateNotificationChannelBodyOneNameMax) + .describe('User friendly name of the channel.'), + signingSecret: zod.coerce + .string() + .regex(updateNotificationChannelBodyOneSigningSecretRegExp) + .optional() + .describe( + 'Signing secret used for webhook request validation on the receiving end.\n\nFormat: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24', + ), + type: zod.enum(['WEBHOOK']).describe('Notification channel type.'), + url: zod.coerce + .string() + .describe('Webhook URL where the notification is sent.'), + }) + .describe( + 'Request with input parameters for creating new notification channel with webhook type.', + ) + .describe( + 'Union type for requests creating new notification channel with certain type.', + ) + +/** + * Get a notification channel by id. + * @summary Get notification channel + */ +export const getNotificationChannelPathChannelIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetNotificationChannelParams = zod.object({ + channelId: zod.coerce + .string() + .regex(getNotificationChannelPathChannelIdRegExp), +}) + +/** + * Soft delete notification channel by id. + * + * Once a notification channel is deleted it cannot be undeleted. + * @summary Delete a notification channel + */ +export const deleteNotificationChannelPathChannelIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteNotificationChannelParams = zod.object({ + channelId: zod.coerce + .string() + .regex(deleteNotificationChannelPathChannelIdRegExp), +}) + +/** + * List all notification events. + * @summary List notification events + */ +export const listNotificationEventsQueryRuleItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listNotificationEventsQueryChannelItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listNotificationEventsQueryPageDefault = 1 + +export const listNotificationEventsQueryPageSizeDefault = 100 +export const listNotificationEventsQueryPageSizeMax = 1000 + +export const listNotificationEventsQueryOrderDefault = 'ASC' + +export const ListNotificationEventsQueryParams = zod.object({ + channel: zod + .array( + zod.coerce + .string() + .regex(listNotificationEventsQueryChannelItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe( + 'Filtering by multiple channel ids.\n\nUsage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J`', + ), + feature: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple feature ids or keys.\n\nUsage: `?feature=feature-1&feature=feature-2`', + ), + from: zod.coerce + .date() + .optional() + .describe('Start date-time in RFC 3339 format.\nInclusive.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listNotificationEventsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'createdAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listNotificationEventsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listNotificationEventsQueryPageSizeMax) + .default(listNotificationEventsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + rule: zod + .array( + zod.coerce + .string() + .regex(listNotificationEventsQueryRuleItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe( + 'Filtering by multiple rule ids.\n\nUsage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5`', + ), + subject: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple subject ids or keys.\n\nUsage: `?subject=subject-1&subject=subject-2`', + ), + to: zod.coerce + .date() + .optional() + .describe('End date-time in RFC 3339 format.\nInclusive.'), +}) + +/** + * Get a notification event by id. + * @summary Get notification event + */ +export const GetNotificationEventParams = zod.object({ + eventId: zod.coerce.string(), +}) + +/** + * @summary Re-send notification event + */ +export const resendNotificationEventPathEventIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ResendNotificationEventParams = zod.object({ + eventId: zod.coerce.string().regex(resendNotificationEventPathEventIdRegExp), +}) + +export const resendNotificationEventBodyChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ResendNotificationEventBody = zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(resendNotificationEventBodyChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Notification channels to which the event should be re-sent.'), + }) + .describe('A notification event that will be re-sent.') + +/** + * List all notification rules. + * @summary List notification rules + */ +export const listNotificationRulesQueryIncludeDeletedDefault = false +export const listNotificationRulesQueryIncludeDisabledDefault = false +export const listNotificationRulesQueryFeatureItemMax = 64 + +export const listNotificationRulesQueryFeatureItemRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listNotificationRulesQueryPageDefault = 1 + +export const listNotificationRulesQueryPageSizeDefault = 100 +export const listNotificationRulesQueryPageSizeMax = 1000 + +export const listNotificationRulesQueryOrderDefault = 'ASC' + +export const ListNotificationRulesQueryParams = zod.object({ + channel: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple notifiaction channel ids.\n\nUsage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3`', + ), + feature: zod + .array( + zod.coerce + .string() + .min(1) + .max(listNotificationRulesQueryFeatureItemMax) + .regex(listNotificationRulesQueryFeatureItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).\nA key is a unique string that is used to identify a resource.\n\nTODO: this is a temporary solution to support both ULID and Key in the same spec for codegen.', + ), + ) + .optional() + .describe( + 'Filtering by multiple feature ids/keys.\n\nUsage: `?feature=feature-1&feature=feature-2`', + ), + includeDeleted: zod.coerce + .boolean() + .default(listNotificationRulesQueryIncludeDeletedDefault) + .describe( + 'Include deleted notification rules in response.\n\nUsage: `?includeDeleted=true`', + ), + includeDisabled: zod.coerce + .boolean() + .default(listNotificationRulesQueryIncludeDisabledDefault) + .describe( + 'Include disabled notification rules in response.\n\nUsage: `?includeDisabled=false`', + ), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listNotificationRulesQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'type', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listNotificationRulesQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listNotificationRulesQueryPageSizeMax) + .default(listNotificationRulesQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Create a new notification rule. + * @summary Create a notification rule + */ +export const createNotificationRuleBodyOneNameMax = 256 + +export const createNotificationRuleBodyOneDisabledDefault = false +export const createNotificationRuleBodyOneThresholdsMax = 10 + +export const createNotificationRuleBodyOneChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const createNotificationRuleBodyOneFeaturesItemMax = 64 + +export const createNotificationRuleBodyOneFeaturesItemRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const createNotificationRuleBodyTwoNameMax = 256 + +export const createNotificationRuleBodyTwoDisabledDefault = false +export const createNotificationRuleBodyTwoChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const createNotificationRuleBodyTwoFeaturesItemMax = 64 + +export const createNotificationRuleBodyTwoFeaturesItemRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const createNotificationRuleBodyThreeNameMax = 256 + +export const createNotificationRuleBodyThreeDisabledDefault = false +export const createNotificationRuleBodyThreeChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const createNotificationRuleBodyFourNameMax = 256 + +export const createNotificationRuleBodyFourDisabledDefault = false +export const createNotificationRuleBodyFourChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreateNotificationRuleBody = zod + .union([ + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(createNotificationRuleBodyOneChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(createNotificationRuleBodyOneDisabledDefault) + .describe('Whether the rule is disabled or not.'), + features: zod + .array( + zod.coerce + .string() + .min(1) + .max(createNotificationRuleBodyOneFeaturesItemMax) + .regex(createNotificationRuleBodyOneFeaturesItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).\nA key is a unique string that is used to identify a resource.\n\nTODO: this is a temporary solution to support both ULID and Key in the same spec for codegen.', + ), + ) + .min(1) + .optional() + .describe( + 'Optional field for defining the scope of notification by feature. It may contain features by id or key.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createNotificationRuleBodyOneNameMax) + .describe('The user friendly name of the notification rule.'), + thresholds: zod + .array( + zod + .object({ + type: zod + .enum([ + 'PERCENT', + 'NUMBER', + 'balance_value', + 'usage_percentage', + 'usage_value', + ]) + .describe( + 'Type of the rule in the balance threshold specification:\n* `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period\n* `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period\n* `usage_value`: threshold defined by the usage value in the current usage period\n* `NUMBER` (**deprecated**): see `usage_value`\n* `PERCENT` (**deprecated**): see `usage_percentage`', + ) + .describe('Type of the threshold.'), + value: zod.coerce.number().describe('Value of the threshold.'), + }) + .describe('Threshold value with multiple supported types.'), + ) + .min(1) + .max(createNotificationRuleBodyOneThresholdsMax) + .describe('List of thresholds the rule suppose to be triggered.'), + type: zod + .enum(['entitlements.balance.threshold']) + .describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with entitlements.balance.threshold type.', + ), + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(createNotificationRuleBodyTwoChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(createNotificationRuleBodyTwoDisabledDefault) + .describe('Whether the rule is disabled or not.'), + features: zod + .array( + zod.coerce + .string() + .min(1) + .max(createNotificationRuleBodyTwoFeaturesItemMax) + .regex(createNotificationRuleBodyTwoFeaturesItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).\nA key is a unique string that is used to identify a resource.\n\nTODO: this is a temporary solution to support both ULID and Key in the same spec for codegen.', + ), + ) + .min(1) + .optional() + .describe( + 'Optional field for defining the scope of notification by feature. It may contain features by id or key.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createNotificationRuleBodyTwoNameMax) + .describe('The user friendly name of the notification rule.'), + type: zod + .enum(['entitlements.reset']) + .describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with entitlements.reset type.', + ), + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(createNotificationRuleBodyThreeChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(createNotificationRuleBodyThreeDisabledDefault) + .describe('Whether the rule is disabled or not.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createNotificationRuleBodyThreeNameMax) + .describe('The user friendly name of the notification rule.'), + type: zod.enum(['invoice.created']).describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with invoice.created type.', + ), + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(createNotificationRuleBodyFourChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(createNotificationRuleBodyFourDisabledDefault) + .describe('Whether the rule is disabled or not.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createNotificationRuleBodyFourNameMax) + .describe('The user friendly name of the notification rule.'), + type: zod.enum(['invoice.updated']).describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with invoice.updated type.', + ), + ]) + .describe( + 'Union type for requests creating new notification rule with certain type.', + ) + +/** + * Update notification rule. + * @summary Update a notification rule + */ +export const updateNotificationRulePathRuleIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateNotificationRuleParams = zod.object({ + ruleId: zod.coerce.string().regex(updateNotificationRulePathRuleIdRegExp), +}) + +export const updateNotificationRuleBodyOneNameMax = 256 + +export const updateNotificationRuleBodyOneDisabledDefault = false +export const updateNotificationRuleBodyOneThresholdsMax = 10 + +export const updateNotificationRuleBodyOneChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const updateNotificationRuleBodyOneFeaturesItemMax = 64 + +export const updateNotificationRuleBodyOneFeaturesItemRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const updateNotificationRuleBodyTwoNameMax = 256 + +export const updateNotificationRuleBodyTwoDisabledDefault = false +export const updateNotificationRuleBodyTwoChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const updateNotificationRuleBodyTwoFeaturesItemMax = 64 + +export const updateNotificationRuleBodyTwoFeaturesItemRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const updateNotificationRuleBodyThreeNameMax = 256 + +export const updateNotificationRuleBodyThreeDisabledDefault = false +export const updateNotificationRuleBodyThreeChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const updateNotificationRuleBodyFourNameMax = 256 + +export const updateNotificationRuleBodyFourDisabledDefault = false +export const updateNotificationRuleBodyFourChannelsItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateNotificationRuleBody = zod + .union([ + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(updateNotificationRuleBodyOneChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(updateNotificationRuleBodyOneDisabledDefault) + .describe('Whether the rule is disabled or not.'), + features: zod + .array( + zod.coerce + .string() + .min(1) + .max(updateNotificationRuleBodyOneFeaturesItemMax) + .regex(updateNotificationRuleBodyOneFeaturesItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).\nA key is a unique string that is used to identify a resource.\n\nTODO: this is a temporary solution to support both ULID and Key in the same spec for codegen.', + ), + ) + .min(1) + .optional() + .describe( + 'Optional field for defining the scope of notification by feature. It may contain features by id or key.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateNotificationRuleBodyOneNameMax) + .describe('The user friendly name of the notification rule.'), + thresholds: zod + .array( + zod + .object({ + type: zod + .enum([ + 'PERCENT', + 'NUMBER', + 'balance_value', + 'usage_percentage', + 'usage_value', + ]) + .describe( + 'Type of the rule in the balance threshold specification:\n* `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period\n* `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period\n* `usage_value`: threshold defined by the usage value in the current usage period\n* `NUMBER` (**deprecated**): see `usage_value`\n* `PERCENT` (**deprecated**): see `usage_percentage`', + ) + .describe('Type of the threshold.'), + value: zod.coerce.number().describe('Value of the threshold.'), + }) + .describe('Threshold value with multiple supported types.'), + ) + .min(1) + .max(updateNotificationRuleBodyOneThresholdsMax) + .describe('List of thresholds the rule suppose to be triggered.'), + type: zod + .enum(['entitlements.balance.threshold']) + .describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with entitlements.balance.threshold type.', + ), + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(updateNotificationRuleBodyTwoChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(updateNotificationRuleBodyTwoDisabledDefault) + .describe('Whether the rule is disabled or not.'), + features: zod + .array( + zod.coerce + .string() + .min(1) + .max(updateNotificationRuleBodyTwoFeaturesItemMax) + .regex(updateNotificationRuleBodyTwoFeaturesItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).\nA key is a unique string that is used to identify a resource.\n\nTODO: this is a temporary solution to support both ULID and Key in the same spec for codegen.', + ), + ) + .min(1) + .optional() + .describe( + 'Optional field for defining the scope of notification by feature. It may contain features by id or key.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateNotificationRuleBodyTwoNameMax) + .describe('The user friendly name of the notification rule.'), + type: zod + .enum(['entitlements.reset']) + .describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with entitlements.reset type.', + ), + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(updateNotificationRuleBodyThreeChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(updateNotificationRuleBodyThreeDisabledDefault) + .describe('Whether the rule is disabled or not.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateNotificationRuleBodyThreeNameMax) + .describe('The user friendly name of the notification rule.'), + type: zod.enum(['invoice.created']).describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with invoice.created type.', + ), + zod + .object({ + channels: zod + .array( + zod.coerce + .string() + .regex(updateNotificationRuleBodyFourChannelsItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .min(1) + .describe('List of notification channels the rule is applied to.'), + disabled: zod.coerce + .boolean() + .default(updateNotificationRuleBodyFourDisabledDefault) + .describe('Whether the rule is disabled or not.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateNotificationRuleBodyFourNameMax) + .describe('The user friendly name of the notification rule.'), + type: zod.enum(['invoice.updated']).describe('Notification rule type.'), + }) + .describe( + 'Request with input parameters for creating new notification rule with invoice.updated type.', + ), + ]) + .describe( + 'Union type for requests creating new notification rule with certain type.', + ) + +/** + * Get a notification rule by id. + * @summary Get notification rule + */ +export const getNotificationRulePathRuleIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetNotificationRuleParams = zod.object({ + ruleId: zod.coerce.string().regex(getNotificationRulePathRuleIdRegExp), +}) + +/** + * Soft delete notification rule by id. + * + * Once a notification rule is deleted it cannot be undeleted. + * @summary Delete a notification rule + */ +export const deleteNotificationRulePathRuleIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteNotificationRuleParams = zod.object({ + ruleId: zod.coerce.string().regex(deleteNotificationRulePathRuleIdRegExp), +}) + +/** + * Test a notification rule by sending a test event with random data. + * @summary Test notification rule + */ +export const testNotificationRulePathRuleIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const TestNotificationRuleParams = zod.object({ + ruleId: zod.coerce.string().regex(testNotificationRulePathRuleIdRegExp), +}) + +/** + * List all plans. + * @summary List plans + */ +export const listPlansQueryIncludeDeletedDefault = false +export const listPlansQueryIdItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listPlansQueryKeyItemMax = 64 + +export const listPlansQueryKeyItemRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const listPlansQueryCurrencyItemMin = 3 +export const listPlansQueryCurrencyItemMax = 3 + +export const listPlansQueryCurrencyItemRegExp = /^[A-Z]{3}$/ +export const listPlansQueryPageDefault = 1 + +export const listPlansQueryPageSizeDefault = 100 +export const listPlansQueryPageSizeMax = 1000 + +export const listPlansQueryOrderDefault = 'ASC' + +export const ListPlansQueryParams = zod.object({ + currency: zod + .array( + zod.coerce + .string() + .min(listPlansQueryCurrencyItemMin) + .max(listPlansQueryCurrencyItemMax) + .regex(listPlansQueryCurrencyItemRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ), + ) + .optional() + .describe('Filter by plan.currency attribute'), + id: zod + .array( + zod.coerce + .string() + .regex(listPlansQueryIdItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Filter by plan.id attribute'), + includeDeleted: zod.coerce + .boolean() + .default(listPlansQueryIncludeDeletedDefault) + .describe( + 'Include deleted plans in response.\n\nUsage: `?includeDeleted=true`', + ), + key: zod + .array( + zod.coerce + .string() + .min(1) + .max(listPlansQueryKeyItemMax) + .regex(listPlansQueryKeyItemRegExp) + .describe( + 'A key is a unique string that is used to identify a resource.', + ), + ) + .optional() + .describe('Filter by plan.key attribute'), + keyVersion: zod + .record(zod.string(), zod.array(zod.coerce.number())) + .optional() + .describe('Filter by plan.key and plan.version attributes'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listPlansQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'key', 'version', 'created_at', 'updated_at']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listPlansQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listPlansQueryPageSizeMax) + .default(listPlansQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), + status: zod + .array( + zod + .enum(['draft', 'active', 'archived', 'scheduled']) + .describe('The status of a plan.'), + ) + .optional() + .describe( + 'Only return plans with the given status.\n\nUsage:\n- `?status=active`: return only the currently active plan\n- `?status=draft`: return only the draft plan\n- `?status=archived`: return only the archived plans', + ), +}) + +/** + * Create a new plan. + * @summary Create a plan + */ +export const createPlanBodyNameMax = 256 + +export const createPlanBodyDescriptionMax = 1024 + +export const createPlanBodyKeyMax = 64 + +export const createPlanBodyKeyRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPlanBodyCurrencyOneMin = 3 +export const createPlanBodyCurrencyOneMax = 3 + +export const createPlanBodyCurrencyOneRegExp = /^[A-Z]{3}$/ +export const createPlanBodyCurrencyDefault = 'USD' +export const createPlanBodyProRatingConfigOneEnabledDefault = true +export const createPlanBodyProRatingConfigOneModeDefault = 'prorate_prices' +export const createPlanBodyProRatingConfigDefault = { + enabled: true, + mode: 'prorate_prices' as const, +} as const +export const createPlanBodySettlementModeDefault = 'credit_then_invoice' +export const createPlanBodyPhasesItemKeyMax = 64 + +export const createPlanBodyPhasesItemKeyRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPlanBodyPhasesItemNameMax = 256 + +export const createPlanBodyPhasesItemDescriptionMax = 1024 + +export const createPlanBodyPhasesItemRateCardsItemOneKeyMax = 64 + +export const createPlanBodyPhasesItemRateCardsItemOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPlanBodyPhasesItemRateCardsItemOneNameMax = 256 + +export const createPlanBodyPhasesItemRateCardsItemOneDescriptionMax = 1024 + +export const createPlanBodyPhasesItemRateCardsItemOneFeatureKeyMax = 64 + +export const createPlanBodyPhasesItemRateCardsItemOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const createPlanBodyPhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createPlanBodyPhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createPlanBodyPhasesItemRateCardsItemOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemOnePriceOnePaymentTermDefault = + 'in_advance' +export const createPlanBodyPhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoKeyMax = 64 + +export const createPlanBodyPhasesItemRateCardsItemTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPlanBodyPhasesItemRateCardsItemTwoNameMax = 256 + +export const createPlanBodyPhasesItemRateCardsItemTwoDescriptionMax = 1024 + +export const createPlanBodyPhasesItemRateCardsItemTwoFeatureKeyMax = 64 + +export const createPlanBodyPhasesItemRateCardsItemTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const createPlanBodyPhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createPlanBodyPhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault = + '1' +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createPlanBodyPhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const CreatePlanBody = zod + .object({ + alignment: zod + .object({ + billablesMustAlign: zod.coerce + .boolean() + .optional() + .describe( + "Whether all Billable items and RateCards must align.\nAlignment means the Price's BillingCadence must align for both duration and anchor time.", + ), + }) + .describe('Alignment configuration for a plan or subscription.') + .optional() + .describe('Alignment configuration for the plan.'), + billingCadence: zod.coerce + .string() + .describe( + 'The default billing cadence for subscriptions using this plan.\nDefines how often customers are billed using ISO8601 duration format.\nExamples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually).', + ), + currency: zod.coerce + .string() + .min(createPlanBodyCurrencyOneMin) + .max(createPlanBodyCurrencyOneMax) + .regex(createPlanBodyCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .default(createPlanBodyCurrencyDefault) + .describe('The currency code of the plan.'), + description: zod.coerce + .string() + .max(createPlanBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + key: zod.coerce + .string() + .min(1) + .max(createPlanBodyKeyMax) + .regex(createPlanBodyKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createPlanBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + phases: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max(createPlanBodyPhasesItemDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + duration: zod.coerce + .string() + .nullable() + .describe('The duration of the phase.'), + key: zod.coerce + .string() + .min(1) + .max(createPlanBodyPhasesItemKeyMax) + .regex(createPlanBodyPhasesItemKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createPlanBodyPhasesItemNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + rateCards: zod + .array( + zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max( + createPlanBodyPhasesItemRateCardsItemOneDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createPlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + createPlanBodyPhasesItemRateCardsItemOneFeatureKeyMax, + ) + .regex( + createPlanBodyPhasesItemRateCardsItemOneFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max(createPlanBodyPhasesItemRateCardsItemOneKeyMax) + .regex( + createPlanBodyPhasesItemRateCardsItemOneKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createPlanBodyPhasesItemRateCardsItemOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createPlanBodyPhasesItemRateCardsItemOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe('The billing cadence of the rate card.'), + description: zod.coerce + .string() + .max( + createPlanBodyPhasesItemRateCardsItemTwoDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createPlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + createPlanBodyPhasesItemRateCardsItemTwoFeatureKeyMax, + ) + .regex( + createPlanBodyPhasesItemRateCardsItemTwoFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max(createPlanBodyPhasesItemRateCardsItemTwoKeyMax) + .regex( + createPlanBodyPhasesItemRateCardsItemTwoKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createPlanBodyPhasesItemRateCardsItemTwoNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe( + 'The type of the price.', + ), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe( + 'The type of the price.', + ), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe( + 'Dynamic price with spend commitments.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe( + 'Package price with spend commitments.', + ), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createPlanBodyPhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + ) + .describe('The rate cards of the plan.'), + }) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.", + ), + ) + .min(1) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.\nA phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices.", + ), + proRatingConfig: zod + .object({ + enabled: zod.coerce + .boolean() + .default(createPlanBodyProRatingConfigOneEnabledDefault) + .describe('Whether pro-rating is enabled for this plan.'), + mode: zod + .enum(['prorate_prices']) + .describe( + 'Pro-rating mode options for handling billing period changes.', + ) + .default(createPlanBodyProRatingConfigOneModeDefault) + .describe('How to handle pro-rating for billing period changes.'), + }) + .describe('Configuration for pro-rating behavior.') + .default(createPlanBodyProRatingConfigDefault) + .describe( + 'Default pro-rating configuration for subscriptions using this plan.', + ), + settlementMode: zod + .enum(['credit_then_invoice', 'credit_only']) + .describe( + 'The settlement mode of a plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.', + ) + .default(createPlanBodySettlementModeDefault) + .describe( + 'The settlement mode of the plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.\nThis is the default and most common settlement mode.', + ), + }) + .describe('Resource create operation model.') + +/** + * Create a new draft version from plan. + * It returns error if there is already a plan in draft or planId does not reference the latest published version. + * @deprecated + * @summary New draft plan + */ +export const nextPlanPathPlanIdOrKeyMax = 64 + +export const nextPlanPathPlanIdOrKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const NextPlanParams = zod.object({ + planIdOrKey: zod.coerce + .string() + .min(1) + .max(nextPlanPathPlanIdOrKeyMax) + .regex(nextPlanPathPlanIdOrKeyRegExp), +}) + +/** + * Update plan by id. + * @summary Update a plan + */ +export const updatePlanPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdatePlanParams = zod.object({ + planId: zod.coerce.string().regex(updatePlanPathPlanIdRegExp), +}) + +export const updatePlanBodyNameMax = 256 + +export const updatePlanBodyDescriptionMax = 1024 + +export const updatePlanBodyProRatingConfigOneEnabledDefault = true +export const updatePlanBodyProRatingConfigOneModeDefault = 'prorate_prices' +export const updatePlanBodyProRatingConfigDefault = { + enabled: true, + mode: 'prorate_prices' as const, +} as const +export const updatePlanBodySettlementModeDefault = 'credit_then_invoice' +export const updatePlanBodyPhasesItemKeyMax = 64 + +export const updatePlanBodyPhasesItemKeyRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updatePlanBodyPhasesItemNameMax = 256 + +export const updatePlanBodyPhasesItemDescriptionMax = 1024 + +export const updatePlanBodyPhasesItemRateCardsItemOneKeyMax = 64 + +export const updatePlanBodyPhasesItemRateCardsItemOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updatePlanBodyPhasesItemRateCardsItemOneNameMax = 256 + +export const updatePlanBodyPhasesItemRateCardsItemOneDescriptionMax = 1024 + +export const updatePlanBodyPhasesItemRateCardsItemOneFeatureKeyMax = 64 + +export const updatePlanBodyPhasesItemRateCardsItemOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const updatePlanBodyPhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updatePlanBodyPhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updatePlanBodyPhasesItemRateCardsItemOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemOnePriceOnePaymentTermDefault = + 'in_advance' +export const updatePlanBodyPhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoKeyMax = 64 + +export const updatePlanBodyPhasesItemRateCardsItemTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoNameMax = 256 + +export const updatePlanBodyPhasesItemRateCardsItemTwoDescriptionMax = 1024 + +export const updatePlanBodyPhasesItemRateCardsItemTwoFeatureKeyMax = 64 + +export const updatePlanBodyPhasesItemRateCardsItemTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const updatePlanBodyPhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault = + '1' +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const updatePlanBodyPhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const UpdatePlanBody = zod + .object({ + alignment: zod + .object({ + billablesMustAlign: zod.coerce + .boolean() + .optional() + .describe( + "Whether all Billable items and RateCards must align.\nAlignment means the Price's BillingCadence must align for both duration and anchor time.", + ), + }) + .describe('Alignment configuration for a plan or subscription.') + .optional() + .describe('Alignment configuration for the plan.'), + billingCadence: zod.coerce + .string() + .describe( + 'The default billing cadence for subscriptions using this plan.\nDefines how often customers are billed using ISO8601 duration format.\nExamples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually).', + ), + description: zod.coerce + .string() + .max(updatePlanBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updatePlanBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + phases: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max(updatePlanBodyPhasesItemDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + duration: zod.coerce + .string() + .nullable() + .describe('The duration of the phase.'), + key: zod.coerce + .string() + .min(1) + .max(updatePlanBodyPhasesItemKeyMax) + .regex(updatePlanBodyPhasesItemKeyRegExp) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updatePlanBodyPhasesItemNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + rateCards: zod + .array( + zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max( + updatePlanBodyPhasesItemRateCardsItemOneDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + updatePlanBodyPhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + updatePlanBodyPhasesItemRateCardsItemOneFeatureKeyMax, + ) + .regex( + updatePlanBodyPhasesItemRateCardsItemOneFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max(updatePlanBodyPhasesItemRateCardsItemOneKeyMax) + .regex( + updatePlanBodyPhasesItemRateCardsItemOneKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updatePlanBodyPhasesItemRateCardsItemOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + updatePlanBodyPhasesItemRateCardsItemOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe('The billing cadence of the rate card.'), + description: zod.coerce + .string() + .max( + updatePlanBodyPhasesItemRateCardsItemTwoDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + updatePlanBodyPhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + updatePlanBodyPhasesItemRateCardsItemTwoFeatureKeyMax, + ) + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max(updatePlanBodyPhasesItemRateCardsItemTwoKeyMax) + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updatePlanBodyPhasesItemRateCardsItemTwoNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe( + 'The type of the price.', + ), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe( + 'The type of the price.', + ), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe( + 'Dynamic price with spend commitments.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe( + 'Package price with spend commitments.', + ), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + updatePlanBodyPhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + ) + .describe('The rate cards of the plan.'), + }) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.", + ), + ) + .min(1) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.\nA phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices.", + ), + proRatingConfig: zod + .object({ + enabled: zod.coerce + .boolean() + .default(updatePlanBodyProRatingConfigOneEnabledDefault) + .describe('Whether pro-rating is enabled for this plan.'), + mode: zod + .enum(['prorate_prices']) + .describe( + 'Pro-rating mode options for handling billing period changes.', + ) + .default(updatePlanBodyProRatingConfigOneModeDefault) + .describe('How to handle pro-rating for billing period changes.'), + }) + .describe('Configuration for pro-rating behavior.') + .default(updatePlanBodyProRatingConfigDefault) + .describe( + 'Default pro-rating configuration for subscriptions using this plan.', + ), + settlementMode: zod + .enum(['credit_then_invoice', 'credit_only']) + .describe( + 'The settlement mode of a plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.', + ) + .default(updatePlanBodySettlementModeDefault) + .describe( + 'The settlement mode of the plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.\nThis is the default and most common settlement mode.', + ), + }) + .describe('Resource update operation model.') + +/** + * Get a plan by id or key. The latest published version is returned if latter is used. + * @summary Get plan + */ +export const getPlanPathPlanIdMax = 64 + +export const getPlanPathPlanIdRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetPlanParams = zod.object({ + planId: zod.coerce + .string() + .min(1) + .max(getPlanPathPlanIdMax) + .regex(getPlanPathPlanIdRegExp), +}) + +export const getPlanQueryIncludeLatestDefault = false + +export const GetPlanQueryParams = zod.object({ + includeLatest: zod.coerce + .boolean() + .default(getPlanQueryIncludeLatestDefault) + .describe( + 'Include latest version of the Plan instead of the version in active state.\n\nUsage: `?includeLatest=true`', + ), +}) + +/** + * Soft delete plan by plan.id. + * + * Once a plan is deleted it cannot be undeleted. + * @summary Delete plan + */ +export const deletePlanPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeletePlanParams = zod.object({ + planId: zod.coerce.string().regex(deletePlanPathPlanIdRegExp), +}) + +/** + * List all available add-ons for plan. + * @summary List all available add-ons for plan + */ +export const listPlanAddonsPathPlanIdMax = 64 + +export const listPlanAddonsPathPlanIdRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ListPlanAddonsParams = zod.object({ + planId: zod.coerce + .string() + .min(1) + .max(listPlanAddonsPathPlanIdMax) + .regex(listPlanAddonsPathPlanIdRegExp), +}) + +export const listPlanAddonsQueryIncludeDeletedDefault = false +export const listPlanAddonsQueryIdItemRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listPlanAddonsQueryKeyItemMax = 64 + +export const listPlanAddonsQueryKeyItemRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const listPlanAddonsQueryPageDefault = 1 + +export const listPlanAddonsQueryPageSizeDefault = 100 +export const listPlanAddonsQueryPageSizeMax = 1000 + +export const listPlanAddonsQueryOrderDefault = 'ASC' + +export const ListPlanAddonsQueryParams = zod.object({ + id: zod + .array( + zod.coerce + .string() + .regex(listPlanAddonsQueryIdItemRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + ) + .optional() + .describe('Filter by addon.id attribute.'), + includeDeleted: zod.coerce + .boolean() + .default(listPlanAddonsQueryIncludeDeletedDefault) + .describe( + 'Include deleted plan add-on assignments.\n\nUsage: `?includeDeleted=true`', + ), + key: zod + .array( + zod.coerce + .string() + .min(1) + .max(listPlanAddonsQueryKeyItemMax) + .regex(listPlanAddonsQueryKeyItemRegExp) + .describe( + 'A key is a unique string that is used to identify a resource.', + ), + ) + .optional() + .describe('Filter by addon.key attribute.'), + keyVersion: zod + .record(zod.string(), zod.array(zod.coerce.number())) + .optional() + .describe('Filter by addon.key and addon.version attributes.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listPlanAddonsQueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'key', 'version', 'created_at', 'updated_at']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listPlanAddonsQueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listPlanAddonsQueryPageSizeMax) + .default(listPlanAddonsQueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Create new add-on assignment for plan. + * @summary Create new add-on assignment for plan + */ +export const createPlanAddonPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreatePlanAddonParams = zod.object({ + planId: zod.coerce.string().regex(createPlanAddonPathPlanIdRegExp), +}) + +export const createPlanAddonBodyAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreatePlanAddonBody = zod + .object({ + addonId: zod.coerce + .string() + .regex(createPlanAddonBodyAddonIdRegExp) + .describe('The add-on unique identifier in ULID format.'), + fromPlanPhase: zod.coerce + .string() + .describe( + 'The key of the plan phase from the add-on becomes available for purchase.', + ), + maxQuantity: zod.coerce + .number() + .optional() + .describe( + 'The maximum number of times the add-on can be purchased for the plan.\nIt is not applicable for add-ons with single instance type.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the resource.'), + }) + .describe('A plan add-on assignment create request.') + +/** + * Update add-on assignment for plan. + * @summary Update add-on assignment for plan + */ +export const updatePlanAddonPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updatePlanAddonPathPlanAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdatePlanAddonParams = zod.object({ + planAddonId: zod.coerce.string().regex(updatePlanAddonPathPlanAddonIdRegExp), + planId: zod.coerce.string().regex(updatePlanAddonPathPlanIdRegExp), +}) + +export const UpdatePlanAddonBody = zod + .object({ + fromPlanPhase: zod.coerce + .string() + .describe( + 'The key of the plan phase from the add-on becomes available for purchase.', + ), + maxQuantity: zod.coerce + .number() + .optional() + .describe( + 'The maximum number of times the add-on can be purchased for the plan.\nIt is not applicable for add-ons with single instance type.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the resource.'), + }) + .describe('Resource update operation model.') + +/** + * Get add-on assignment for plan by id. + * @summary Get add-on assignment for plan + */ +export const getPlanAddonPathPlanIdMax = 64 + +export const getPlanAddonPathPlanIdRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getPlanAddonPathPlanAddonIdMax = 64 + +export const getPlanAddonPathPlanAddonIdRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetPlanAddonParams = zod.object({ + planAddonId: zod.coerce + .string() + .min(1) + .max(getPlanAddonPathPlanAddonIdMax) + .regex(getPlanAddonPathPlanAddonIdRegExp), + planId: zod.coerce + .string() + .min(1) + .max(getPlanAddonPathPlanIdMax) + .regex(getPlanAddonPathPlanIdRegExp), +}) + +/** + * Delete add-on assignment for plan. + * + * Once a plan is deleted it cannot be undeleted. + * @summary Delete add-on assignment for plan + */ +export const deletePlanAddonPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const deletePlanAddonPathPlanAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeletePlanAddonParams = zod.object({ + planAddonId: zod.coerce.string().regex(deletePlanAddonPathPlanAddonIdRegExp), + planId: zod.coerce.string().regex(deletePlanAddonPathPlanIdRegExp), +}) + +/** + * Archive a plan version. + * @summary Archive plan version + */ +export const archivePlanPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ArchivePlanParams = zod.object({ + planId: zod.coerce.string().regex(archivePlanPathPlanIdRegExp), +}) + +/** + * Publish a plan version. + * @summary Publish plan + */ +export const publishPlanPathPlanIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const PublishPlanParams = zod.object({ + planId: zod.coerce.string().regex(publishPlanPathPlanIdRegExp), +}) + +/** + * Query meter for consumer portal. This endpoint is publicly exposable to consumers. Query meter for consumer portal. This endpoint is publicly exposable to consumers. + * @summary Query meter Query meter + */ +export const queryPortalMeterPathMeterSlugMax = 64 + +export const queryPortalMeterPathMeterSlugRegExp = /^[a-z0-9]+(?:_[a-z0-9]+)*$/ + +export const QueryPortalMeterParams = zod.object({ + meterSlug: zod.coerce + .string() + .min(1) + .max(queryPortalMeterPathMeterSlugMax) + .regex(queryPortalMeterPathMeterSlugRegExp), +}) + +export const queryPortalMeterQueryClientIdMax = 36 + +export const queryPortalMeterQueryWindowTimeZoneDefault = 'UTC' +export const queryPortalMeterQueryFilterCustomerIdMax = 100 + +export const QueryPortalMeterQueryParams = zod.object({ + clientId: zod.coerce + .string() + .min(1) + .max(queryPortalMeterQueryClientIdMax) + .optional() + .describe('Client ID\nUseful to track progress of a query.'), + filterCustomerId: zod + .array(zod.coerce.string()) + .max(queryPortalMeterQueryFilterCustomerIdMax) + .optional() + .describe( + 'Filtering by multiple customers.\n\nFor example: ?filterCustomerId=customer-1&filterCustomerId=customer-2', + ), + filterGroupBy: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe( + 'Simple filter for group bys with exact match.\n\nFor example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo\n\n⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead', + ), + from: zod.coerce + .date() + .optional() + .describe( + 'Start date-time in RFC 3339 format.\n\nInclusive.\n\nFor example: ?from=2025-01-01T00%3A00%3A00.000Z', + ), + groupBy: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'If not specified a single aggregate will be returned for each subject and time window.\n`subject` is a reserved group by value.\n\nFor example: ?groupBy=subject&groupBy=model', + ), + to: zod.coerce + .date() + .optional() + .describe( + 'End date-time in RFC 3339 format.\n\nInclusive.\n\nFor example: ?to=2025-02-01T00%3A00%3A00.000Z', + ), + windowSize: zod + .enum(['MINUTE', 'HOUR', 'DAY', 'MONTH']) + .optional() + .describe( + 'If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group.\n\nFor example: ?windowSize=DAY', + ), + windowTimeZone: zod.coerce + .string() + .default(queryPortalMeterQueryWindowTimeZoneDefault) + .describe( + 'The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones).\nIf not specified, the UTC timezone will be used.\n\nFor example: ?windowTimeZone=UTC', + ), +}) + +/** + * Create a consumer portal token. + * @summary Create consumer portal token + */ +export const CreatePortalTokenBody = zod + .object({ + allowedMeterSlugs: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Optional, if defined only the specified meters will be allowed.', + ), + subject: zod.coerce.string(), + }) + .describe( + "A consumer portal token.\n\nValidator doesn't obey required for readOnly properties\nSee: https://github.com/stoplightio/spectral/issues/1274", + ) + +/** + * List tokens. + * @summary List consumer portal tokens + */ +export const listPortalTokensQueryLimitDefault = 25 +export const listPortalTokensQueryLimitMax = 100 + +export const ListPortalTokensQueryParams = zod.object({ + limit: zod.coerce + .number() + .min(1) + .max(listPortalTokensQueryLimitMax) + .default(listPortalTokensQueryLimitDefault), +}) + +/** + * Invalidates consumer portal tokens by ID or subject. + * @summary Invalidate portal tokens + */ +export const InvalidatePortalTokensBody = zod.object({ + id: zod.coerce + .string() + .optional() + .describe('Invalidate a portal token by ID.'), + subject: zod.coerce + .string() + .optional() + .describe('Invalidate all portal tokens for a subject.'), +}) + +/** + * Create checkout session. + * @summary Create checkout session + */ +export const createStripeCheckoutSessionBodyAppIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createStripeCheckoutSessionBodyCustomerOneIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createStripeCheckoutSessionBodyCustomerThreeNameMax = 256 + +export const createStripeCheckoutSessionBodyCustomerThreeDescriptionMax = 1024 + +export const createStripeCheckoutSessionBodyCustomerThreeKeyMax = 256 + +export const createStripeCheckoutSessionBodyCustomerThreeUsageAttributionOneSubjectKeysMin = 0 + +export const createStripeCheckoutSessionBodyCustomerThreeCurrencyOneMin = 3 +export const createStripeCheckoutSessionBodyCustomerThreeCurrencyOneMax = 3 + +export const createStripeCheckoutSessionBodyCustomerThreeCurrencyOneRegExp = + /^[A-Z]{3}$/ +export const createStripeCheckoutSessionBodyCustomerThreeBillingAddressOneCountryOneMin = 2 +export const createStripeCheckoutSessionBodyCustomerThreeBillingAddressOneCountryOneMax = 2 + +export const createStripeCheckoutSessionBodyCustomerThreeBillingAddressOneCountryOneRegExp = + /^[A-Z]{2}$/ +export const createStripeCheckoutSessionBodyOptionsOneCurrencyOneMin = 3 +export const createStripeCheckoutSessionBodyOptionsOneCurrencyOneMax = 3 + +export const createStripeCheckoutSessionBodyOptionsOneCurrencyOneRegExp = + /^[A-Z]{3}$/ +export const createStripeCheckoutSessionBodyOptionsOneCustomTextOneAfterSubmitMessageMax = 1200 + +export const createStripeCheckoutSessionBodyOptionsOneCustomTextOneShippingAddressMessageMax = 1200 + +export const createStripeCheckoutSessionBodyOptionsOneCustomTextOneSubmitMessageMax = 1200 + +export const createStripeCheckoutSessionBodyOptionsOneCustomTextOneTermsOfServiceAcceptanceMessageMax = 1200 + +export const CreateStripeCheckoutSessionBody = zod + .object({ + appId: zod.coerce + .string() + .regex(createStripeCheckoutSessionBodyAppIdRegExp) + .optional() + .describe('If not provided, the default Stripe app is used if any.'), + customer: zod + .union([ + zod + .object({ + id: zod.coerce + .string() + .regex(createStripeCheckoutSessionBodyCustomerOneIdRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + }) + .describe('Create Stripe checkout session with customer ID.'), + zod + .object({ + key: zod.coerce.string(), + }) + .describe('Create Stripe checkout session with customer key.'), + zod + .object({ + billingAddress: zod + .object({ + city: zod.coerce.string().optional().describe('City.'), + country: zod.coerce + .string() + .min( + createStripeCheckoutSessionBodyCustomerThreeBillingAddressOneCountryOneMin, + ) + .max( + createStripeCheckoutSessionBodyCustomerThreeBillingAddressOneCountryOneMax, + ) + .regex( + createStripeCheckoutSessionBodyCustomerThreeBillingAddressOneCountryOneRegExp, + ) + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code.\nCustom two-letter country codes are also supported for convenience.', + ) + .optional() + .describe( + 'Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format.', + ), + line1: zod.coerce + .string() + .optional() + .describe('First line of the address.'), + line2: zod.coerce + .string() + .optional() + .describe('Second line of the address.'), + phoneNumber: zod.coerce + .string() + .optional() + .describe('Phone number.'), + postalCode: zod.coerce + .string() + .optional() + .describe('Postal code.'), + state: zod.coerce + .string() + .optional() + .describe('State or province.'), + }) + .describe('Address') + .optional() + .describe( + 'The billing address of the customer.\nUsed for tax and invoicing.', + ), + currency: zod.coerce + .string() + .min(createStripeCheckoutSessionBodyCustomerThreeCurrencyOneMin) + .max(createStripeCheckoutSessionBodyCustomerThreeCurrencyOneMax) + .regex( + createStripeCheckoutSessionBodyCustomerThreeCurrencyOneRegExp, + ) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .optional() + .describe( + 'Currency of the customer.\nUsed for billing, tax and invoicing.', + ), + description: zod.coerce + .string() + .max(createStripeCheckoutSessionBodyCustomerThreeDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + key: zod.coerce + .string() + .min(1) + .max(createStripeCheckoutSessionBodyCustomerThreeKeyMax) + .optional() + .describe( + 'An optional unique key of the customer.\nEither key or usageAttribution.subjectKeys must be provided.\nUseful to reference the customer in external systems.\nFor example, your database ID.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createStripeCheckoutSessionBodyCustomerThreeNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + primaryEmail: zod.coerce + .string() + .optional() + .describe('The primary email address of the customer.'), + usageAttribution: zod + .object({ + subjectKeys: zod + .array( + zod.coerce + .string() + .min(1) + .describe( + 'SubjectKey is a key that is used to identify a subject.', + ), + ) + .min( + createStripeCheckoutSessionBodyCustomerThreeUsageAttributionOneSubjectKeysMin, + ) + .describe( + 'The subjects that are attributed to the customer.\nCan be empty when no subjects are associated with the customer.', + ), + }) + .describe( + 'Mapping to attribute metered usage to the customer.\nOne customer can have zero or more subjects,\nbut one subject can only belong to one customer.', + ) + .optional() + .describe( + 'Mapping to attribute metered usage to the customer\nEither key or usageAttribution.subjectKeys must be provided.', + ), + }) + .describe('Resource create operation model.'), + ]) + .describe( + 'Provide a customer ID or key to use an existing OpenMeter customer.\nor provide a customer object to create a new customer.', + ), + options: zod + .object({ + billingAddressCollection: zod + .enum(['auto', 'required']) + .describe( + 'Specify whether Checkout should collect the customer’s billing address.', + ) + .optional() + .describe( + 'Specify whether Checkout should collect the customer’s billing address. Defaults to auto.', + ), + cancelURL: zod.coerce + .string() + .optional() + .describe( + 'If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website.\nThis parameter is not allowed if ui_mode is embedded.', + ), + clientReferenceID: zod.coerce + .string() + .optional() + .describe( + 'A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems.', + ), + consentCollection: zod + .object({ + paymentMethodReuseAgreement: zod + .object({ + position: zod + .enum(['auto', 'hidden']) + .optional() + .describe( + 'Create Stripe checkout session consent collection agreement position.', + ), + }) + .describe( + 'Create Stripe checkout session payment method reuse agreement.', + ) + .optional() + .describe( + 'Determines the position and visibility of the payment method reuse agreement in the UI.\nWhen set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI.', + ), + promotions: zod + .enum(['auto', 'none']) + .describe( + 'Create Stripe checkout session consent collection promotions.', + ) + .optional() + .describe( + 'If set to auto, enables the collection of customer consent for promotional communications.\nThe Checkout Session will determine whether to display an option to opt into promotional\ncommunication from the merchant depending on the customer’s locale. Only available to US merchants.', + ), + termsOfService: zod + .enum(['none', 'required']) + .describe( + 'Create Stripe checkout session consent collection terms of service.', + ) + .optional() + .describe( + 'If set to required, it requires customers to check a terms of service checkbox before being able to pay.\nThere must be a valid terms of service URL set in your Stripe Dashboard settings.\nhttps://dashboard.stripe.com/settings/public', + ), + }) + .describe( + 'Configure fields for the Checkout Session to gather active consent from customers.', + ) + .optional() + .describe( + 'Configure fields for the Checkout Session to gather active consent from customers.', + ), + currency: zod.coerce + .string() + .min(createStripeCheckoutSessionBodyOptionsOneCurrencyOneMin) + .max(createStripeCheckoutSessionBodyOptionsOneCurrencyOneMax) + .regex(createStripeCheckoutSessionBodyOptionsOneCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .optional() + .describe('Three-letter ISO currency code, in lowercase.'), + customerUpdate: zod + .object({ + address: zod + .enum(['auto', 'never']) + .describe( + 'Create Stripe checkout session customer update behavior.', + ) + .optional() + .describe( + 'Describes whether Checkout saves the billing address onto customer.address.\nTo always collect a full billing address, use billing_address_collection.\nDefaults to never.', + ), + name: zod + .enum(['auto', 'never']) + .describe( + 'Create Stripe checkout session customer update behavior.', + ) + .optional() + .describe( + 'Describes whether Checkout saves the name onto customer.name.\nDefaults to never.', + ), + shipping: zod + .enum(['auto', 'never']) + .describe( + 'Create Stripe checkout session customer update behavior.', + ) + .optional() + .describe( + 'Describes whether Checkout saves shipping information onto customer.shipping.\nTo collect shipping information, use shipping_address_collection.\nDefaults to never.', + ), + }) + .describe( + 'Controls what fields on Customer can be updated by the Checkout Session.', + ) + .optional() + .describe( + 'Controls what fields on Customer can be updated by the Checkout Session.', + ), + customText: zod + .object({ + afterSubmit: zod + .object({ + message: zod.coerce + .string() + .max( + createStripeCheckoutSessionBodyOptionsOneCustomTextOneAfterSubmitMessageMax, + ) + .optional(), + }) + .optional() + .describe( + 'Custom text that should be displayed after the payment confirmation button.', + ), + shippingAddress: zod + .object({ + message: zod.coerce + .string() + .max( + createStripeCheckoutSessionBodyOptionsOneCustomTextOneShippingAddressMessageMax, + ) + .optional(), + }) + .optional() + .describe( + 'Custom text that should be displayed alongside shipping address collection.', + ), + submit: zod + .object({ + message: zod.coerce + .string() + .max( + createStripeCheckoutSessionBodyOptionsOneCustomTextOneSubmitMessageMax, + ) + .optional(), + }) + .optional() + .describe( + 'Custom text that should be displayed alongside the payment confirmation button.', + ), + termsOfServiceAcceptance: zod + .object({ + message: zod.coerce + .string() + .max( + createStripeCheckoutSessionBodyOptionsOneCustomTextOneTermsOfServiceAcceptanceMessageMax, + ) + .optional(), + }) + .optional() + .describe( + 'Custom text that should be displayed in place of the default terms of service agreement text.', + ), + }) + .describe('Stripe CheckoutSession.custom_text') + .optional() + .describe( + 'Display additional text for your customers using custom text.', + ), + expiresAt: zod.coerce + .number() + .optional() + .describe( + 'The Epoch time in seconds at which the Checkout Session will expire.\nIt can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation.', + ), + locale: zod.coerce.string().optional(), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .optional() + .describe( + 'Set of key-value pairs that you can attach to an object.\nThis can be useful for storing additional information about the object in a structured format.\nIndividual keys can be unset by posting an empty value to them.\nAll keys can be unset by posting an empty value to metadata.', + ), + paymentMethodTypes: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'A list of the types of payment methods (e.g., card) this Checkout Session can accept.', + ), + redirectOnCompletion: zod + .enum(['always', 'if_required', 'never']) + .describe('Create Stripe checkout session redirect on completion.') + .optional() + .describe( + 'This parameter applies to ui_mode: embedded. Defaults to always.\nLearn more about the redirect behavior of embedded sessions at\nhttps://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form', + ), + returnURL: zod.coerce + .string() + .optional() + .describe( + 'The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site.\nThis parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session.', + ), + successURL: zod.coerce + .string() + .optional() + .describe( + 'The URL to which Stripe should send customers when payment or setup is complete.\nThis parameter is not allowed if ui_mode is embedded.\nIf you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page:\nhttps://docs.stripe.com/payments/checkout/custom-success-page', + ), + taxIdCollection: zod + .object({ + enabled: zod.coerce + .boolean() + .describe( + 'Enable tax ID collection during checkout. Defaults to false.', + ), + required: zod + .enum(['if_supported', 'never']) + .describe( + 'Create Stripe checkout session tax ID collection required.', + ) + .optional() + .describe( + 'Describes whether a tax ID is required during checkout. Defaults to never.', + ), + }) + .describe('Create Stripe checkout session tax ID collection.') + .optional() + .describe('Controls tax ID collection during checkout.'), + uiMode: zod + .enum(['embedded', 'hosted']) + .describe('Stripe CheckoutSession.ui_mode') + .optional() + .describe('The UI mode of the Session. Defaults to hosted.'), + }) + .describe( + 'Create Stripe checkout session options\nSee https://docs.stripe.com/api/checkout/sessions/create', + ) + .describe('Options passed to Stripe when creating the checkout session.'), + stripeCustomerId: zod.coerce + .string() + .optional() + .describe( + "Stripe customer ID.\nIf not provided OpenMeter creates a new Stripe customer or\nuses the OpenMeter customer's default Stripe customer ID.", + ), + }) + .describe('Create Stripe checkout session request.') + +/** + * Upserts a subject. Creates or updates subject. + * + * If the subject doesn't exist, it will be created. + * If the subject exists, it will be partially updated with the provided fields. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + * @deprecated + * @summary Upsert subject + */ +export const UpsertSubjectBodyItem = zod + .object({ + currentPeriodEnd: zod.coerce + .date() + .optional() + .describe('The end of the current period for the subject.'), + currentPeriodStart: zod.coerce + .date() + .optional() + .describe('The start of the current period for the subject.'), + displayName: zod.coerce + .string() + .nullish() + .describe('A human-readable display name for the subject.'), + key: zod.coerce + .string() + .describe( + 'A unique, human-readable identifier for the subject.\nThis is typically a database ID or a customer key.', + ), + metadata: zod + .record(zod.string(), zod.unknown()) + .nullish() + .describe('Metadata for the subject.'), + stripeCustomerId: zod.coerce + .string() + .nullish() + .describe('The Stripe customer ID for the subject.'), + }) + .describe( + 'A subject is a unique identifier for a user or entity.\n\n⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead.', + ) +export const UpsertSubjectBody = zod.array(UpsertSubjectBodyItem) + +/** + * Get subject by ID or key. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + * @deprecated + * @summary Get subject + */ +export const GetSubjectParams = zod.object({ + subjectIdOrKey: zod.coerce.string(), +}) + +/** + * Delete subject by ID or key. + * + * ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + * @deprecated + * @summary Delete subject + */ +export const DeleteSubjectParams = zod.object({ + subjectIdOrKey: zod.coerce.string(), +}) + +/** + * OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given subject can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements) instead. + * @deprecated + * @summary Create a subject entitlement + */ +export const CreateEntitlementParams = zod.object({ + subjectIdOrKey: zod.coerce.string(), +}) + +export const createEntitlementBodyOneFeatureKeyMax = 64 + +export const createEntitlementBodyOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createEntitlementBodyOneFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createEntitlementBodyOneIsSoftLimitDefault = false +export const createEntitlementBodyOneIsUnlimitedDefault = false +export const createEntitlementBodyOneUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createEntitlementBodyOneIssueAfterResetMin = 0 + +export const createEntitlementBodyOneIssueAfterResetPriorityDefault = 1 +export const createEntitlementBodyOneIssueAfterResetPriorityMax = 255 + +export const createEntitlementBodyOnePreserveOverageAtResetDefault = false +export const createEntitlementBodyTwoFeatureKeyMax = 64 + +export const createEntitlementBodyTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createEntitlementBodyTwoFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createEntitlementBodyTwoUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createEntitlementBodyThreeFeatureKeyMax = 64 + +export const createEntitlementBodyThreeFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createEntitlementBodyThreeFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createEntitlementBodyThreeUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ + +export const CreateEntitlementBody = zod + .union([ + zod + .object({ + featureId: zod.coerce + .string() + .regex(createEntitlementBodyOneFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createEntitlementBodyOneFeatureKeyMax) + .regex(createEntitlementBodyOneFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + isSoftLimit: zod.coerce + .boolean() + .default(createEntitlementBodyOneIsSoftLimitDefault) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min(createEntitlementBodyOneIssueAfterResetMin) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max(createEntitlementBodyOneIssueAfterResetPriorityMax) + .default(createEntitlementBodyOneIssueAfterResetPriorityDefault) + .describe('Defines the grant priority for the default grant.'), + isUnlimited: zod.coerce + .boolean() + .default(createEntitlementBodyOneIsUnlimitedDefault) + .describe( + 'Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future.', + ), + measureUsageFrom: zod + .union([ + zod + .enum(['CURRENT_PERIOD_START', 'NOW']) + .describe('Start of measurement options'), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe('Measure usage from') + .optional() + .describe( + 'Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default(createEntitlementBodyOnePreserveOverageAtResetDefault) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createEntitlementBodyOneUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inpurs for metered entitlement'), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + featureId: zod.coerce + .string() + .regex(createEntitlementBodyTwoFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createEntitlementBodyTwoFeatureKeyMax) + .regex(createEntitlementBodyTwoFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createEntitlementBodyTwoUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for static entitlement'), + zod + .object({ + featureId: zod.coerce + .string() + .regex(createEntitlementBodyThreeFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createEntitlementBodyThreeFeatureKeyMax) + .regex(createEntitlementBodyThreeFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createEntitlementBodyThreeUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for boolean entitlement'), + ]) + .describe('Create inputs for entitlement') + +/** + * List all entitlements for a subject. For checking entitlement access, use the /value endpoint instead. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements) instead. + * @deprecated + * @summary List subject entitlements + */ +export const ListSubjectEntitlementsParams = zod.object({ + subjectIdOrKey: zod.coerce.string(), +}) + +export const listSubjectEntitlementsQueryIncludeDeletedDefault = false + +export const ListSubjectEntitlementsQueryParams = zod.object({ + includeDeleted: zod.coerce + .boolean() + .default(listSubjectEntitlementsQueryIncludeDeletedDefault), +}) + +/** + * List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + * @deprecated + * @summary List subject entitlement grants + */ +export const ListEntitlementGrantsParams = zod.object({ + entitlementIdOrFeatureKey: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +export const listEntitlementGrantsQueryIncludeDeletedDefault = false +export const listEntitlementGrantsQueryOrderByDefault = 'updatedAt' + +export const ListEntitlementGrantsQueryParams = zod.object({ + includeDeleted: zod.coerce + .boolean() + .default(listEntitlementGrantsQueryIncludeDeletedDefault), + orderBy: zod + .enum(['id', 'createdAt', 'updatedAt']) + .describe('Order by options for grants.') + .default(listEntitlementGrantsQueryOrderByDefault), +}) + +/** + * Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + * + * A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + * + * Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + * + * Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + * + * Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * + * Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + * @deprecated + * @summary Create subject entitlement grant + */ +export const CreateGrantParams = zod.object({ + entitlementIdOrFeatureKey: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +export const createGrantBodyAmountMin = 0 + +export const createGrantBodyPriorityMax = 255 + +export const createGrantBodyExpirationOneCountMax = 1000 + +export const createGrantBodyMaxRolloverAmountDefault = 0 +export const createGrantBodyMinRolloverAmountDefault = 0 +export const createGrantBodyRecurrenceOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ + +export const CreateGrantBody = zod + .object({ + amount: zod.coerce + .number() + .min(createGrantBodyAmountMin) + .describe('The amount to grant. Should be a positive number.'), + effectiveAt: zod.coerce + .date() + .describe( + 'Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute).', + ), + expiration: zod + .object({ + count: zod.coerce + .number() + .min(1) + .max(createGrantBodyExpirationOneCountMax) + .describe('The number of time units in the expiration period.'), + duration: zod + .enum(['HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe('The expiration duration enum') + .describe('The unit of time for the expiration period.'), + }) + .describe('The grant expiration definition') + .describe('The grant expiration definition'), + maxRolloverAmount: zod.coerce + .number() + .default(createGrantBodyMaxRolloverAmountDefault) + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('The grant metadata.'), + minRolloverAmount: zod.coerce + .number() + .default(createGrantBodyMinRolloverAmountDefault) + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + priority: zod.coerce + .number() + .min(1) + .max(createGrantBodyPriorityMax) + .optional() + .describe( + 'The priority of the grant. Grants with higher priority are applied first.\nPriority is a positive decimal numbers. With lower numbers indicating higher importance.\nFor example, a priority of 1 is more urgent than a priority of 2.\nWhen there are several grants available for the same subject, the system selects the grant with the highest priority.\nIn cases where grants share the same priority level, the grant closest to its expiration will be used first.\nIn the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first.', + ), + recurrence: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex(createGrantBodyRecurrenceOneIntervalOneOneRegExp), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The subject of the grant.'), + }) + .describe('The grant creation input.') + +/** + * Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided subject-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + * + * This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + * + * ⚠️ __Deprecated__: Use [`PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override`](#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) instead. + * @deprecated + * @summary Override subject entitlement + */ +export const OverrideEntitlementParams = zod.object({ + entitlementIdOrFeatureKey: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +export const overrideEntitlementBodyOneFeatureKeyMax = 64 + +export const overrideEntitlementBodyOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const overrideEntitlementBodyOneFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideEntitlementBodyOneIsSoftLimitDefault = false +export const overrideEntitlementBodyOneIsUnlimitedDefault = false +export const overrideEntitlementBodyOneUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const overrideEntitlementBodyOneIssueAfterResetMin = 0 + +export const overrideEntitlementBodyOneIssueAfterResetPriorityDefault = 1 +export const overrideEntitlementBodyOneIssueAfterResetPriorityMax = 255 + +export const overrideEntitlementBodyOnePreserveOverageAtResetDefault = false +export const overrideEntitlementBodyTwoFeatureKeyMax = 64 + +export const overrideEntitlementBodyTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const overrideEntitlementBodyTwoFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideEntitlementBodyTwoUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const overrideEntitlementBodyThreeFeatureKeyMax = 64 + +export const overrideEntitlementBodyThreeFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const overrideEntitlementBodyThreeFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideEntitlementBodyThreeUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ + +export const OverrideEntitlementBody = zod + .union([ + zod + .object({ + featureId: zod.coerce + .string() + .regex(overrideEntitlementBodyOneFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(overrideEntitlementBodyOneFeatureKeyMax) + .regex(overrideEntitlementBodyOneFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + isSoftLimit: zod.coerce + .boolean() + .default(overrideEntitlementBodyOneIsSoftLimitDefault) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min(overrideEntitlementBodyOneIssueAfterResetMin) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max(overrideEntitlementBodyOneIssueAfterResetPriorityMax) + .default(overrideEntitlementBodyOneIssueAfterResetPriorityDefault) + .describe('Defines the grant priority for the default grant.'), + isUnlimited: zod.coerce + .boolean() + .default(overrideEntitlementBodyOneIsUnlimitedDefault) + .describe( + 'Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future.', + ), + measureUsageFrom: zod + .union([ + zod + .enum(['CURRENT_PERIOD_START', 'NOW']) + .describe('Start of measurement options'), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe('Measure usage from') + .optional() + .describe( + 'Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default(overrideEntitlementBodyOnePreserveOverageAtResetDefault) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideEntitlementBodyOneUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inpurs for metered entitlement'), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + featureId: zod.coerce + .string() + .regex(overrideEntitlementBodyTwoFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(overrideEntitlementBodyTwoFeatureKeyMax) + .regex(overrideEntitlementBodyTwoFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideEntitlementBodyTwoUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for static entitlement'), + zod + .object({ + featureId: zod.coerce + .string() + .regex(overrideEntitlementBodyThreeFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(overrideEntitlementBodyThreeFeatureKeyMax) + .regex(overrideEntitlementBodyThreeFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideEntitlementBodyThreeUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for boolean entitlement'), + ]) + .describe('Create inputs for entitlement') + +/** + * This endpoint should be used for access checks and enforcement. All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + * + * For convenience reasons, /value works with both entitlementId and featureKey. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) instead. + * @deprecated + * @summary Get subject entitlement value + */ +export const GetEntitlementValueParams = zod.object({ + entitlementIdOrFeatureKey: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +export const GetEntitlementValueQueryParams = zod.object({ + time: zod.coerce.date().optional(), +}) + +/** + * Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + * @deprecated + * @summary Get subject entitlement + */ +export const GetEntitlementParams = zod.object({ + entitlementId: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +/** + * Deleting an entitlement revokes access to the associated feature. As a single subject can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + * As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + * + * ⚠️ __Deprecated__: Use [`DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + * @deprecated + * @summary Delete subject entitlement + */ +export const DeleteEntitlementParams = zod.object({ + entitlementId: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +/** + * Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + * + * WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) instead. + * @deprecated + * @summary Get subject entitlement history + */ +export const GetEntitlementHistoryParams = zod.object({ + entitlementId: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +export const getEntitlementHistoryQueryWindowTimeZoneDefault = 'UTC' + +export const GetEntitlementHistoryQueryParams = zod.object({ + from: zod.coerce + .date() + .optional() + .describe( + 'Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter.', + ), + to: zod.coerce + .date() + .optional() + .describe( + 'End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now.\nIf not now then gets truncated to the granularity of the underlying meter.', + ), + windowSize: zod + .enum(['MINUTE', 'HOUR', 'DAY', 'MONTH']) + .describe('Windowsize'), + windowTimeZone: zod.coerce + .string() + .default(getEntitlementHistoryQueryWindowTimeZoneDefault) + .describe('The timezone used when calculating the windows.'), +}) + +/** + * Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the subjects billing period to enforce usage based on their subscription. + * + * Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) instead. + * @deprecated + * @summary Reset subject entitlement + */ +export const ResetEntitlementUsageParams = zod.object({ + entitlementId: zod.coerce.string(), + subjectIdOrKey: zod.coerce.string(), +}) + +export const ResetEntitlementUsageBody = zod + .object({ + effectiveAt: zod.coerce + .date() + .optional() + .describe( + 'The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored.', + ), + preserveOverage: zod.coerce + .boolean() + .optional() + .describe( + "Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior.\n- If true, the overage is preserved.\n- If false, the overage is forgiven.", + ), + retainAnchor: zod.coerce + .boolean() + .optional() + .describe( + 'Determines whether the usage period anchor is retained or reset to the effectiveAt time.\n- If true, the usage period anchor is retained.\n- If false, the usage period anchor is reset to the effectiveAt time.', + ), + }) + .describe('Reset parameters') + +/** + * @summary Create subscription + */ +export const createSubscriptionBodyOnePlanOneKeyMax = 64 + +export const createSubscriptionBodyOnePlanOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ + +export const createSubscriptionBodyOneTimingDefault = 'immediate' +export const createSubscriptionBodyOneCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createSubscriptionBodyOneCustomerKeyMax = 256 + +export const createSubscriptionBodyTwoCustomPlanOneOneNameMax = 256 + +export const createSubscriptionBodyTwoCustomPlanOneOneDescriptionMax = 1024 + +export const createSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMin = 3 +export const createSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMax = 3 + +export const createSubscriptionBodyTwoCustomPlanOneOneCurrencyOneRegExp = + /^[A-Z]{3}$/ +export const createSubscriptionBodyTwoCustomPlanOneOneCurrencyDefault = 'USD' +export const createSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneEnabledDefault = true +export const createSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneModeDefault = + 'prorate_prices' +export const createSubscriptionBodyTwoCustomPlanOneOneProRatingConfigDefault = { + enabled: true, + mode: 'prorate_prices' as const, +} as const +export const createSubscriptionBodyTwoCustomPlanOneOneSettlementModeDefault = + 'credit_then_invoice' +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyMax = 64 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemNameMax = 256 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemDescriptionMax = 1024 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyMax = 64 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneNameMax = 256 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDescriptionMax = 1024 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyMax = 64 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOnePaymentTermDefault = + 'in_advance' +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyMax = 64 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoNameMax = 256 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDescriptionMax = 1024 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyMax = 64 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault = + '1' +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const createSubscriptionBodyTwoTimingDefault = 'immediate' +export const createSubscriptionBodyTwoCustomerIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createSubscriptionBodyTwoCustomerKeyMax = 256 + +export const CreateSubscriptionBody = zod + .union([ + zod + .object({ + alignment: zod + .object({ + billablesMustAlign: zod.coerce + .boolean() + .optional() + .describe( + "Whether all Billable items and RateCards must align.\nAlignment means the Price's BillingCadence must align for both duration and anchor time.", + ), + }) + .describe('Alignment configuration for a plan or subscription.') + .optional() + .describe('What alignment settings the subscription should have.'), + billingAnchor: zod.coerce + .date() + .optional() + .describe( + 'The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used.', + ), + customerId: zod.coerce + .string() + .regex(createSubscriptionBodyOneCustomerIdRegExp) + .optional() + .describe( + 'The ID of the customer. Provide either the key or ID. Has presedence over the key.', + ), + customerKey: zod.coerce + .string() + .min(1) + .max(createSubscriptionBodyOneCustomerKeyMax) + .optional() + .describe('The key of the customer. Provide either the key or ID.'), + description: zod.coerce + .string() + .optional() + .describe('Description for the Subscription.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Arbitrary metadata associated with the subscription.'), + name: zod.coerce + .string() + .optional() + .describe( + 'The name of the Subscription. If not provided the plan name is used.', + ), + plan: zod + .object({ + key: zod.coerce + .string() + .min(1) + .max(createSubscriptionBodyOnePlanOneKeyMax) + .regex(createSubscriptionBodyOnePlanOneKeyRegExp) + .describe('The plan key.'), + version: zod.coerce + .number() + .optional() + .describe('The plan version.'), + }) + .describe( + 'References an exact plan defaulting to the current active version.', + ) + .describe('The plan reference to change to.'), + settlementMode: zod + .enum(['credit_then_invoice', 'credit_only']) + .describe( + 'The settlement mode of a plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.', + ) + .optional() + .describe('The settlement mode of the subscription.'), + startingPhase: zod.coerce + .string() + .min(1) + .optional() + .describe( + 'The key of the phase to start the subscription in.\nIf not provided, the subscription will start in the first phase of the plan.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .default(createSubscriptionBodyOneTimingDefault) + .describe( + 'Timing configuration for the change, when the change should take effect.\nThe default is immediate.', + ), + }) + .describe('Create subscription based on plan.'), + zod + .object({ + billingAnchor: zod.coerce + .date() + .optional() + .describe( + 'The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used.', + ), + customerId: zod.coerce + .string() + .regex(createSubscriptionBodyTwoCustomerIdRegExp) + .optional() + .describe( + 'The ID of the customer. Provide either the key or ID. Has presedence over the key.', + ), + customerKey: zod.coerce + .string() + .min(1) + .max(createSubscriptionBodyTwoCustomerKeyMax) + .optional() + .describe('The key of the customer. Provide either the key or ID.'), + customPlan: zod + .object({ + alignment: zod + .object({ + billablesMustAlign: zod.coerce + .boolean() + .optional() + .describe( + "Whether all Billable items and RateCards must align.\nAlignment means the Price's BillingCadence must align for both duration and anchor time.", + ), + }) + .describe('Alignment configuration for a plan or subscription.') + .optional() + .describe('Alignment configuration for the plan.'), + billingCadence: zod.coerce + .string() + .describe( + 'The default billing cadence for subscriptions using this plan.\nDefines how often customers are billed using ISO8601 duration format.\nExamples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually).', + ), + currency: zod.coerce + .string() + .min(createSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMin) + .max(createSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMax) + .regex(createSubscriptionBodyTwoCustomPlanOneOneCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .default(createSubscriptionBodyTwoCustomPlanOneOneCurrencyDefault) + .describe('The currency code of the plan.'), + description: zod.coerce + .string() + .max(createSubscriptionBodyTwoCustomPlanOneOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createSubscriptionBodyTwoCustomPlanOneOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + phases: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + duration: zod.coerce + .string() + .nullable() + .describe('The duration of the phase.'), + key: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyMax, + ) + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyRegExp, + ) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + rateCards: zod + .array( + zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe( + 'The percentage of the discount.', + ), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyMax, + ) + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyMax, + ) + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe( + 'Additional metadata for the resource.', + ), + name: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe( + 'Set of provider specific tax configs.', + ) + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe( + 'The billing cadence of the rate card.', + ), + description: zod.coerce + .string() + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe( + 'The percentage of the discount.', + ), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyMax, + ) + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyMax, + ) + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe( + 'Additional metadata for the resource.', + ), + name: zod.coerce + .string() + .min(1) + .max( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe( + 'Flat price with payment term.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + maximumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe( + 'Unit price with spend commitments.', + ), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe( + 'The mode of the tiered price.', + ) + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe( + 'The type of the price.', + ), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe( + 'The type of the price.', + ), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe( + 'Tiered price with spend commitments.', + ), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe( + 'Dynamic price with spend commitments.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The price of one package.', + ), + maximumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity per package.', + ), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe( + 'Package price with spend commitments.', + ), + ]) + .describe( + 'The price of the usage based rate card.', + ) + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + createSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe( + 'Set of provider specific tax configs.', + ) + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + ) + .describe('The rate cards of the plan.'), + }) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.", + ), + ) + .min(1) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.\nA phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices.", + ), + proRatingConfig: zod + .object({ + enabled: zod.coerce + .boolean() + .default( + createSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneEnabledDefault, + ) + .describe('Whether pro-rating is enabled for this plan.'), + mode: zod + .enum(['prorate_prices']) + .describe( + 'Pro-rating mode options for handling billing period changes.', + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneModeDefault, + ) + .describe( + 'How to handle pro-rating for billing period changes.', + ), + }) + .describe('Configuration for pro-rating behavior.') + .default( + createSubscriptionBodyTwoCustomPlanOneOneProRatingConfigDefault, + ) + .describe( + 'Default pro-rating configuration for subscriptions using this plan.', + ), + settlementMode: zod + .enum(['credit_then_invoice', 'credit_only']) + .describe( + 'The settlement mode of a plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.', + ) + .default( + createSubscriptionBodyTwoCustomPlanOneOneSettlementModeDefault, + ) + .describe( + 'The settlement mode of the plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.\nThis is the default and most common settlement mode.', + ), + }) + .describe('The template for omitting properties.') + .describe( + 'Plan input for custom subscription creation (without key and version).', + ) + .describe( + 'The custom plan description which defines the Subscription.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .default(createSubscriptionBodyTwoTimingDefault) + .describe( + 'Timing configuration for the change, when the change should take effect.\nThe default is immediate.', + ), + }) + .describe('Create a custom subscription.'), + ]) + .describe('Create a subscription.') + +/** + * @summary Get subscription + */ +export const getSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(getSubscriptionPathSubscriptionIdRegExp), +}) + +export const GetSubscriptionQueryParams = zod.object({ + at: zod.coerce + .date() + .optional() + .describe( + 'The time at which the subscription should be queried. If not provided the current time is used.', + ), +}) + +/** + * Batch processing commands for manipulating running subscriptions. + * The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + * @summary Edit subscription + */ +export const editSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const EditSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(editSubscriptionPathSubscriptionIdRegExp), +}) + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneKeyMax = 64 + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardOneNameMax = 256 + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneDescriptionMax = 1024 + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneFeatureKeyMax = 64 + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const editSubscriptionBodyCustomizationsItemOneRateCardOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardOnePriceOnePaymentTermDefault = + 'in_advance' +export const editSubscriptionBodyCustomizationsItemOneRateCardOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoKeyMax = 64 + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoNameMax = 256 + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoDescriptionMax = 1024 + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoFeatureKeyMax = 64 + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMultiplierDefault = + '1' +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemOneRateCardTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemThreePhaseDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const editSubscriptionBodyCustomizationsItemThreePhaseKeyMax = 64 + +export const editSubscriptionBodyCustomizationsItemThreePhaseKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const editSubscriptionBodyCustomizationsMax = 100 + +export const EditSubscriptionBody = zod + .object({ + customizations: zod + .array( + zod + .union([ + zod + .object({ + op: zod.enum(['add_item']), + phaseKey: zod.coerce.string(), + rateCard: zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max( + editSubscriptionBodyCustomizationsItemOneRateCardOneDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + editSubscriptionBodyCustomizationsItemOneRateCardOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardOneFeatureKeyMax, + ) + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardOneFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardOneKeyMax, + ) + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardOneKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardOneNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + editSubscriptionBodyCustomizationsItemOneRateCardOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe('The billing cadence of the rate card.'), + description: zod.coerce + .string() + .max( + editSubscriptionBodyCustomizationsItemOneRateCardTwoDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + editSubscriptionBodyCustomizationsItemOneRateCardTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardTwoFeatureKeyMax, + ) + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardTwoKeyMax, + ) + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemOneRateCardTwoNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the flat price.'), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.'), + zod + .object({ + amount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The amount of the unit price.'), + maximumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe('Unit price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe('The mode of the tiered price.') + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe( + 'The type of the price.', + ), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe( + 'The type of the price.', + ), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe('Tiered price with spend commitments.'), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe( + 'Dynamic price with spend commitments.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The price of one package.'), + maximumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe('The quantity per package.'), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe( + 'Package price with spend commitments.', + ), + ]) + .describe('The price of the usage based rate card.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemOneRateCardTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe('Set of provider specific tax configs.') + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + }) + .describe('Add a new item to a phase.'), + zod + .object({ + itemKey: zod.coerce.string(), + op: zod.enum(['remove_item']), + phaseKey: zod.coerce.string(), + }) + .describe('Remove an item from a phase.'), + zod + .object({ + op: zod.enum(['add_phase']), + phase: zod + .object({ + description: zod.coerce + .string() + .optional() + .describe('The description of the phase.'), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe('The percentage of the discount.'), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + editSubscriptionBodyCustomizationsItemThreePhaseDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe('The discounts on the plan.'), + duration: zod.coerce + .string() + .optional() + .describe( + 'The intended duration of the new phase.\nDuration is required when the phase will not be the last phase.', + ), + key: zod.coerce + .string() + .min(1) + .max( + editSubscriptionBodyCustomizationsItemThreePhaseKeyMax, + ) + .regex( + editSubscriptionBodyCustomizationsItemThreePhaseKeyRegExp, + ) + .describe('A locally unique identifier for the phase.'), + name: zod.coerce + .string() + .describe('The name of the phase.'), + startAfter: zod.coerce + .string() + .nullable() + .describe( + 'Interval after the subscription starts to transition to the phase.\nWhen null, the phase starts immediately after the subscription starts.', + ), + }) + .describe('Subscription phase create input.'), + }) + .describe('Add a new phase'), + zod + .object({ + op: zod.enum(['remove_phase']), + phaseKey: zod.coerce.string(), + shift: zod + .enum(['next', 'prev']) + .describe( + 'The direction of the phase shift when a phase is removed.', + ), + }) + .describe('Remove a phase'), + zod + .object({ + extendBy: zod.coerce.string(), + op: zod.enum(['stretch_phase']), + phaseKey: zod.coerce.string(), + }) + .describe('Stretch a phase'), + zod + .object({ + op: zod.enum(['unschedule_edit']), + }) + .describe('Unschedules any edits from the current phase.'), + ]) + .describe('The operation to be performed on the subscription.'), + ) + .max(editSubscriptionBodyCustomizationsMax) + .describe( + 'Batch processing commands for manipulating running subscriptions.\nThe key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .optional() + .describe( + 'Whether the billing period should be restarted.Timing configuration to allow for the changes to take effect at different times.', + ), + }) + .describe('Subscription edit input.') + +/** + * Deletes a subscription. Only scheduled subscriptions can be deleted. + * @summary Delete subscription + */ +export const deleteSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(deleteSubscriptionPathSubscriptionIdRegExp), +}) + +/** + * Create a new subscription addon, either providing the key or the id of the addon. + * @summary Create subscription addon + */ +export const createSubscriptionAddonPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreateSubscriptionAddonParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(createSubscriptionAddonPathSubscriptionIdRegExp), +}) + +export const createSubscriptionAddonBodyNameMax = 256 + +export const createSubscriptionAddonBodyDescriptionMax = 1024 + +export const createSubscriptionAddonBodyQuantityMin = 0 + +export const createSubscriptionAddonBodyAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreateSubscriptionAddonBody = zod + .object({ + addon: zod + .object({ + id: zod.coerce + .string() + .regex(createSubscriptionAddonBodyAddonIdRegExp) + .describe('The ID of the add-on.'), + }) + .describe('The add-on to create.'), + description: zod.coerce + .string() + .max(createSubscriptionAddonBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(createSubscriptionAddonBodyNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + quantity: zod.coerce + .number() + .min(createSubscriptionAddonBodyQuantityMin) + .describe( + 'The quantity of the add-on. Always 1 for single instance add-ons.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .describe( + 'The timing of the operation. After the create or update, a new entry will be created in the timeline.', + ), + }) + .describe('A subscription add-on create body.') + +/** + * List all addons of a subscription. In the returned list will match to a set unique by addonId. + * @summary List subscription addons + */ +export const listSubscriptionAddonsPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ListSubscriptionAddonsParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(listSubscriptionAddonsPathSubscriptionIdRegExp), +}) + +/** + * Get a subscription addon by id. + * @summary Get subscription addon + */ +export const getSubscriptionAddonPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getSubscriptionAddonPathSubscriptionAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetSubscriptionAddonParams = zod.object({ + subscriptionAddonId: zod.coerce + .string() + .regex(getSubscriptionAddonPathSubscriptionAddonIdRegExp), + subscriptionId: zod.coerce + .string() + .regex(getSubscriptionAddonPathSubscriptionIdRegExp), +}) + +/** + * Updates a subscription addon (allows changing the quantity: purchasing more instances or cancelling the current instances) + * @summary Update subscription addon + */ +export const updateSubscriptionAddonPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const updateSubscriptionAddonPathSubscriptionAddonIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UpdateSubscriptionAddonParams = zod.object({ + subscriptionAddonId: zod.coerce + .string() + .regex(updateSubscriptionAddonPathSubscriptionAddonIdRegExp), + subscriptionId: zod.coerce + .string() + .regex(updateSubscriptionAddonPathSubscriptionIdRegExp), +}) + +export const updateSubscriptionAddonBodyNameMax = 256 + +export const updateSubscriptionAddonBodyDescriptionMax = 1024 + +export const updateSubscriptionAddonBodyQuantityMin = 0 + +export const UpdateSubscriptionAddonBody = zod + .object({ + description: zod.coerce + .string() + .max(updateSubscriptionAddonBodyDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(updateSubscriptionAddonBodyNameMax) + .optional() + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + quantity: zod.coerce + .number() + .min(updateSubscriptionAddonBodyQuantityMin) + .optional() + .describe( + 'The quantity of the add-on. Always 1 for single instance add-ons.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .optional() + .describe( + 'The timing of the operation. After the create or update, a new entry will be created in the timeline.', + ), + }) + .describe('Resource create or update operation model.') + +/** + * Cancels the subscription. + * Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancellation time. + * @summary Cancel subscription + */ +export const cancelSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CancelSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(cancelSubscriptionPathSubscriptionIdRegExp), +}) + +export const CancelSubscriptionBody = zod.object({ + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .optional() + .describe('If not provided the subscription is canceled immediately.'), +}) + +/** + * Closes a running subscription and starts a new one according to the specification. + * Can be used for upgrades, downgrades, and plan changes. + * @summary Change subscription + */ +export const changeSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ChangeSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(changeSubscriptionPathSubscriptionIdRegExp), +}) + +export const changeSubscriptionBodyOnePlanOneKeyMax = 64 + +export const changeSubscriptionBodyOnePlanOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ + +export const changeSubscriptionBodyTwoCustomPlanOneOneNameMax = 256 + +export const changeSubscriptionBodyTwoCustomPlanOneOneDescriptionMax = 1024 + +export const changeSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMin = 3 +export const changeSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMax = 3 + +export const changeSubscriptionBodyTwoCustomPlanOneOneCurrencyOneRegExp = + /^[A-Z]{3}$/ +export const changeSubscriptionBodyTwoCustomPlanOneOneCurrencyDefault = 'USD' +export const changeSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneEnabledDefault = true +export const changeSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneModeDefault = + 'prorate_prices' +export const changeSubscriptionBodyTwoCustomPlanOneOneProRatingConfigDefault = { + enabled: true, + mode: 'prorate_prices' as const, +} as const +export const changeSubscriptionBodyTwoCustomPlanOneOneSettlementModeDefault = + 'credit_then_invoice' +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyMax = 64 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemNameMax = 256 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemDescriptionMax = 1024 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyMax = 64 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneNameMax = 256 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDescriptionMax = 1024 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyMax = 64 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault = false +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOnePaymentTermDefault = + 'in_advance' +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyMax = 64 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoNameMax = 256 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDescriptionMax = 1024 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyMax = 64 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault = false +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin = 0 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault = 1 +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax = 255 + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault = false +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp = + /^txcd_\d{8}$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault = + 'in_advance' +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault = + '1' +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ +export const changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp = + /^-?[0-9]+(\.[0-9]+)?$/ + +export const ChangeSubscriptionBody = zod + .union([ + zod + .object({ + alignment: zod + .object({ + billablesMustAlign: zod.coerce + .boolean() + .optional() + .describe( + "Whether all Billable items and RateCards must align.\nAlignment means the Price's BillingCadence must align for both duration and anchor time.", + ), + }) + .describe('Alignment configuration for a plan or subscription.') + .optional() + .describe('What alignment settings the subscription should have.'), + billingAnchor: zod.coerce + .date() + .optional() + .describe( + 'The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used.', + ), + description: zod.coerce + .string() + .optional() + .describe('Description for the Subscription.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Arbitrary metadata associated with the subscription.'), + name: zod.coerce + .string() + .optional() + .describe( + 'The name of the Subscription. If not provided the plan name is used.', + ), + plan: zod + .object({ + key: zod.coerce + .string() + .min(1) + .max(changeSubscriptionBodyOnePlanOneKeyMax) + .regex(changeSubscriptionBodyOnePlanOneKeyRegExp) + .describe('The plan key.'), + version: zod.coerce + .number() + .optional() + .describe('The plan version.'), + }) + .describe( + 'References an exact plan defaulting to the current active version.', + ) + .describe('The plan reference to change to.'), + settlementMode: zod + .enum(['credit_then_invoice', 'credit_only']) + .describe( + 'The settlement mode of a plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.', + ) + .optional() + .describe('The settlement mode of the subscription.'), + startingPhase: zod.coerce + .string() + .min(1) + .optional() + .describe( + 'The key of the phase to start the subscription in.\nIf not provided, the subscription will start in the first phase of the plan.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .describe( + 'Timing configuration for the change, when the change should take effect.\nFor changing a subscription, the accepted values depend on the subscription configuration.', + ), + }) + .describe('Change subscription based on plan.'), + zod + .object({ + billingAnchor: zod.coerce + .date() + .optional() + .describe( + 'The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used.', + ), + customPlan: zod + .object({ + alignment: zod + .object({ + billablesMustAlign: zod.coerce + .boolean() + .optional() + .describe( + "Whether all Billable items and RateCards must align.\nAlignment means the Price's BillingCadence must align for both duration and anchor time.", + ), + }) + .describe('Alignment configuration for a plan or subscription.') + .optional() + .describe('Alignment configuration for the plan.'), + billingCadence: zod.coerce + .string() + .describe( + 'The default billing cadence for subscriptions using this plan.\nDefines how often customers are billed using ISO8601 duration format.\nExamples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually).', + ), + currency: zod.coerce + .string() + .min(changeSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMin) + .max(changeSubscriptionBodyTwoCustomPlanOneOneCurrencyOneMax) + .regex(changeSubscriptionBodyTwoCustomPlanOneOneCurrencyOneRegExp) + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code.\nCustom three-letter currency codes are also supported for convenience.', + ) + .default(changeSubscriptionBodyTwoCustomPlanOneOneCurrencyDefault) + .describe('The currency code of the plan.'), + description: zod.coerce + .string() + .max(changeSubscriptionBodyTwoCustomPlanOneOneDescriptionMax) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max(changeSubscriptionBodyTwoCustomPlanOneOneNameMax) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + phases: zod + .array( + zod + .object({ + description: zod.coerce + .string() + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + duration: zod.coerce + .string() + .nullable() + .describe('The duration of the phase.'), + key: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyMax, + ) + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemKeyRegExp, + ) + .describe('A semi-unique identifier for the resource.'), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe('Additional metadata for the resource.'), + name: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + rateCards: zod + .array( + zod + .union([ + zod + .object({ + billingCadence: zod.coerce + .string() + .nullable() + .describe( + 'The billing cadence of the rate card.\nWhen null it means it is a one time fee.', + ), + description: zod.coerce + .string() + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe( + 'The percentage of the discount.', + ), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discount of the rate card. For flat fee rate cards only percentage discounts are supported.\nOnly available when price is set.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyMax, + ) + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyMax, + ) + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe( + 'Additional metadata for the resource.', + ), + name: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .object({ + amount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOnePriceOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe('Flat price with payment term.') + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemOneTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe( + 'Set of provider specific tax configs.', + ) + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['flat_fee']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A flat fee rate card defines a one-time purchase or a recurring fee.', + ), + zod + .object({ + billingCadence: zod.coerce + .string() + .describe( + 'The billing cadence of the rate card.', + ), + description: zod.coerce + .string() + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDescriptionMax, + ) + .optional() + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + discounts: zod + .object({ + percentage: zod + .object({ + percentage: zod.coerce + .number() + .describe( + 'Numeric representation of a percentage\n\n50% is represented as 50', + ) + .describe( + 'The percentage of the discount.', + ), + }) + .describe('Percentage discount.') + .optional() + .describe('The percentage discount.'), + usage: zod + .object({ + quantity: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoDiscountsOneUsageOneQuantityOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity of the usage discount.\n\nMust be positive.', + ), + }) + .describe( + 'Usage discount.\n\nUsage discount means that the first N items are free. From billing perspective\nthis means that any usage on a specific feature is considered 0 until this discount\nis exhausted.', + ) + .optional() + .describe('The usage discount.'), + }) + .describe('Discount by type on a price') + .optional() + .describe( + 'The discounts of the rate card.\n\nFlat fee rate cards only support percentage discounts.', + ), + entitlementTemplate: zod + .union([ + zod + .object({ + isSoftLimit: zod.coerce + .boolean() + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIsSoftLimitDefault, + ) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issueAfterReset: zod.coerce + .number() + .min( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetMin, + ) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityMax, + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOneIssueAfterResetPriorityDefault, + ) + .describe( + 'Defines the grant priority for the default grant.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoEntitlementTemplateOneOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod.coerce + .string() + .optional() + .describe( + 'The interval of the metered entitlement.\nDefaults to the billing cadence of the rate card.', + ), + }) + .describe( + 'The entitlement template with a metered entitlement.', + ), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['static']), + }) + .describe( + 'Entitlement template of a static entitlement.', + ), + zod + .object({ + metadata: zod + .record( + zod.string(), + zod.coerce.string(), + ) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe( + 'Additional metadata for the feature.', + ), + type: zod.enum(['boolean']), + }) + .describe( + 'Entitlement template of a boolean entitlement.', + ), + ]) + .describe( + 'Entitlement templates are used to define the entitlements of a plan.\nFeatures are omitted from the entitlement template, as they are defined in the rate card.', + ) + .optional() + .describe( + 'The entitlement of the rate card.\nOnly available when featureKey is set.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyMax, + ) + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoFeatureKeyRegExp, + ) + .optional() + .describe( + 'The feature the customer is entitled to use.', + ), + key: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyMax, + ) + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoKeyRegExp, + ) + .describe( + 'A semi-unique identifier for the resource.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .nullish() + .describe( + 'Additional metadata for the resource.', + ), + name: zod.coerce + .string() + .min(1) + .max( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoNameMax, + ) + .describe( + 'Human-readable name for the resource. Between 1 and 256 characters.', + ), + price: zod + .union([ + zod + .object({ + amount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + paymentTerm: zod + .enum(['in_advance', 'in_arrears']) + .describe( + 'The payment term of a flat price.\nOne of: in_advance or in_arrears.', + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneOnePaymentTermDefault, + ) + .describe( + 'The payment term of the flat price.\nDefaults to in advance.', + ), + type: zod + .enum(['flat']) + .describe('The type of the price.'), + }) + .describe( + 'Flat price with payment term.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + maximumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneTwoMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + type: zod + .enum(['unit']) + .describe('The type of the price.'), + }) + .describe( + 'Unit price with spend commitments.', + ), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + mode: zod + .enum(['volume', 'graduated']) + .describe( + 'The mode of the tiered price.', + ) + .describe( + 'Defines if the tiering mode is volume-based or graduated:\n- In `volume`-based tiering, the maximum quantity within a period determines the per unit price.\n- In `graduated` tiering, pricing can change as the quantity grows.', + ), + tiers: zod + .array( + zod + .object({ + flatPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemFlatPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the flat price.', + ), + type: zod + .enum(['flat']) + .describe( + 'The type of the price.', + ), + }) + .describe('Flat price.') + .nullable() + .describe( + 'The flat price component of the tier.', + ), + unitPrice: zod + .object({ + amount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUnitPriceOneAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The amount of the unit price.', + ), + type: zod + .enum(['unit']) + .describe( + 'The type of the price.', + ), + }) + .describe('Unit price.') + .nullable() + .describe( + 'The unit price component of the tier.', + ), + upToAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneThreeTiersItemUpToAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'Up to and including to this quantity will be contained in the tier.\nIf null, the tier is open-ended.', + ), + }) + .describe( + 'A price tier.\nAt least one price component is required in each tier.', + ), + ) + .min(1) + .describe( + 'The tiers of the tiered price.\nAt least one price component is required in each tier.', + ), + type: zod + .enum(['tiered']) + .describe( + 'The type of the price.\n\nOne of: flat, unit, or tiered.', + ), + }) + .describe( + 'Tiered price with spend commitments.', + ), + zod + .object({ + maximumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + multiplier: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFourMultiplierDefault, + ) + .describe( + 'The multiplier to apply to the base price to get the dynamic price.\n\nExamples:\n- 0.0: the price is zero\n- 0.5: the price is 50% of the base price\n- 1.0: the price is the same as the base price\n- 1.5: the price is 150% of the base price', + ), + type: zod + .enum(['dynamic']) + .describe('The type of the price.'), + }) + .describe( + 'Dynamic price with spend commitments.', + ), + zod + .object({ + amount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The price of one package.', + ), + maximumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMaximumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is limited to spend at most the amount.', + ), + minimumAmount: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveMinimumAmountOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .optional() + .describe( + 'The customer is committed to spend at least the amount.', + ), + quantityPerPackage: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoPriceOneFiveQuantityPerPackageOneRegExp, + ) + .describe( + 'Numeric represents an arbitrary precision number.', + ) + .describe( + 'The quantity per package.', + ), + type: zod + .enum(['package']) + .describe('The type of the price.'), + }) + .describe( + 'Package price with spend commitments.', + ), + ]) + .describe( + 'The price of the usage based rate card.', + ) + .nullable() + .describe( + 'The price of the rate card.\nWhen null, the feature or service is free.', + ), + taxConfig: zod + .object({ + behavior: zod + .enum(['inclusive', 'exclusive']) + .describe( + 'Tax behavior.\n\nThis enum is used to specify whether tax is included in the price or excluded from the price.', + ) + .optional() + .describe( + "Tax behavior.\n\nIf not specified the billing profile is used to determine the tax behavior.\nIf not specified in the billing profile, the provider's default behavior is used.", + ), + customInvoicing: zod + .object({ + code: zod.coerce + .string() + .describe( + 'Tax code.\n\nThe tax code should be interpreted by the custom invoicing provider.', + ), + }) + .describe('Custom invoicing tax config.') + .optional() + .describe('Custom invoicing tax config.'), + stripe: zod + .object({ + code: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneStripeOneCodeRegExp, + ) + .describe( + 'Product tax code.\n\nSee: https://docs.stripe.com/tax/tax-codes', + ), + }) + .describe('The tax config for Stripe.') + .optional() + .describe('Stripe tax config.'), + taxCodeId: zod.coerce + .string() + .regex( + changeSubscriptionBodyTwoCustomPlanOneOnePhasesItemRateCardsItemTwoTaxConfigOneTaxCodeIdRegExp, + ) + .optional() + .describe( + 'Tax code reference.\n\nWhen both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence:\nthe referenced tax code entity is used and `stripe.code` is ignored.', + ), + }) + .describe( + 'Set of provider specific tax configs.', + ) + .optional() + .describe( + 'The tax config of the rate card.\nWhen undefined, the tax config of the feature or the default tax config of the plan is used.', + ), + type: zod + .enum(['usage_based']) + .describe('The type of the RateCard.'), + }) + .describe( + 'A usage-based rate card defines a price based on usage.', + ), + ]) + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ), + ) + .describe('The rate cards of the plan.'), + }) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.", + ), + ) + .min(1) + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.\nA phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices.", + ), + proRatingConfig: zod + .object({ + enabled: zod.coerce + .boolean() + .default( + changeSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneEnabledDefault, + ) + .describe('Whether pro-rating is enabled for this plan.'), + mode: zod + .enum(['prorate_prices']) + .describe( + 'Pro-rating mode options for handling billing period changes.', + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOneProRatingConfigOneModeDefault, + ) + .describe( + 'How to handle pro-rating for billing period changes.', + ), + }) + .describe('Configuration for pro-rating behavior.') + .default( + changeSubscriptionBodyTwoCustomPlanOneOneProRatingConfigDefault, + ) + .describe( + 'Default pro-rating configuration for subscriptions using this plan.', + ), + settlementMode: zod + .enum(['credit_then_invoice', 'credit_only']) + .describe( + 'The settlement mode of a plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.', + ) + .default( + changeSubscriptionBodyTwoCustomPlanOneOneSettlementModeDefault, + ) + .describe( + 'The settlement mode of the plan.\nIt determines how the billing system generates invoices and credits for the subscriptions using this plan.\n- credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced.\n- credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription.\nThis is the default and most common settlement mode.', + ), + }) + .describe('The template for omitting properties.') + .describe( + 'Plan input for custom subscription creation (without key and version).', + ) + .describe( + 'The custom plan description which defines the Subscription.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .describe( + 'Timing configuration for the change, when the change should take effect.\nFor changing a subscription, the accepted values depend on the subscription configuration.', + ), + }) + .describe('Change a custom subscription.'), + ]) + .describe('Change a subscription.') + +/** + * Migrates the subscripiton to the provided version of the current plan. + * If possible, the migration will be done immediately. + * If not, the migration will be scheduled to the end of the current billing period. + * @summary Migrate subscription + */ +export const migrateSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const MigrateSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(migrateSubscriptionPathSubscriptionIdRegExp), +}) + +export const migrateSubscriptionBodyTimingDefault = 'immediate' + +export const MigrateSubscriptionBody = zod.object({ + billingAnchor: zod.coerce + .date() + .optional() + .describe( + 'The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used.', + ), + startingPhase: zod.coerce + .string() + .min(1) + .optional() + .describe( + 'The key of the phase to start the subscription in.\nIf not provided, the subscription will start in the first phase of the plan.', + ), + targetVersion: zod.coerce + .number() + .min(1) + .optional() + .describe( + 'The version of the plan to migrate to.\nIf not provided, the subscription will migrate to the latest version of the current plan.', + ), + timing: zod + .union([ + zod + .enum(['immediate', 'next_billing_cycle']) + .describe( + 'Subscription edit timing.\nWhen immediate, the requested changes take effect immediately.\nWhen nextBillingCycle, the requested changes take effect at the next billing cycle.', + ), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe( + 'Subscription edit timing defined when the changes should take effect.\nIf the provided configuration is not supported by the subscription, an error will be returned.', + ) + .default(migrateSubscriptionBodyTimingDefault) + .describe( + 'Timing configuration for the migration, when the migration should take effect.\nIf not supported by the subscription, 400 will be returned.', + ), +}) + +/** + * Restores a canceled subscription. + * Any subscription scheduled to start later will be deleted and this subscription will be continued indefinitely. + * @deprecated + * @summary Restore subscription + */ +export const restoreSubscriptionPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const RestoreSubscriptionParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(restoreSubscriptionPathSubscriptionIdRegExp), +}) + +/** + * Cancels the scheduled cancelation. + * @summary Unschedule cancelation + */ +export const unscheduleCancelationPathSubscriptionIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const UnscheduleCancelationParams = zod.object({ + subscriptionId: zod.coerce + .string() + .regex(unscheduleCancelationPathSubscriptionIdRegExp), +}) + +/** + * OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given customer can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + * @summary Create a customer entitlement + */ +export const createCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createCustomerEntitlementV2PathCustomerIdOrKeyTwoMax = 256 + +export const CreateCustomerEntitlementV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(createCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(createCustomerEntitlementV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const createCustomerEntitlementV2BodyOneFeatureKeyMax = 64 + +export const createCustomerEntitlementV2BodyOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createCustomerEntitlementV2BodyOneFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createCustomerEntitlementV2BodyOneIsSoftLimitDefault = false +export const createCustomerEntitlementV2BodyOneUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createCustomerEntitlementV2BodyOnePreserveOverageAtResetDefault = false +export const createCustomerEntitlementV2BodyOneIssueAfterResetMin = 0 + +export const createCustomerEntitlementV2BodyOneIssueAfterResetPriorityDefault = 1 +export const createCustomerEntitlementV2BodyOneIssueAfterResetPriorityMax = 255 + +export const createCustomerEntitlementV2BodyOneIssueOneAmountMin = 0 + +export const createCustomerEntitlementV2BodyOneIssueOnePriorityDefault = 1 +export const createCustomerEntitlementV2BodyOneIssueOnePriorityMax = 255 + +export const createCustomerEntitlementV2BodyOneGrantsItemAmountMin = 0 + +export const createCustomerEntitlementV2BodyOneGrantsItemPriorityMax = 255 + +export const createCustomerEntitlementV2BodyOneGrantsItemMinRolloverAmountDefault = 0 +export const createCustomerEntitlementV2BodyOneGrantsItemRecurrenceOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createCustomerEntitlementV2BodyOneGrantsItemExpirationOneCountMax = 1000 + +export const createCustomerEntitlementV2BodyTwoFeatureKeyMax = 64 + +export const createCustomerEntitlementV2BodyTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createCustomerEntitlementV2BodyTwoFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createCustomerEntitlementV2BodyTwoUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createCustomerEntitlementV2BodyThreeFeatureKeyMax = 64 + +export const createCustomerEntitlementV2BodyThreeFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const createCustomerEntitlementV2BodyThreeFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createCustomerEntitlementV2BodyThreeUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ + +export const CreateCustomerEntitlementV2Body = zod + .union([ + zod + .object({ + featureId: zod.coerce + .string() + .regex(createCustomerEntitlementV2BodyOneFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createCustomerEntitlementV2BodyOneFeatureKeyMax) + .regex(createCustomerEntitlementV2BodyOneFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + grants: zod + .array( + zod + .object({ + amount: zod.coerce + .number() + .min(createCustomerEntitlementV2BodyOneGrantsItemAmountMin) + .describe( + 'The amount to grant. Should be a positive number.', + ), + annotations: zod + .record(zod.string(), zod.unknown()) + .describe( + 'Set of key-value pairs managed by the system. Cannot be modified by user.', + ) + .optional() + .describe('Grant annotations'), + effectiveAt: zod.coerce + .date() + .describe( + 'Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute).', + ), + expiration: zod + .object({ + count: zod.coerce + .number() + .min(1) + .max( + createCustomerEntitlementV2BodyOneGrantsItemExpirationOneCountMax, + ) + .describe( + 'The number of time units in the expiration period.', + ), + duration: zod + .enum(['HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe('The expiration duration enum') + .describe('The unit of time for the expiration period.'), + }) + .describe('The grant expiration definition') + .optional() + .describe( + 'The grant expiration definition. If no expiration is provided, the grant can be active indefinitely.', + ), + maxRolloverAmount: zod.coerce + .number() + .optional() + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('The grant metadata.'), + minRolloverAmount: zod.coerce + .number() + .default( + createCustomerEntitlementV2BodyOneGrantsItemMinRolloverAmountDefault, + ) + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + priority: zod.coerce + .number() + .min(1) + .max(createCustomerEntitlementV2BodyOneGrantsItemPriorityMax) + .optional() + .describe( + 'The priority of the grant. Grants with higher priority are applied first.\nPriority is a positive decimal numbers. With lower numbers indicating higher importance.\nFor example, a priority of 1 is more urgent than a priority of 2.\nWhen there are several grants available for the same subject, the system selects the grant with the highest priority.\nIn cases where grants share the same priority level, the grant closest to its expiration will be used first.\nIn the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first.', + ), + recurrence: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe( + 'A date-time anchor to base the recurring period on.', + ), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createCustomerEntitlementV2BodyOneGrantsItemRecurrenceOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The subject of the grant.'), + }) + .describe('The grant creation input.'), + ) + .optional() + .describe('Grants'), + isSoftLimit: zod.coerce + .boolean() + .default(createCustomerEntitlementV2BodyOneIsSoftLimitDefault) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issue: zod + .object({ + amount: zod.coerce + .number() + .min(createCustomerEntitlementV2BodyOneIssueOneAmountMin) + .describe('The initial grant amount'), + priority: zod.coerce + .number() + .min(1) + .max(createCustomerEntitlementV2BodyOneIssueOnePriorityMax) + .default( + createCustomerEntitlementV2BodyOneIssueOnePriorityDefault, + ) + .describe('The priority of the issue after reset'), + }) + .describe('Issue after reset') + .optional() + .describe('Issue after reset'), + issueAfterReset: zod.coerce + .number() + .min(createCustomerEntitlementV2BodyOneIssueAfterResetMin) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max(createCustomerEntitlementV2BodyOneIssueAfterResetPriorityMax) + .default( + createCustomerEntitlementV2BodyOneIssueAfterResetPriorityDefault, + ) + .describe('Defines the grant priority for the default grant.'), + measureUsageFrom: zod + .union([ + zod + .enum(['CURRENT_PERIOD_START', 'NOW']) + .describe('Start of measurement options'), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe('Measure usage from') + .optional() + .describe( + 'Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + createCustomerEntitlementV2BodyOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createCustomerEntitlementV2BodyOneUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for metered entitlement'), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + featureId: zod.coerce + .string() + .regex(createCustomerEntitlementV2BodyTwoFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createCustomerEntitlementV2BodyTwoFeatureKeyMax) + .regex(createCustomerEntitlementV2BodyTwoFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createCustomerEntitlementV2BodyTwoUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for static entitlement'), + zod + .object({ + featureId: zod.coerce + .string() + .regex(createCustomerEntitlementV2BodyThreeFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(createCustomerEntitlementV2BodyThreeFeatureKeyMax) + .regex(createCustomerEntitlementV2BodyThreeFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createCustomerEntitlementV2BodyThreeUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for boolean entitlement'), + ]) + .describe('Create inputs for entitlement') + +/** + * List all entitlements for a customer. For checking entitlement access, use the /value endpoint instead. + * @summary List customer entitlements + */ +export const listCustomerEntitlementsV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listCustomerEntitlementsV2PathCustomerIdOrKeyTwoMax = 256 + +export const ListCustomerEntitlementsV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(listCustomerEntitlementsV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(listCustomerEntitlementsV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const listCustomerEntitlementsV2QueryIncludeDeletedDefault = false +export const listCustomerEntitlementsV2QueryPageDefault = 1 + +export const listCustomerEntitlementsV2QueryPageSizeDefault = 100 +export const listCustomerEntitlementsV2QueryPageSizeMax = 1000 + +export const listCustomerEntitlementsV2QueryOrderDefault = 'ASC' + +export const ListCustomerEntitlementsV2QueryParams = zod.object({ + includeDeleted: zod.coerce + .boolean() + .default(listCustomerEntitlementsV2QueryIncludeDeletedDefault), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listCustomerEntitlementsV2QueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listCustomerEntitlementsV2QueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listCustomerEntitlementsV2QueryPageSizeMax) + .default(listCustomerEntitlementsV2QueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Get entitlement by feature key. For checking entitlement access, use the /value endpoint instead. + * If featureKey is used, the entitlement is resolved for the current timestamp. + * @summary Get customer entitlement + */ +export const getCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerEntitlementV2PathCustomerIdOrKeyTwoMax = 256 + +export const getCustomerEntitlementV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const getCustomerEntitlementV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetCustomerEntitlementV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementV2PathEntitlementIdOrFeatureKeyMax) + .regex(getCustomerEntitlementV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +/** + * Deleting an entitlement revokes access to the associated feature. As a single customer can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + * As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + * @summary Delete customer entitlement + */ +export const deleteCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const deleteCustomerEntitlementV2PathCustomerIdOrKeyTwoMax = 256 + +export const deleteCustomerEntitlementV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const deleteCustomerEntitlementV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const DeleteCustomerEntitlementV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(deleteCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(deleteCustomerEntitlementV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(deleteCustomerEntitlementV2PathEntitlementIdOrFeatureKeyMax) + .regex(deleteCustomerEntitlementV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +/** + * List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + * @summary List customer entitlement grants + */ +export const listCustomerEntitlementGrantsV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listCustomerEntitlementGrantsV2PathCustomerIdOrKeyTwoMax = 256 + +export const listCustomerEntitlementGrantsV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const listCustomerEntitlementGrantsV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ListCustomerEntitlementGrantsV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(listCustomerEntitlementGrantsV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(listCustomerEntitlementGrantsV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(listCustomerEntitlementGrantsV2PathEntitlementIdOrFeatureKeyMax) + .regex(listCustomerEntitlementGrantsV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +export const listCustomerEntitlementGrantsV2QueryIncludeDeletedDefault = false +export const listCustomerEntitlementGrantsV2QueryPageDefault = 1 + +export const listCustomerEntitlementGrantsV2QueryPageSizeDefault = 100 +export const listCustomerEntitlementGrantsV2QueryPageSizeMax = 1000 + +export const listCustomerEntitlementGrantsV2QueryOffsetDefault = 0 +export const listCustomerEntitlementGrantsV2QueryOffsetMin = 0 + +export const listCustomerEntitlementGrantsV2QueryLimitDefault = 100 +export const listCustomerEntitlementGrantsV2QueryLimitMax = 1000 + +export const listCustomerEntitlementGrantsV2QueryOrderDefault = 'ASC' + +export const ListCustomerEntitlementGrantsV2QueryParams = zod.object({ + includeDeleted: zod.coerce + .boolean() + .default(listCustomerEntitlementGrantsV2QueryIncludeDeletedDefault), + limit: zod.coerce + .number() + .min(1) + .max(listCustomerEntitlementGrantsV2QueryLimitMax) + .default(listCustomerEntitlementGrantsV2QueryLimitDefault) + .describe('Number of items to return.\n\nDefault is 100.'), + offset: zod.coerce + .number() + .min(listCustomerEntitlementGrantsV2QueryOffsetMin) + .default(listCustomerEntitlementGrantsV2QueryOffsetDefault) + .describe('Number of items to skip.\n\nDefault is 0.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listCustomerEntitlementGrantsV2QueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listCustomerEntitlementGrantsV2QueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listCustomerEntitlementGrantsV2QueryPageSizeMax) + .default(listCustomerEntitlementGrantsV2QueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + * + * A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + * + * Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + * + * Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + * + * Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * + * Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + * @summary Create customer entitlement grant + */ +export const createCustomerEntitlementGrantV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const createCustomerEntitlementGrantV2PathCustomerIdOrKeyTwoMax = 256 + +export const createCustomerEntitlementGrantV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const createCustomerEntitlementGrantV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const CreateCustomerEntitlementGrantV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(createCustomerEntitlementGrantV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(createCustomerEntitlementGrantV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(createCustomerEntitlementGrantV2PathEntitlementIdOrFeatureKeyMax) + .regex(createCustomerEntitlementGrantV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +export const createCustomerEntitlementGrantV2BodyAmountMin = 0 + +export const createCustomerEntitlementGrantV2BodyPriorityMax = 255 + +export const createCustomerEntitlementGrantV2BodyMinRolloverAmountDefault = 0 +export const createCustomerEntitlementGrantV2BodyRecurrenceOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const createCustomerEntitlementGrantV2BodyExpirationOneCountMax = 1000 + +export const CreateCustomerEntitlementGrantV2Body = zod + .object({ + amount: zod.coerce + .number() + .min(createCustomerEntitlementGrantV2BodyAmountMin) + .describe('The amount to grant. Should be a positive number.'), + annotations: zod + .record(zod.string(), zod.unknown()) + .describe( + 'Set of key-value pairs managed by the system. Cannot be modified by user.', + ) + .optional() + .describe('Grant annotations'), + effectiveAt: zod.coerce + .date() + .describe( + 'Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute).', + ), + expiration: zod + .object({ + count: zod.coerce + .number() + .min(1) + .max(createCustomerEntitlementGrantV2BodyExpirationOneCountMax) + .describe('The number of time units in the expiration period.'), + duration: zod + .enum(['HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe('The expiration duration enum') + .describe('The unit of time for the expiration period.'), + }) + .describe('The grant expiration definition') + .optional() + .describe( + 'The grant expiration definition. If no expiration is provided, the grant can be active indefinitely.', + ), + maxRolloverAmount: zod.coerce + .number() + .optional() + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('The grant metadata.'), + minRolloverAmount: zod.coerce + .number() + .default(createCustomerEntitlementGrantV2BodyMinRolloverAmountDefault) + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + priority: zod.coerce + .number() + .min(1) + .max(createCustomerEntitlementGrantV2BodyPriorityMax) + .optional() + .describe( + 'The priority of the grant. Grants with higher priority are applied first.\nPriority is a positive decimal numbers. With lower numbers indicating higher importance.\nFor example, a priority of 1 is more urgent than a priority of 2.\nWhen there are several grants available for the same subject, the system selects the grant with the highest priority.\nIn cases where grants share the same priority level, the grant closest to its expiration will be used first.\nIn the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first.', + ), + recurrence: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + createCustomerEntitlementGrantV2BodyRecurrenceOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The subject of the grant.'), + }) + .describe('The grant creation input.') + +/** + * Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + * + * WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + * @summary Get customer entitlement history + */ +export const getCustomerEntitlementHistoryV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerEntitlementHistoryV2PathCustomerIdOrKeyTwoMax = 256 + +export const getCustomerEntitlementHistoryV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const getCustomerEntitlementHistoryV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetCustomerEntitlementHistoryV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerEntitlementHistoryV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementHistoryV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementHistoryV2PathEntitlementIdOrFeatureKeyMax) + .regex(getCustomerEntitlementHistoryV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +export const getCustomerEntitlementHistoryV2QueryWindowTimeZoneDefault = 'UTC' + +export const GetCustomerEntitlementHistoryV2QueryParams = zod.object({ + from: zod.coerce + .date() + .optional() + .describe( + 'Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter.', + ), + to: zod.coerce + .date() + .optional() + .describe( + 'End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now.\nIf not now then gets truncated to the granularity of the underlying meter.', + ), + windowSize: zod + .enum(['MINUTE', 'HOUR', 'DAY', 'MONTH']) + .describe('Windowsize'), + windowTimeZone: zod.coerce + .string() + .default(getCustomerEntitlementHistoryV2QueryWindowTimeZoneDefault) + .describe('The timezone used when calculating the windows.'), +}) + +/** + * Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided customer-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + * + * This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + * @summary Override customer entitlement + */ +export const overrideCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideCustomerEntitlementV2PathCustomerIdOrKeyTwoMax = 256 + +export const overrideCustomerEntitlementV2PathEntitlementIdOrFeatureKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideCustomerEntitlementV2PathEntitlementIdOrFeatureKeyTwoMax = 256 + +export const OverrideCustomerEntitlementV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(overrideCustomerEntitlementV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(overrideCustomerEntitlementV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.union([ + zod.coerce + .string() + .regex( + overrideCustomerEntitlementV2PathEntitlementIdOrFeatureKeyOneRegExp, + ) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(overrideCustomerEntitlementV2PathEntitlementIdOrFeatureKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), +}) + +export const overrideCustomerEntitlementV2BodyOneFeatureKeyMax = 64 + +export const overrideCustomerEntitlementV2BodyOneFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const overrideCustomerEntitlementV2BodyOneFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideCustomerEntitlementV2BodyOneIsSoftLimitDefault = false +export const overrideCustomerEntitlementV2BodyOneUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const overrideCustomerEntitlementV2BodyOnePreserveOverageAtResetDefault = false +export const overrideCustomerEntitlementV2BodyOneIssueAfterResetMin = 0 + +export const overrideCustomerEntitlementV2BodyOneIssueAfterResetPriorityDefault = 1 +export const overrideCustomerEntitlementV2BodyOneIssueAfterResetPriorityMax = 255 + +export const overrideCustomerEntitlementV2BodyOneIssueOneAmountMin = 0 + +export const overrideCustomerEntitlementV2BodyOneIssueOnePriorityDefault = 1 +export const overrideCustomerEntitlementV2BodyOneIssueOnePriorityMax = 255 + +export const overrideCustomerEntitlementV2BodyOneGrantsItemAmountMin = 0 + +export const overrideCustomerEntitlementV2BodyOneGrantsItemPriorityMax = 255 + +export const overrideCustomerEntitlementV2BodyOneGrantsItemMinRolloverAmountDefault = 0 +export const overrideCustomerEntitlementV2BodyOneGrantsItemRecurrenceOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const overrideCustomerEntitlementV2BodyOneGrantsItemExpirationOneCountMax = 1000 + +export const overrideCustomerEntitlementV2BodyTwoFeatureKeyMax = 64 + +export const overrideCustomerEntitlementV2BodyTwoFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const overrideCustomerEntitlementV2BodyTwoFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideCustomerEntitlementV2BodyTwoUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ +export const overrideCustomerEntitlementV2BodyThreeFeatureKeyMax = 64 + +export const overrideCustomerEntitlementV2BodyThreeFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$/ +export const overrideCustomerEntitlementV2BodyThreeFeatureIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const overrideCustomerEntitlementV2BodyThreeUsagePeriodOneIntervalOneOneRegExp = + /^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/ + +export const OverrideCustomerEntitlementV2Body = zod + .union([ + zod + .object({ + featureId: zod.coerce + .string() + .regex(overrideCustomerEntitlementV2BodyOneFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(overrideCustomerEntitlementV2BodyOneFeatureKeyMax) + .regex(overrideCustomerEntitlementV2BodyOneFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + grants: zod + .array( + zod + .object({ + amount: zod.coerce + .number() + .min(overrideCustomerEntitlementV2BodyOneGrantsItemAmountMin) + .describe( + 'The amount to grant. Should be a positive number.', + ), + annotations: zod + .record(zod.string(), zod.unknown()) + .describe( + 'Set of key-value pairs managed by the system. Cannot be modified by user.', + ) + .optional() + .describe('Grant annotations'), + effectiveAt: zod.coerce + .date() + .describe( + 'Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute).', + ), + expiration: zod + .object({ + count: zod.coerce + .number() + .min(1) + .max( + overrideCustomerEntitlementV2BodyOneGrantsItemExpirationOneCountMax, + ) + .describe( + 'The number of time units in the expiration period.', + ), + duration: zod + .enum(['HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe('The expiration duration enum') + .describe('The unit of time for the expiration period.'), + }) + .describe('The grant expiration definition') + .optional() + .describe( + 'The grant expiration definition. If no expiration is provided, the grant can be active indefinitely.', + ), + maxRolloverAmount: zod.coerce + .number() + .optional() + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('The grant metadata.'), + minRolloverAmount: zod.coerce + .number() + .default( + overrideCustomerEntitlementV2BodyOneGrantsItemMinRolloverAmountDefault, + ) + .describe( + 'Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset.\nBalance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount))', + ), + priority: zod.coerce + .number() + .min(1) + .max( + overrideCustomerEntitlementV2BodyOneGrantsItemPriorityMax, + ) + .optional() + .describe( + 'The priority of the grant. Grants with higher priority are applied first.\nPriority is a positive decimal numbers. With lower numbers indicating higher importance.\nFor example, a priority of 1 is more urgent than a priority of 2.\nWhen there are several grants available for the same subject, the system selects the grant with the highest priority.\nIn cases where grants share the same priority level, the grant closest to its expiration will be used first.\nIn the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first.', + ), + recurrence: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe( + 'A date-time anchor to base the recurring period on.', + ), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideCustomerEntitlementV2BodyOneGrantsItemRecurrenceOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The subject of the grant.'), + }) + .describe('The grant creation input.'), + ) + .optional() + .describe('Grants'), + isSoftLimit: zod.coerce + .boolean() + .default(overrideCustomerEntitlementV2BodyOneIsSoftLimitDefault) + .describe( + 'If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true.', + ), + issue: zod + .object({ + amount: zod.coerce + .number() + .min(overrideCustomerEntitlementV2BodyOneIssueOneAmountMin) + .describe('The initial grant amount'), + priority: zod.coerce + .number() + .min(1) + .max(overrideCustomerEntitlementV2BodyOneIssueOnePriorityMax) + .default( + overrideCustomerEntitlementV2BodyOneIssueOnePriorityDefault, + ) + .describe('The priority of the issue after reset'), + }) + .describe('Issue after reset') + .optional() + .describe('Issue after reset'), + issueAfterReset: zod.coerce + .number() + .min(overrideCustomerEntitlementV2BodyOneIssueAfterResetMin) + .optional() + .describe( + 'You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance.\nIf an amount is specified here, a grant will be created alongside the entitlement with the specified amount.\nThat grant will have it\'s rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here.\nManually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same.', + ), + issueAfterResetPriority: zod.coerce + .number() + .min(1) + .max(overrideCustomerEntitlementV2BodyOneIssueAfterResetPriorityMax) + .default( + overrideCustomerEntitlementV2BodyOneIssueAfterResetPriorityDefault, + ) + .describe('Defines the grant priority for the default grant.'), + measureUsageFrom: zod + .union([ + zod + .enum(['CURRENT_PERIOD_START', 'NOW']) + .describe('Start of measurement options'), + zod.coerce + .date() + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ), + ]) + .describe('Measure usage from') + .optional() + .describe( + 'Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + preserveOverageAtReset: zod.coerce + .boolean() + .default( + overrideCustomerEntitlementV2BodyOnePreserveOverageAtResetDefault, + ) + .describe( + 'If true, the overage is preserved at reset. If false, the usage is reset to 0.', + ), + type: zod.enum(['metered']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideCustomerEntitlementV2BodyOneUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for metered entitlement'), + zod + .object({ + config: zod.coerce + .string() + .describe( + 'The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object.', + ), + featureId: zod.coerce + .string() + .regex(overrideCustomerEntitlementV2BodyTwoFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(overrideCustomerEntitlementV2BodyTwoFeatureKeyMax) + .regex(overrideCustomerEntitlementV2BodyTwoFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['static']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideCustomerEntitlementV2BodyTwoUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for static entitlement'), + zod + .object({ + featureId: zod.coerce + .string() + .regex(overrideCustomerEntitlementV2BodyThreeFeatureIdRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + featureKey: zod.coerce + .string() + .min(1) + .max(overrideCustomerEntitlementV2BodyThreeFeatureKeyMax) + .regex(overrideCustomerEntitlementV2BodyThreeFeatureKeyRegExp) + .optional() + .describe( + 'The feature the subject is entitled to use.\nEither featureKey or featureId is required.', + ), + metadata: zod + .record(zod.string(), zod.coerce.string()) + .describe( + 'Set of key-value pairs.\nMetadata can be used to store additional information about a resource.', + ) + .optional() + .describe('Additional metadata for the feature.'), + type: zod.enum(['boolean']), + usagePeriod: zod + .object({ + anchor: zod.coerce + .date() + .optional() + .describe('A date-time anchor to base the recurring period on.'), + interval: zod + .union([ + zod.coerce + .string() + .regex( + overrideCustomerEntitlementV2BodyThreeUsagePeriodOneIntervalOneOneRegExp, + ), + zod + .enum(['DAY', 'WEEK', 'MONTH', 'YEAR']) + .describe( + 'The unit of time for the interval.\nOne of: `day`, `week`, `month`, or `year`.', + ), + ]) + .describe('Period duration for the recurrence') + .describe('The unit of time for the interval.'), + }) + .describe('Recurring period with an interval and an anchor.') + .optional() + .describe('The usage period associated with the entitlement.'), + }) + .describe('Create inputs for boolean entitlement'), + ]) + .describe('Create inputs for entitlement') + +/** + * Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the customers billing period to enforce usage based on their subscription. + * + * Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + * @summary Reset customer entitlement + */ +export const resetCustomerEntitlementUsageV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const resetCustomerEntitlementUsageV2PathCustomerIdOrKeyTwoMax = 256 + +export const resetCustomerEntitlementUsageV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const resetCustomerEntitlementUsageV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const ResetCustomerEntitlementUsageV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(resetCustomerEntitlementUsageV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(resetCustomerEntitlementUsageV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(resetCustomerEntitlementUsageV2PathEntitlementIdOrFeatureKeyMax) + .regex(resetCustomerEntitlementUsageV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +export const ResetCustomerEntitlementUsageV2Body = zod + .object({ + effectiveAt: zod.coerce + .date() + .optional() + .describe( + 'The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored.', + ), + preserveOverage: zod.coerce + .boolean() + .optional() + .describe( + "Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior.\n- If true, the overage is preserved.\n- If false, the overage is forgiven.", + ), + retainAnchor: zod.coerce + .boolean() + .optional() + .describe( + 'Determines whether the usage period anchor is retained or reset to the effectiveAt time.\n- If true, the usage period anchor is retained.\n- If false, the usage period anchor is reset to the effectiveAt time.', + ), + }) + .describe('Reset parameters') + +/** + * Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + * @summary Get customer entitlement value + */ +export const getCustomerEntitlementValueV2PathCustomerIdOrKeyOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const getCustomerEntitlementValueV2PathCustomerIdOrKeyTwoMax = 256 + +export const getCustomerEntitlementValueV2PathEntitlementIdOrFeatureKeyMax = 64 + +export const getCustomerEntitlementValueV2PathEntitlementIdOrFeatureKeyRegExp = + /^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetCustomerEntitlementValueV2Params = zod.object({ + customerIdOrKey: zod.union([ + zod.coerce + .string() + .regex(getCustomerEntitlementValueV2PathCustomerIdOrKeyOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementValueV2PathCustomerIdOrKeyTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]), + entitlementIdOrFeatureKey: zod.coerce + .string() + .min(1) + .max(getCustomerEntitlementValueV2PathEntitlementIdOrFeatureKeyMax) + .regex(getCustomerEntitlementValueV2PathEntitlementIdOrFeatureKeyRegExp), +}) + +export const GetCustomerEntitlementValueV2QueryParams = zod.object({ + time: zod.coerce.date().optional(), +}) + +/** + * List all entitlements for all the customers and features. This endpoint is intended for administrative purposes only. + * To fetch the entitlements of a specific subject please use the /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + * @summary List all entitlements + */ +export const listEntitlementsV2QueryExcludeInactiveDefault = false +export const listEntitlementsV2QueryPageDefault = 1 + +export const listEntitlementsV2QueryPageSizeDefault = 100 +export const listEntitlementsV2QueryPageSizeMax = 1000 + +export const listEntitlementsV2QueryOffsetDefault = 0 +export const listEntitlementsV2QueryOffsetMin = 0 + +export const listEntitlementsV2QueryLimitDefault = 100 +export const listEntitlementsV2QueryLimitMax = 1000 + +export const listEntitlementsV2QueryOrderDefault = 'ASC' + +export const ListEntitlementsV2QueryParams = zod.object({ + customerIds: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple customers.\n\nUsage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9`', + ), + customerKeys: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple customers.\n\nUsage: `?customerKeys=customer-1&customerKeys=customer-3`', + ), + entitlementType: zod + .array( + zod + .enum(['metered', 'boolean', 'static']) + .describe('Type of the entitlement.'), + ) + .optional() + .describe( + 'Filtering by multiple entitlement types.\n\nUsage: `?entitlementType=metered&entitlementType=boolean`', + ), + excludeInactive: zod.coerce + .boolean() + .default(listEntitlementsV2QueryExcludeInactiveDefault) + .describe( + 'Exclude inactive entitlements in the response (those scheduled for later or earlier)', + ), + feature: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple features.\n\nUsage: `?feature=feature-1&feature=feature-2`', + ), + limit: zod.coerce + .number() + .min(1) + .max(listEntitlementsV2QueryLimitMax) + .default(listEntitlementsV2QueryLimitDefault) + .describe('Number of items to return.\n\nDefault is 100.'), + offset: zod.coerce + .number() + .min(listEntitlementsV2QueryOffsetMin) + .default(listEntitlementsV2QueryOffsetDefault) + .describe('Number of items to skip.\n\nDefault is 0.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listEntitlementsV2QueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listEntitlementsV2QueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listEntitlementsV2QueryPageSizeMax) + .default(listEntitlementsV2QueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) + +/** + * Get entitlement by ID. + * @summary Get entitlement by ID + */ +export const getEntitlementByIdV2PathEntitlementIdRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ + +export const GetEntitlementByIdV2Params = zod.object({ + entitlementId: zod.coerce + .string() + .regex(getEntitlementByIdV2PathEntitlementIdRegExp), +}) + +/** + * List ingested events with advanced filtering and cursor pagination. + * @summary List ingested events + */ +export const listEventsV2QueryLimitDefault = 100 +export const listEventsV2QueryLimitMax = 100 + +export const listEventsV2QueryClientIdMax = 36 + +export const ListEventsV2QueryParams = zod.object({ + clientId: zod.coerce + .string() + .min(1) + .max(listEventsV2QueryClientIdMax) + .optional() + .describe('Client ID\nUseful to track progress of a query.'), + cursor: zod.coerce + .string() + .optional() + .describe('The cursor after which to start the pagination.'), + limit: zod.coerce + .number() + .min(1) + .max(listEventsV2QueryLimitMax) + .default(listEventsV2QueryLimitDefault) + .describe('The limit of the pagination.'), +}) + +/** + * List all grants for all the customers and entitlements. This endpoint is intended for administrative purposes only. + * To fetch the grants of a specific entitlement please use the /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * @summary List grants + */ +export const listGrantsV2QueryCustomerItemOneRegExp = + /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/ +export const listGrantsV2QueryCustomerItemTwoMax = 256 + +export const listGrantsV2QueryIncludeDeletedDefault = false +export const listGrantsV2QueryPageDefault = 1 + +export const listGrantsV2QueryPageSizeDefault = 100 +export const listGrantsV2QueryPageSizeMax = 1000 + +export const listGrantsV2QueryOffsetDefault = 0 +export const listGrantsV2QueryOffsetMin = 0 + +export const listGrantsV2QueryLimitDefault = 100 +export const listGrantsV2QueryLimitMax = 1000 + +export const listGrantsV2QueryOrderDefault = 'ASC' + +export const ListGrantsV2QueryParams = zod.object({ + customer: zod + .array( + zod + .union([ + zod.coerce + .string() + .regex(listGrantsV2QueryCustomerItemOneRegExp) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier).', + ), + zod.coerce + .string() + .min(1) + .max(listGrantsV2QueryCustomerItemTwoMax) + .describe('ExternalKey is a looser version of key.'), + ]) + .describe( + 'ULID (Universally Unique Lexicographically Sortable Identifier) or external unique key.', + ), + ) + .optional() + .describe( + 'Filtering by multiple customers (either by ID or key).\n\nUsage: `?customer=customer-1&customer=customer-2`', + ), + feature: zod + .array(zod.coerce.string()) + .optional() + .describe( + 'Filtering by multiple features.\n\nUsage: `?feature=feature-1&feature=feature-2`', + ), + includeDeleted: zod.coerce + .boolean() + .default(listGrantsV2QueryIncludeDeletedDefault) + .describe('Include deleted'), + limit: zod.coerce + .number() + .min(1) + .max(listGrantsV2QueryLimitMax) + .default(listGrantsV2QueryLimitDefault) + .describe('Number of items to return.\n\nDefault is 100.'), + offset: zod.coerce + .number() + .min(listGrantsV2QueryOffsetMin) + .default(listGrantsV2QueryOffsetDefault) + .describe('Number of items to skip.\n\nDefault is 0.'), + order: zod + .enum(['ASC', 'DESC']) + .describe('The order direction.') + .default(listGrantsV2QueryOrderDefault) + .describe('The order direction.'), + orderBy: zod + .enum(['id', 'createdAt', 'updatedAt']) + .optional() + .describe('The order by field.'), + page: zod.coerce + .number() + .min(1) + .default(listGrantsV2QueryPageDefault) + .describe('Page index.\n\nDefault is 1.'), + pageSize: zod.coerce + .number() + .min(1) + .max(listGrantsV2QueryPageSizeMax) + .default(listGrantsV2QueryPageSizeDefault) + .describe('The maximum number of items per page.\n\nDefault is 100.'), +}) diff --git a/api/client/javascript/tsconfig.json b/api/client/javascript/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..9d00fafcba1ce83e73c824195866ed20822ad7ae --- /dev/null +++ b/api/client/javascript/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "allowJs": true, + "allowSyntheticDefaultImports": true, + "declaration": true, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "forceConsistentCasingInFileNames": true, + "incremental": true, + "jsx": "react-jsx", + "lib": ["esnext"], + "module": "NodeNext", + "moduleResolution": "nodenext", + "outDir": "./dist", + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "target": "ESNext" + }, + "exclude": [ + "**/*.spec.ts", + "**/*.test.ts", + "scripts/**/*.ts", + "dist/**/*.ts", + "*.config.ts" + ], + "include": ["**/*.ts", "src/react/**/*.tsx"] +} diff --git a/api/client/javascript/vitest.config.ts b/api/client/javascript/vitest.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..117a67645f43d9d4489faffc282ade12b1530b21 --- /dev/null +++ b/api/client/javascript/vitest.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: {}, +}) diff --git a/api/client/node/README.md b/api/client/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e7abd81b673f8c86db7ac1b12b348ff632769606 --- /dev/null +++ b/api/client/node/README.md @@ -0,0 +1,3 @@ +# OpenMeter Node SDK + +Moved to fetch based client in [JavaScript SDK](../javascript) diff --git a/api/client/python/.gitattributes b/api/client/python/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..cafbcfa5b1077f4f6261f27b8da75d4200c122f8 --- /dev/null +++ b/api/client/python/.gitattributes @@ -0,0 +1 @@ +openmeter/**/* linguist-generated=true diff --git a/api/client/python/.gitignore b/api/client/python/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..72b2980fd61021aad904da39c9fb18dc7f5a910c --- /dev/null +++ b/api/client/python/.gitignore @@ -0,0 +1,19 @@ +# python +# Packaging +*.egg-info/ +*.egg +*.eggs/ +dist/ +build/ +CHANGELOG.md + +# Python cache +__pycache__/ +*.pyc +*.pyo +*.pyd + +# Virtual envs +.python-version +.venv/ +venv/ diff --git a/api/client/python/MANIFEST.in b/api/client/python/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..4046ebaae9861b90c6ba66f93f877d68ca8d4b5c --- /dev/null +++ b/api/client/python/MANIFEST.in @@ -0,0 +1,5 @@ +include *.md +include LICENSE +include openmeter/py.typed +recursive-include tests *.py +recursive-include samples *.py *.md diff --git a/api/client/python/Makefile b/api/client/python/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..556e53754451abc5c3c15792abfeb668b5c9ee47 --- /dev/null +++ b/api/client/python/Makefile @@ -0,0 +1,19 @@ +# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html + +.PHONY: publish-python-sdk +publish-python-sdk: ## Publish Python SDK + $(call print-target) + ./scripts/release.sh + +.PHONY: help +.DEFAULT_GOAL := help +help: + @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' + +# Variable outputting/exporting rules +var-%: ; @echo $($*) +varexport-%: ; @echo $*=$($*) + +define print-target + @printf "Executing target: \033[36m$@\033[0m\n" +endef diff --git a/api/client/python/README.md b/api/client/python/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d295db1e23bec34f1cb20f929f65132723e3df83 --- /dev/null +++ b/api/client/python/README.md @@ -0,0 +1,329 @@ +# OpenMeter Python SDK + +[On PyPI](https://pypi.org/project/openmeter) + +This package is generated by `@typespec/http-client-python` with Typespec. + +## Prerequisites + +- Python 3.9 or later is required to use this package. + +## Install + +> The Python SDK is in preview mode. + +```sh +pip install --pre openmeter +# or using an exact version +pip install openmeter==1.0.0bXXX +``` + +## Examples + +### Setup + +#### Synchronous Client + +```python +from openmeter import Client + +client = Client( + endpoint="https://openmeter.cloud", + token="your-api-token", +) +``` + +#### Async Client + +```python +from openmeter.aio import Client + +client = Client( + endpoint="https://openmeter.cloud", + token="your-api-token", +) +``` + +### Ingest an Event + +#### Synchronous + +```python +import datetime +import uuid + +from openmeter.models import Event + +# Create an Event instance (following CloudEvents specification) +event = Event( + id=str(uuid.uuid4()), + source="my-app", + specversion="1.0", + type="prompt", + subject="customer-1", + time=datetime.datetime.now(datetime.timezone.utc), + data={ + "tokens": 100, + "model": "gpt-4o", + "type": "input", + }, +) + +# Ingest the event +client.events.ingest_event(event) +``` + +#### Async + +```python +import datetime +import uuid +import asyncio + +from openmeter.aio import Client +from openmeter.models import Event + +async def main(): + async with Client( + endpoint="https://openmeter.cloud", + token="your-api-token", + ) as client: + # Create an Event instance (following CloudEvents specification) + event = Event( + id=str(uuid.uuid4()), + source="my-app", + specversion="1.0", + type="prompt", + subject="customer-1", + time=datetime.datetime.now(datetime.timezone.utc), + data={ + "tokens": 100, + "model": "gpt-4o", + "type": "input", + }, + ) + + # Ingest the event + await client.events.ingest_event(event) + +asyncio.run(main()) +``` + +### Query Meter + +#### Synchronous + +```python +from openmeter.models import MeterQueryResult + +# Query total values +r: MeterQueryResult = client.meters.query_json(meter_id_or_slug="tokens_total") +print("Query total values:", r.data[0].value) +``` + +#### Async + +```python +import asyncio + +from openmeter.aio import Client +from openmeter.models import MeterQueryResult + +async def main(): + async with Client( + endpoint="https://openmeter.cloud", + token="your-api-token", + ) as client: + # Query total values + r: MeterQueryResult = await client.meters.query_json( + meter_id_or_slug="tokens_total" + ) + print("Query total values:", r.data[0].value) + +asyncio.run(main()) +``` + +## Client API Reference + +The OpenMeter Python SDK provides a comprehensive client interface organized into logical operation groups. Below is a complete reference of all available methods. + +### Overview + +| Namespace | Operation | Method | Description | +| ---------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------- | +| **Events** | | | Track usage by ingesting events | +| | Create | `client.events.ingest_event(event)` | Ingest a single event | +| | Create | `client.events.ingest_events(events)` | Ingest batch of events | +| | Create | `client.events.ingest_events_json(events_json)` | Ingest events from JSON | +| | Read | `client.events.list(**kwargs)` | List ingested events with filtering | +| | Read | `client.events_v2.list(**kwargs)` | List ingested events with advanced filtering (V2) | +| **Meters** | | | Track and aggregate usage data from events | +| | Create | `client.meters.create(meter)` | Create a new meter | +| | Read | `client.meters.get(meter_id_or_slug)` | Get a meter by ID or slug | +| | Read | `client.meters.list(**kwargs)` | List all meters | +| | Read | `client.meters.query_json(meter_id_or_slug, **kwargs)` | Query usage data in JSON format | +| | Read | `client.meters.query_csv(meter_id_or_slug, **kwargs)` | Query usage data in CSV format | +| | Read | `client.meters.query(meter_id_or_slug, **kwargs)` | Query usage data | +| | Read | `client.meters.list_subjects(meter_id_or_slug, **kwargs)` | List subjects for a meter | +| | Read | `client.meters.list_group_by_values(meter_id_or_slug, **kwargs)` | List group-by values for a meter | +| | Update | `client.meters.update(meter_id_or_slug, meter)` | Update a meter by ID or slug | +| | Delete | `client.meters.delete(meter_id_or_slug)` | Delete a meter by ID or slug | +| **Subjects** | | | Manage entities that consume resources | +| | Create | `client.subjects.upsert(subjects)` | Create or update one or multiple subjects | +| | Read | `client.subjects.get(subject_id_or_key)` | Get a subject by ID or key | +| | Read | `client.subjects.list()` | List all subjects | +| | Delete | `client.subjects.delete(subject_id_or_key)` | Delete a subject by ID or key | +| **Customers** | | | Manage customer information and lifecycles | +| | Create | `client.customers.create(customer)` | Create a new customer | +| | Read | `client.customers.get(customer_id_or_key, **kwargs)` | Get a customer by ID or key | +| | Read | `client.customers.list(**kwargs)` | List all customers | +| | Read | `client.customers.list_customer_subscriptions(customer_id_or_key, **kwargs)` | List customer subscriptions | +| | Update | `client.customers.update(customer_id_or_key, customer)` | Update a customer | +| | Delete | `client.customers.delete(customer_id_or_key)` | Delete a customer | +| **Customer (Single)** | | | Customer-specific operations | +| | Read | `client.customer.get_customer_access(customer_id_or_key)` | Get customer access information | +| **Customer Apps** | | | Manage customer app integrations | +| | Read | `client.customer_apps.list_app_data(customer_id_or_key, **kwargs)` | List app data for a customer | +| | Update | `client.customer_apps.upsert_app_data(customer_id_or_key, app_data)` | Upsert app data for a customer | +| | Delete | `client.customer_apps.delete_app_data(customer_id_or_key, app_id)` | Delete app data for a customer | +| **Customer Stripe** | | | Manage Stripe integration for customers | +| | Read | `client.customer_stripe.get(customer_id_or_key)` | Get Stripe customer data | +| | Update | `client.customer_stripe.upsert(customer_id_or_key, data)` | Upsert Stripe customer data | +| | Create | `client.customer_stripe.create_portal_session(customer_id_or_key, **kwargs)` | Create a Stripe customer portal session | +| **Customer Entitlement** | | | Single customer entitlement operations | +| | Read | `client.customer_entitlement.get_customer_entitlement_value(customer_id_or_key, **kwargs)` | Get customer entitlement value | +| **Customer Overrides** | | | Manage customer-specific pricing overrides | +| | Read | `client.customer_overrides.list(customer_id_or_key)` | List customer overrides | +| | Read | `client.customer_overrides.get(customer_id_or_key, override_id)` | Get a customer override | +| | Update | `client.customer_overrides.upsert(customer_id_or_key, override)` | Upsert a customer override | +| | Delete | `client.customer_overrides.delete(customer_id_or_key, override_id)` | Delete a customer override | +| **Features** | | | Define application capabilities and services | +| | Create | `client.features.create(feature)` | Create a new feature | +| | Read | `client.features.get(feature_id)` | Get a feature by ID | +| | Read | `client.features.list(**kwargs)` | List all features | +| | Delete | `client.features.delete(feature_id)` | Delete a feature by ID | +| **Plans** | | | Manage subscription plans and pricing | +| | Create | `client.plans.create(request)` | Create a new plan | +| | Read | `client.plans.get(plan_id, **kwargs)` | Get a plan by ID | +| | Read | `client.plans.list(**kwargs)` | List all plans | +| | Update | `client.plans.update(plan_id, body)` | Update a plan | +| | Delete | `client.plans.delete(plan_id)` | Delete a plan by ID | +| | Other | `client.plans.publish(plan_id)` | Publish a plan | +| | Other | `client.plans.archive(plan_id)` | Archive a plan version | +| | Other | `client.plans.next(plan_id_or_key)` | Create new draft plan version | +| **Plan Addons** | | | Manage addons assigned to plans | +| | Create | `client.plan_addons.create(plan_id, body)` | Create addon assignment for plan | +| | Read | `client.plan_addons.get(plan_id, plan_addon_id)` | Get addon assignment for plan | +| | Read | `client.plan_addons.list(plan_id, **kwargs)` | List addon assignments for plan | +| | Update | `client.plan_addons.update(plan_id, plan_addon_id, body)` | Update addon assignment for plan | +| | Delete | `client.plan_addons.delete(plan_id, plan_addon_id)` | Delete addon assignment for plan | +| **Addons** | | | Manage standalone addons available across plans | +| | Create | `client.addons.create(request)` | Create a new addon | +| | Read | `client.addons.get(addon_id, **kwargs)` | Get an addon by ID | +| | Read | `client.addons.list(**kwargs)` | List all addons | +| | Update | `client.addons.update(addon_id, request)` | Update an addon | +| | Delete | `client.addons.delete(addon_id)` | Delete an addon by ID | +| | Other | `client.addons.publish(addon_id)` | Publish an addon | +| | Other | `client.addons.archive(addon_id)` | Archive an addon | +| **Subscriptions** | | | Manage customer subscriptions | +| | Create | `client.subscriptions.create(body)` | Create a new subscription | +| | Read | `client.subscriptions.get_expanded(subscription_id, **kwargs)` | Get a subscription with expanded details | +| | Update | `client.subscriptions.edit(subscription_id, body)` | Edit a subscription | +| | Update | `client.subscriptions.change(subscription_id, body)` | Change a subscription | +| | Update | `client.subscriptions.migrate(subscription_id, body)` | Migrate subscription to a new plan version | +| | Update | `client.subscriptions.restore(subscription_id)` | Restore a canceled subscription | +| | Delete | `client.subscriptions.cancel(subscription_id, body)` | Cancel a subscription | +| | Delete | `client.subscriptions.delete(subscription_id)` | Delete a subscription | +| | Other | `client.subscriptions.unschedule_cancelation(subscription_id)` | Unschedule a subscription cancelation | +| **Subscription Addons** | | | Manage addons on subscriptions | +| | Create | `client.subscription_addons.create(subscription_id, body)` | Add an addon to a subscription | +| | Read | `client.subscription_addons.get(subscription_id, subscription_addon_id)` | Get a subscription addon | +| | Read | `client.subscription_addons.list(subscription_id, **kwargs)` | List addons on a subscription | +| | Update | `client.subscription_addons.update(subscription_id, subscription_addon_id, body)` | Update a subscription addon | +| **Entitlements** | | | Admin entitlements management | +| | Read | `client.entitlements.list(**kwargs)` | List all entitlements (admin) | +| | Read | `client.entitlements.get(entitlement_id)` | Get an entitlement by ID | +| **Entitlements V2** | | | V2 Admin entitlements management | +| | Read | `client.entitlements_v2.list(**kwargs)` | List all entitlements V2 (admin) | +| | Read | `client.entitlements_v2.get(entitlement_id_or_feature_key, **kwargs)` | Get an entitlement V2 by ID or feature key | +| **Customer Entitlements V2** | | | Manage customer entitlements (V2) | +| | Create | `client.customer_entitlements_v2.post(customer_id_or_key, body)` | Create a customer entitlement | +| | Read | `client.customer_entitlements_v2.list(customer_id_or_key, **kwargs)` | List customer entitlements | +| | Read | `client.customer_entitlements_v2.get(customer_id_or_key, entitlement_id_or_feature_key)` | Get a customer entitlement | +| | Delete | `client.customer_entitlements_v2.delete(customer_id_or_key, entitlement_id)` | Delete a customer entitlement | +| | Update | `client.customer_entitlements_v2.override(customer_id_or_key, entitlement_id_or_feature_key, override)` | Override a customer entitlement | +| **Customer Entitlement V2** | | | Single customer entitlement operations (V2) | +| | Read | `client.customer_entitlement_v2.get_grants(customer_id_or_key, entitlement_id_or_feature_key, **kwargs)` | List grants for a customer entitlement | +| | Read | `client.customer_entitlement_v2.get_customer_entitlement_value(customer_id_or_key, entitlement_id_or_feature_key, **kwargs)` | Get customer entitlement value | +| | Read | `client.customer_entitlement_v2.get_customer_entitlement_history(customer_id_or_key, entitlement_id_or_feature_key, **kwargs)` | Get customer entitlement history | +| | Create | `client.customer_entitlement_v2.create_customer_entitlement_grant(customer_id_or_key, entitlement_id_or_feature_key, grant)` | Create a grant for customer entitlement | +| | Update | `client.customer_entitlement_v2.reset_customer_entitlement(customer_id_or_key, entitlement_id, **kwargs)` | Reset customer entitlement usage | +| **Grants** | | | Admin grants management | +| | Read | `client.grants.list(**kwargs)` | List all grants (admin) | +| | Delete | `client.grants.delete(grant_id)` | Delete (void) a grant | +| **Grants V2** | | | V2 Admin grants management | +| | Read | `client.grants_v2.list(**kwargs)` | List all grants V2 (admin) | +| **Billing Profiles** | | | Manage billing profiles | +| | Create | `client.billing_profiles.create(profile)` | Create a billing profile | +| | Read | `client.billing_profiles.get(id)` | Get a billing profile by ID | +| | Read | `client.billing_profiles.list(**kwargs)` | List billing profiles | +| | Update | `client.billing_profiles.update(id, profile)` | Update a billing profile | +| | Delete | `client.billing_profiles.delete(id)` | Delete a billing profile | +| **Invoices** | | | Manage invoices | +| | Read | `client.invoices.list(**kwargs)` | List invoices | +| | Other | `client.invoices.invoice_pending_lines_action(customer_id, **kwargs)` | Invoice pending lines for customer | +| **Invoice** | | | Single invoice operations | +| | Read | `client.invoice.get_invoice(id, **kwargs)` | Get an invoice by ID | +| | Update | `client.invoice.update_invoice(id, invoice)` | Update an invoice | +| | Delete | `client.invoice.delete_invoice(id)` | Delete an invoice | +| | Other | `client.invoice.advance_action(id)` | Advance invoice to next status | +| | Other | `client.invoice.approve_action(id)` | Approve an invoice | +| | Other | `client.invoice.retry_action(id, body)` | Retry advancing invoice after failure | +| | Other | `client.invoice.void_invoice_action(id)` | Void an invoice | +| | Other | `client.invoice.recalculate_tax_action(id)` | Recalculate invoice tax amounts | +| | Other | `client.invoice.snapshot_quantities_action(id)` | Snapshot invoice quantities | +| **Customer Invoice** | | | Customer-specific invoice operations | +| | Create | `client.customer_invoice.create_pending_invoice_line(customer_id, body)` | Create pending invoice line for customer | +| | Other | `client.customer_invoice.simulate_invoice(customer_id, **kwargs)` | Simulate an invoice for a customer | +| **Apps** | | | Manage integrations and app installations | +| | Read | `client.apps.list(**kwargs)` | List installed apps | +| | Read | `client.apps.get(id)` | Get an app by ID | +| | Update | `client.apps.update(id, app)` | Update an app | +| | Delete | `client.apps.uninstall(id)` | Uninstall an app | +| **App Stripe** | | | Stripe app integration | +| | Create | `client.app_stripe.webhook(id, body)` | Handle Stripe webhook event | +| | Update | `client.app_stripe.update_stripe_api_key(id, request)` | Update Stripe API key | +| | Create | `client.app_stripe.create_checkout_session(body)` | Create Stripe checkout session | +| **App Custom Invoicing** | | | Custom invoicing app integration | +| | Other | `client.app_custom_invoicing.draft_syncronized(id, invoice_number, **kwargs)` | Notify when draft invoice synchronized | +| | Other | `client.app_custom_invoicing.finalized(id, invoice_number, **kwargs)` | Notify when invoice finalized | +| | Other | `client.app_custom_invoicing.payment_status(id, invoice_number, body)` | Update invoice payment status | +| **Marketplace** | | | App marketplace operations | +| | Read | `client.marketplace.list(**kwargs)` | List marketplace apps | +| | Read | `client.marketplace.get(app_type)` | Get marketplace app | +| | Read | `client.marketplace.get_o_auth2_install_url(app_type, **kwargs)` | Get OAuth2 install URL | +| | Create | `client.marketplace.authorize_o_auth2_install(app_type, **kwargs)` | Authorize OAuth2 installation | +| | Create | `client.marketplace.install_with_api_key(app_type, body)` | Install app with API key | +| | Create | `client.marketplace.install(app_type, body)` | Install marketplace app | +| **Notification Channels** | | | Manage notification channels | +| | Create | `client.notification_channels.create(channel)` | Create a notification channel | +| | Read | `client.notification_channels.get(channel_id)` | Get a notification channel by ID | +| | Read | `client.notification_channels.list(**kwargs)` | List notification channels | +| | Update | `client.notification_channels.update(channel_id, channel)` | Update a notification channel | +| | Delete | `client.notification_channels.delete(channel_id)` | Delete a notification channel | +| **Notification Rules** | | | Manage notification rules | +| | Create | `client.notification_rules.create(rule)` | Create a notification rule | +| | Read | `client.notification_rules.get(rule_id)` | Get a notification rule by ID | +| | Read | `client.notification_rules.list(**kwargs)` | List notification rules | +| | Update | `client.notification_rules.update(rule_id, rule)` | Update a notification rule | +| | Delete | `client.notification_rules.delete(rule_id)` | Delete a notification rule | +| | Other | `client.notification_rules.test(rule_id)` | Test a notification rule | +| **Notification Events** | | | View notification events | +| | Read | `client.notification_events.get(event_id)` | Get a notification event by ID | +| | Read | `client.notification_events.list(**kwargs)` | List notification events | +| **Progress** | | | Track long-running operations | +| | Read | `client.progress.get_progress(id)` | Get progress of a long-running operation | +| **Currencies** | | | Currency information | +| | Read | `client.currencies.list_currencies()` | List all supported currencies | +| **Debug** | | | Debug utilities for monitoring and troubleshooting | +| | Read | `client.debug.metrics()` | Get event ingestion metrics | diff --git a/api/client/python/examples/README.md b/api/client/python/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6bf97c427e67fd266728f7a0b9081364fa5e25e5 --- /dev/null +++ b/api/client/python/examples/README.md @@ -0,0 +1,29 @@ +# Examples + +## Setup + +Install dependencies + +```sh +poetry install +``` + +## Running Examples + +Run any example with environment variables: + +```sh +OPENMETER_ENDPOINT=https://openmeter.cloud \ +OPENMETER_TOKEN=om_xxx \ +poetry run python ./sync/ingest.py +``` + +## Type Checking + +The examples are type-checked using **Pyright**: + +```sh +poetry run pyright +``` + +**Note**: Mypy is not compatible with the generated SDK models due to how it handles overloaded constructors. Pyright is the recommended type checker for this project. diff --git a/api/client/python/examples/async/customer.py b/api/client/python/examples/async/customer.py new file mode 100644 index 0000000000000000000000000000000000000000..af9eb47ef33efe7302a8460a7dba2ae7b94a3215 --- /dev/null +++ b/api/client/python/examples/async/customer.py @@ -0,0 +1,77 @@ +from os import environ +from typing import Optional +import asyncio + +from openmeter.aio import Client +from openmeter.models import ( + CustomerCreate, + CustomerReplaceUpdate, + CustomerUsageAttribution, + Metadata, +) +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") +customer_key: str = environ.get("OPENMETER_CUSTOMER_KEY") or "acme-corp-1" +subject_key: str = environ.get("OPENMETER_SUBJECT_KEY") or "acme-user-1" + + +async def main() -> None: + async with Client( + endpoint=ENDPOINT, + token=token, + ) as client: + try: + # Create a customer + customer_create = CustomerCreate( + name="Acme Corporation", + usage_attribution=CustomerUsageAttribution(subject_keys=[subject_key]), + description="A demo customer for testing", + metadata=Metadata( + { + "industry": "technology", + } + ), + key=customer_key, + primary_email="contact@acme-corp.example.com", + currency="EUR", + ) + + created_customer = await client.customers.create(customer_create) + print(f"Customer created successfully with ID: {created_customer.id}") + print(f"Customer name: {created_customer.name}") + print(f"Customer key: {created_customer.key}") + + # Get the customer by ID or key + customer = await client.customers.get(created_customer.id) + print(f"\nRetrieved customer: {customer.name}") + print(f"Primary email: {customer.primary_email}") + print(f"Currency: {customer.currency}") + + # Update the customer + customer_update = CustomerReplaceUpdate( + name="Acme Corporation Ltd.", + usage_attribution=CustomerUsageAttribution(subject_keys=[subject_key]), + description="Updated demo customer", + metadata=Metadata( + { + "industry": "technology", + } + ), + key=customer_key, + primary_email="info@acme-corp.example.com", + currency="USD", + ) + + updated_customer = await client.customers.update(created_customer.id, customer_update) + print(f"\nCustomer updated successfully") + print(f"Updated name: {updated_customer.name}") + print(f"Updated email: {updated_customer.primary_email}") + print(f"Updated currency: {updated_customer.currency}") + + except HttpResponseError as e: + print(f"Error: {e}") + + +asyncio.run(main()) diff --git a/api/client/python/examples/async/entitlement.py b/api/client/python/examples/async/entitlement.py new file mode 100644 index 0000000000000000000000000000000000000000..0dcd0f88d88cd8af965f72267c07f6d620308d31 --- /dev/null +++ b/api/client/python/examples/async/entitlement.py @@ -0,0 +1,88 @@ +from os import environ +from typing import Optional +import asyncio + +from openmeter.aio import Client +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") +customer_key: str = environ.get("OPENMETER_CUSTOMER_KEY") or "acme-corp-1" +feature_key: str = environ.get("OPENMETER_FEATURE_KEY") or "api_access" + + +async def main() -> None: + async with Client( + endpoint=ENDPOINT, + token=token, + ) as client: + try: + # Check customer access to a specific feature + print(f"Checking access for customer '{customer_key}' to feature '{feature_key}'...") + + entitlement_value = await client.customer_entitlement.get_customer_entitlement_value( + customer_key, feature_key + ) + + print(f"\nEntitlement Value:") + print(f"Has Access: {entitlement_value.has_access}") + + # For metered entitlements, additional properties are available + if entitlement_value.balance is not None: + print(f"Balance: {entitlement_value.balance}") + if entitlement_value.usage is not None: + print(f"Usage: {entitlement_value.usage}") + if entitlement_value.overage is not None: + print(f"Overage: {entitlement_value.overage}") + + # For static entitlements, config is available + if entitlement_value.config is not None: + print(f"Config: {entitlement_value.config}") + + # List customer entitlements and demonstrate type-specific handling + print(f"\nListing all entitlements for customer '{customer_key}'...") + entitlements_response = await client.customer_entitlements_v2.list(customer_key) + + print(f"\nEntitlements by Type:") + for entitlement in entitlements_response.items_property: + # Note: Due to a deserialization issue in the SDK, items come back as dicts + # Access fields using dict syntax or .get() + print(f"\n Feature: {entitlement.get('featureKey')}") + print(f" ID: {entitlement.get('id')}") + + # Handle different entitlement types using discriminator + entitlement_type = entitlement.get("type") + if entitlement_type == "metered": + # Metered entitlement + print(f" Type: Metered") + print(f" Soft Limit: {entitlement.get('isSoftLimit')}") + if entitlement.get("issueAfterReset") is not None: + print(f" Issue After Reset: {entitlement.get('issueAfterReset')}") + elif entitlement_type == "static": + # Static entitlement + print(f" Type: Static") + if entitlement.get("config") is not None: + print(f" Config: {entitlement.get('config')}") + elif entitlement_type == "boolean": + # Boolean entitlement + print(f" Type: Boolean") + + # Get overall customer access to all features + print(f"\nGetting overall access for customer '{customer_key}'...") + customer_access = await client.customer.get_customer_access(customer_key) + + print(f"\nCustomer Access Summary:") + print(f"Total entitlements: {len(customer_access.entitlements)}") + for feature, value in customer_access.entitlements.items(): + access_status = "✓" if value.has_access else "✗" + print(f" {access_status} {feature}: has_access={value.has_access}") + if value.balance is not None: + print(f" Balance: {value.balance}") + if value.usage is not None: + print(f" Usage: {value.usage}") + + except HttpResponseError as e: + print(f"Error: {e}") + + +asyncio.run(main()) diff --git a/api/client/python/examples/async/ingest.py b/api/client/python/examples/async/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..7a4cc687f82d2afd8748b4d7513bc47676338024 --- /dev/null +++ b/api/client/python/examples/async/ingest.py @@ -0,0 +1,43 @@ +from os import environ +from typing import Optional +import datetime +import uuid +import asyncio + +from openmeter.aio import Client +from openmeter.models import Event +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") + + +async def main() -> None: + async with Client( + endpoint=ENDPOINT, + token=token, + ) as client: + try: + # Create a CloudEvents event + event = Event( + id=str(uuid.uuid4()), + source="my-app", + specversion="1.0", + type="prompt", + subject="customer-1", + time=datetime.datetime.now(datetime.timezone.utc), + data={ + "tokens": 100, + "model": "gpt-4o", + "type": "input", + }, + ) + + # Ingest the event + await client.events.ingest_event(event) + print("Event ingested successfully") + except HttpResponseError as e: + print(f"Error ingesting event: {e}") + + +asyncio.run(main()) diff --git a/api/client/python/examples/async/query.py b/api/client/python/examples/async/query.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0b20220f37beea622771e274b6adbb688c8e04 --- /dev/null +++ b/api/client/python/examples/async/query.py @@ -0,0 +1,48 @@ +from os import environ +from typing import Optional +import asyncio + +from openmeter.aio import Client +from openmeter.models import MeterQueryResult, FilterString +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") + + +async def main() -> None: + async with Client( + endpoint=ENDPOINT, + token=token, + ) as client: + try: + # Query total values + r: MeterQueryResult = await client.meters.query_json(meter_id_or_slug="tokens_total") + if r.data and len(r.data) > 0: + print("Query total values:", r.data[0].value) + else: + print("Query total values: No data returned") + + # Query total values grouped by language + r = await client.meters.query_json( + meter_id_or_slug="tokens_total", + group_by=["model"], + ) + print("Query total values grouped by model:") + for row in r.data: + print("\t", row.group_by["model"], ":", row.value) + + # Query total values for model=gpt-4o + r = await client.meters.query_json( + meter_id_or_slug="tokens_total", + advanced_meter_group_by_filters={"model": FilterString(eq="gpt-4o")}, + ) + if r.data and len(r.data) > 0: + print("Query total values for model=gpt-4o:", r.data[0].value) + else: + print("Query total values for model=gpt-4o: No data returned") + except HttpResponseError as e: + print(e) + + +asyncio.run(main()) diff --git a/api/client/python/examples/async/subscription.py b/api/client/python/examples/async/subscription.py new file mode 100644 index 0000000000000000000000000000000000000000..23c9f194c5efe8bf7766ee09a8c0996b7f6addc7 --- /dev/null +++ b/api/client/python/examples/async/subscription.py @@ -0,0 +1,74 @@ +from os import environ +from typing import Optional +import asyncio + +from openmeter.aio import Client +from openmeter.models import ( + Metadata, + PlanSubscriptionCreate, + PlanReferenceInput, + SubscriptionStatus, +) +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") +customer_key: str = environ.get("OPENMETER_CUSTOMER_KEY") or "acme-corp-1" +plan_key: str = environ.get("OPENMETER_PLAN_KEY") or "free" + + +async def main() -> None: + async with Client( + endpoint=ENDPOINT, + token=token, + ) as client: + try: + # Create a subscription for the customer using the free plan + print(f"Creating subscription for customer '{customer_key}' with plan '{plan_key}'...") + + subscription_create = PlanSubscriptionCreate( + plan=PlanReferenceInput( + key=plan_key, + ), + name="Free Plan Subscription", + description="Subscription to the free plan for Acme Corporation", + customer_key=customer_key, + metadata=Metadata( + { + "source": "example", + "environment": "development", + } + ), + ) + + subscription = await client.subscriptions.create(subscription_create) + print(f"Subscription created successfully with ID: {subscription.id}") + print(f"Subscription name: {subscription.name}") + print(f"Subscription status: {subscription.status}") + print(f"Customer ID: {subscription.customer_id}") + print(f"Active from: {subscription.active_from}") + print(f"Active to: {subscription.active_to}") + print(f"Currency: {subscription.currency}") + print(f"Billing cadence: {subscription.billing_cadence}") + + # Retrieve the subscription to verify + retrieved_subscription = await client.subscriptions.get_expanded(subscription.id) + print(f"\nRetrieved subscription: {retrieved_subscription.name}") + print(f"Status: {retrieved_subscription.status}") + if retrieved_subscription.plan: + print(f"Plan key: {retrieved_subscription.plan.key}") + print(f"Plan version: {retrieved_subscription.plan.version}") + + # List subscriptions for the customer + print(f"\nListing subscriptions for customer '{customer_key}'...") + subscriptions_response = await client.customers.list_customer_subscriptions( + customer_key, status=[SubscriptionStatus.ACTIVE] + ) + for sub in subscriptions_response.items_property: + print(f"\t{sub.name} (ID: {sub.id}, Status: {sub.status})") + + except HttpResponseError as e: + print(f"Error: {e}") + + +asyncio.run(main()) diff --git a/api/client/python/examples/poetry.lock b/api/client/python/examples/poetry.lock new file mode 100644 index 0000000000000000000000000000000000000000..50c25fce4196837c27cd8aadcd012abe6015b405 --- /dev/null +++ b/api/client/python/examples/poetry.lock @@ -0,0 +1,1113 @@ +# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand. + +[[package]] +name = "aiohappyeyeballs" +version = "2.6.1" +description = "Happy Eyeballs for asyncio" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "aiohappyeyeballs-2.6.1-py3-none-any.whl", hash = "sha256:f349ba8f4b75cb25c99c5c2d84e997e485204d2902a9597802b0371f09331fb8"}, + {file = "aiohappyeyeballs-2.6.1.tar.gz", hash = "sha256:c3f9d0113123803ccadfdf3f0faa505bc78e6a72d1cc4806cbd719826e943558"}, +] + +[[package]] +name = "aiohttp" +version = "3.13.4" +description = "Async http client/server framework (asyncio)" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "aiohttp-3.13.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:6290fe12fe8cefa6ea3c1c5b969d32c010dfe191d4392ff9b599a3f473cbe722"}, + {file = "aiohttp-3.13.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7520d92c0e8fbbe63f36f20a5762db349ff574ad38ad7bc7732558a650439845"}, + {file = "aiohttp-3.13.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d2710ae1e1b81d0f187883b6e9d66cecf8794b50e91aa1e73fc78bfb5503b5d9"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:717d17347567ded1e273aa09918650dfd6fd06f461549204570c7973537d4123"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:383880f7b8de5ac208fa829c7038d08e66377283b2de9e791b71e06e803153c2"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1867087e2c1963db1216aedf001efe3b129835ed2b05d97d058176a6d08b5726"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6234bf416a38d687c3ab7f79934d7fb2a42117a5b9813aca07de0a5398489023"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cdd3393130bf6588962441ffd5bde1d3ea2d63a64afa7119b3f3ba349cebbe7"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0d0dbc6c76befa76865373d6aa303e480bb8c3486e7763530f7f6e527b471118"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:10fb7b53262cf4144a083c9db0d2b4d22823d6708270a9970c4627b248c6064c"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:eb10ce8c03850e77f4d9518961c227be569e12f71525a7e90d17bca04299921d"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:7c65738ac5ae32b8feef699a4ed0dc91a0c8618b347781b7461458bbcaaac7eb"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:6b335919ffbaf98df8ff3c74f7a6decb8775882632952fd1810a017e38f15aee"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:ec75fc18cb9f4aca51c2cbace20cf6716e36850f44189644d2d69a875d5e0532"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:463fa18a95c5a635d2b8c09babe240f9d7dbf2a2010a6c0b35d8c4dff2a0e819"}, + {file = "aiohttp-3.13.4-cp310-cp310-win32.whl", hash = "sha256:13168f5645d9045522c6cef818f54295376257ed8d02513a37c2ef3046fc7a97"}, + {file = "aiohttp-3.13.4-cp310-cp310-win_amd64.whl", hash = "sha256:a7058af1f53209fdf07745579ced525d38d481650a989b7aa4a3b484b901cdab"}, + {file = "aiohttp-3.13.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8ea0c64d1bcbf201b285c2246c51a0c035ba3bbd306640007bc5844a3b4658c1"}, + {file = "aiohttp-3.13.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6f742e1fa45c0ed522b00ede565e18f97e4cf8d1883a712ac42d0339dfb0cce7"}, + {file = "aiohttp-3.13.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6dcfb50ee25b3b7a1222a9123be1f9f89e56e67636b561441f0b304e25aaef8f"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3262386c4ff370849863ea93b9ea60fd59c6cf56bf8f93beac625cf4d677c04d"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:473bb5aa4218dd254e9ae4834f20e31f5a0083064ac0136a01a62ddbae2eaa42"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e56423766399b4c77b965f6aaab6c9546617b8994a956821cc507d00b91d978c"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8af249343fafd5ad90366a16d230fc265cf1149f26075dc9fe93cfd7c7173942"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bc0a5cf4f10ef5a2c94fdde488734b582a3a7a000b131263e27c9295bd682d9"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5c7ff1028e3c9fc5123a865ce17df1cb6424d180c503b8517afbe89aa566e6be"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ba5cf98b5dcb9bddd857da6713a503fa6d341043258ca823f0f5ab7ab4a94ee8"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:d85965d3ba21ee4999e83e992fecb86c4614d6920e40705501c0a1f80a583c12"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:49f0b18a9b05d79f6f37ddd567695943fcefb834ef480f17a4211987302b2dc7"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7f78cb080c86fbf765920e5f1ef35af3f24ec4314d6675d0a21eaf41f6f2679c"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:67a3ec705534a614b68bbf1c70efa777a21c3da3895d1c44510a41f5a7ae0453"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d6630ec917e85c5356b2295744c8a97d40f007f96a1c76bf1928dc2e27465393"}, + {file = "aiohttp-3.13.4-cp311-cp311-win32.whl", hash = "sha256:54049021bc626f53a5394c29e8c444f726ee5a14b6e89e0ad118315b1f90f5e3"}, + {file = "aiohttp-3.13.4-cp311-cp311-win_amd64.whl", hash = "sha256:c033f2bc964156030772d31cbf7e5defea181238ce1f87b9455b786de7d30145"}, + {file = "aiohttp-3.13.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ee62d4471ce86b108b19c3364db4b91180d13fe3510144872d6bad5401957360"}, + {file = "aiohttp-3.13.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c0fd8f41b54b58636402eb493afd512c23580456f022c1ba2db0f810c959ed0d"}, + {file = "aiohttp-3.13.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4baa48ce49efd82d6b1a0be12d6a36b35e5594d1dd42f8bfba96ea9f8678b88c"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d738ebab9f71ee652d9dbd0211057690022201b11197f9a7324fd4dba128aa97"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0ce692c3468fa831af7dceed52edf51ac348cebfc8d3feb935927b63bd3e8576"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8e08abcfe752a454d2cb89ff0c08f2d1ecd057ae3e8cc6d84638de853530ebab"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5977f701b3fff36367a11087f30ea73c212e686d41cd363c50c022d48b011d8d"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54203e10405c06f8b6020bd1e076ae0fe6c194adcee12a5a78af3ffa3c57025e"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:358a6af0145bc4dda037f13167bef3cce54b132087acc4c295c739d05d16b1c3"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:898ea1850656d7d61832ef06aa9846ab3ddb1621b74f46de78fbc5e1a586ba83"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:7bc30cceb710cf6a44e9617e43eebb6e3e43ad855a34da7b4b6a73537d8a6763"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4a31c0c587a8a038f19a4c7e60654a6c899c9de9174593a13e7cc6e15ff271f9"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:2062f675f3fe6e06d6113eb74a157fb9df58953ffed0cdb4182554b116545758"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d1ba8afb847ff80626d5e408c1fdc99f942acc877d0702fe137015903a220a9"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b08149419994cdd4d5eecf7fd4bc5986b5a9380285bcd01ab4c0d6bfca47b79d"}, + {file = "aiohttp-3.13.4-cp312-cp312-win32.whl", hash = "sha256:fc432f6a2c4f720180959bc19aa37259651c1a4ed8af8afc84dd41c60f15f791"}, + {file = "aiohttp-3.13.4-cp312-cp312-win_amd64.whl", hash = "sha256:6148c9ae97a3e8bff9a1fc9c757fa164116f86c100468339730e717590a3fb77"}, + {file = "aiohttp-3.13.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:63dd5e5b1e43b8fb1e91b79b7ceba1feba588b317d1edff385084fcc7a0a4538"}, + {file = "aiohttp-3.13.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:746ac3cc00b5baea424dacddea3ec2c2702f9590de27d837aa67004db1eebc6e"}, + {file = "aiohttp-3.13.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bda8f16ea99d6a6705e5946732e48487a448be874e54a4f73d514660ff7c05d3"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4b061e7b5f840391e3f64d0ddf672973e45c4cfff7a0feea425ea24e51530fc2"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b252e8d5cd66184b570d0d010de742736e8a4fab22c58299772b0c5a466d4b21"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:20af8aad61d1803ff11152a26146d8d81c266aa8c5aa9b4504432abb965c36a0"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:13a5cc924b59859ad2adb1478e31f410a7ed46e92a2a619d6d1dd1a63c1a855e"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:534913dfb0a644d537aebb4123e7d466d94e3be5549205e6a31f72368980a81a"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:320e40192a2dcc1cf4b5576936e9652981ab596bf81eb309535db7e2f5b5672f"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9e587fcfce2bcf06526a43cb705bdee21ac089096f2e271d75de9c339db3100c"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:9eb9c2eea7278206b5c6c1441fdd9dc420c278ead3f3b2cc87f9b693698cc500"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:29be00c51972b04bf9d5c8f2d7f7314f48f96070ca40a873a53056e652e805f7"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:90c06228a6c3a7c9f776fe4fc0b7ff647fffd3bed93779a6913c804ae00c1073"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:a533ec132f05fd9a1d959e7f34184cd7d5e8511584848dab85faefbaac573069"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1c946f10f413836f82ea4cfb90200d2a59578c549f00857e03111cf45ad01ca5"}, + {file = "aiohttp-3.13.4-cp313-cp313-win32.whl", hash = "sha256:48708e2706106da6967eff5908c78ca3943f005ed6bcb75da2a7e4da94ef8c70"}, + {file = "aiohttp-3.13.4-cp313-cp313-win_amd64.whl", hash = "sha256:74a2eb058da44fa3a877a49e2095b591d4913308bb424c418b77beb160c55ce3"}, + {file = "aiohttp-3.13.4-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:e0a2c961fc92abeff61d6444f2ce6ad35bb982db9fc8ff8a47455beacf454a57"}, + {file = "aiohttp-3.13.4-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:153274535985a0ff2bff1fb6c104ed547cec898a09213d21b0f791a44b14d933"}, + {file = "aiohttp-3.13.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:351f3171e2458da3d731ce83f9e6b9619e325c45cbd534c7759750cabf453ad7"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f989ac8bc5595ff761a5ccd32bdb0768a117f36dd1504b1c2c074ed5d3f4df9c"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d36fc1709110ec1e87a229b201dd3ddc32aa01e98e7868083a794609b081c349"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:42adaeea83cbdf069ab94f5103ce0787c21fb1a0153270da76b59d5578302329"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:92deb95469928cc41fd4b42a95d8012fa6df93f6b1c0a83af0ffbc4a5e218cde"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0c0c7c07c4257ef3a1df355f840bc62d133bcdef5c1c5ba75add3c08553e2eed"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f062c45de8a1098cb137a1898819796a2491aec4e637a06b03f149315dff4d8f"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:76093107c531517001114f0ebdb4f46858ce818590363e3e99a4a2280334454a"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:6f6ec32162d293b82f8b63a16edc80769662fbd5ae6fbd4936d3206a2c2cc63b"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:5903e2db3d202a00ad9f0ec35a122c005e85d90c9836ab4cda628f01edf425e2"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:2d5bea57be7aca98dbbac8da046d99b5557c5cf4e28538c4c786313078aca09e"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:bcf0c9902085976edc0232b75006ef38f89686901249ce14226b6877f88464fb"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c3295f98bfeed2e867cab588f2a146a9db37a85e3ae9062abf46ba062bd29165"}, + {file = "aiohttp-3.13.4-cp314-cp314-win32.whl", hash = "sha256:a598a5c5767e1369d8f5b08695cab1d8160040f796c4416af76fd773d229b3c9"}, + {file = "aiohttp-3.13.4-cp314-cp314-win_amd64.whl", hash = "sha256:c555db4bc7a264bead5a7d63d92d41a1122fcd39cc62a4db815f45ad46f9c2c8"}, + {file = "aiohttp-3.13.4-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:45abbbf09a129825d13c18c7d3182fecd46d9da3cfc383756145394013604ac1"}, + {file = "aiohttp-3.13.4-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:74c80b2bc2c2adb7b3d1941b2b60701ee2af8296fc8aad8b8bc48bc25767266c"}, + {file = "aiohttp-3.13.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c97989ae40a9746650fa196894f317dafc12227c808c774929dda0ff873a5954"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dae86be9811493f9990ef44fff1685f5c1a3192e9061a71a109d527944eed551"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1db491abe852ca2fa6cc48a3341985b0174b3741838e1341b82ac82c8bd9e871"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0e5d701c0aad02a7dce72eef6b93226cf3734330f1a31d69ebbf69f33b86666e"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8ac32a189081ae0a10ba18993f10f338ec94341f0d5df8fff348043962f3c6f8"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:98e968cdaba43e45c73c3f306fca418c8009a957733bac85937c9f9cf3f4de27"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ca114790c9144c335d538852612d3e43ea0f075288f4849cf4b05d6cd2238ce7"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ea2e071661ba9cfe11eabbc81ac5376eaeb3061f6e72ec4cc86d7cdd1ffbdbbb"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:34e89912b6c20e0fd80e07fa401fd218a410aa1ce9f1c2f1dad6db1bd0ce0927"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0e217cf9f6a42908c52b46e42c568bd57adc39c9286ced31aaace614b6087965"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:0c296f1221e21ba979f5ac1964c3b78cfde15c5c5f855ffd2caab337e9cd9182"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:d99a9d168ebaffb74f36d011750e490085ac418f4db926cce3989c8fe6cb6b1b"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cb19177205d93b881f3f89e6081593676043a6828f59c78c17a0fd6c1fbed2ba"}, + {file = "aiohttp-3.13.4-cp314-cp314t-win32.whl", hash = "sha256:c606aa5656dab6552e52ca368e43869c916338346bfaf6304e15c58fb113ea30"}, + {file = "aiohttp-3.13.4-cp314-cp314t-win_amd64.whl", hash = "sha256:014dcc10ec8ab8db681f0d68e939d1e9286a5aa2b993cbbdb0db130853e02144"}, + {file = "aiohttp-3.13.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:b3f00bb9403728b08eb3951e982ca0a409c7a871d709684623daeab79465b181"}, + {file = "aiohttp-3.13.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:cb15595eb52870f84248d7cc97013a76f52ab02ff74d394be093b1d9b8b82bc0"}, + {file = "aiohttp-3.13.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:907ad36b6a65cff7d88d7aca0f77c650546ba850a4f92c92ecb83590d4613249"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5539ec0d6a3a5c6799b661b7e79166ad1b7ae71ccb59a92fcb6b4ef89295bc94"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3b4e07d8803a70dd886b5f38588e5b49f894995ca8e132b06c31a2583ae2ef6e"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ce7320a945aac4bf0bb8901600e4f9409eb602f25ce3ef4d275b48f6d704a862"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:26ed03f7d3d6453634729e2c7600d7255d65e879559c5a48fe1bb78355cde74b"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c3f733916e85506b8000dddc071c6b82f8c68f56c99adb328d6550017db062d"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b3d525648fe7c8b4977e460c18098f9f81d7991d72edfdc2f13cf96068f279bc"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:4e2e68085730a03704beb2cff035fa8648f62c9f93758d7e6d70add7f7bb5b3b"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:797613182ffaaca0b9ad5f3b3d3ce5d21242c768f75e66c750b8292bd97c9de3"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:2d15e7e4f1099d9e4d863eaf77a8eee5dcb002b7d7188061b0fbee37f845899e"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:19f60011ad60e40a01d242238bb335399e3a4d8df958c63cbb835add8d5c3b5a"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:c344c47e85678e410b064fc2ace14db86bb69db7ed5520c234bf13aed603ec30"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:d904084985ca66459e93797e5e05985c048a9c0633655331144c089943e53d12"}, + {file = "aiohttp-3.13.4-cp39-cp39-win32.whl", hash = "sha256:1746338dc2a33cf706cd7446575d13d451f28f9860bebc908c7632b22e71ae3f"}, + {file = "aiohttp-3.13.4-cp39-cp39-win_amd64.whl", hash = "sha256:a5444dce2e6fba0a1dc2d58d026e674f25f21de178c6f844342629bcef019f2f"}, + {file = "aiohttp-3.13.4.tar.gz", hash = "sha256:d97a6d09c66087890c2ab5d49069e1e570583f7ac0314ecf98294c1b6aaebd38"}, +] + +[package.dependencies] +aiohappyeyeballs = ">=2.5.0" +aiosignal = ">=1.4.0" +async-timeout = {version = ">=4.0,<6.0", markers = "python_version < \"3.11\""} +attrs = ">=17.3.0" +frozenlist = ">=1.1.1" +multidict = ">=4.5,<7.0" +propcache = ">=0.2.0" +yarl = ">=1.17.0,<2.0" + +[package.extras] +speedups = ["Brotli (>=1.2) ; platform_python_implementation == \"CPython\"", "aiodns (>=3.3.0)", "backports.zstd ; platform_python_implementation == \"CPython\" and python_version < \"3.14\"", "brotlicffi (>=1.2) ; platform_python_implementation != \"CPython\""] + +[[package]] +name = "aiosignal" +version = "1.4.0" +description = "aiosignal: a list of registered asynchronous callbacks" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e"}, + {file = "aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7"}, +] + +[package.dependencies] +frozenlist = ">=1.1.0" +typing-extensions = {version = ">=4.2", markers = "python_version < \"3.13\""} + +[[package]] +name = "async-timeout" +version = "5.0.1" +description = "Timeout context manager for asyncio programs" +optional = false +python-versions = ">=3.8" +groups = ["main"] +markers = "python_version < \"3.11\"" +files = [ + {file = "async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c"}, + {file = "async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3"}, +] + +[[package]] +name = "attrs" +version = "25.4.0" +description = "Classes Without Boilerplate" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "attrs-25.4.0-py3-none-any.whl", hash = "sha256:adcf7e2a1fb3b36ac48d97835bb6d8ade15b8dcce26aba8bf1d14847b57a3373"}, + {file = "attrs-25.4.0.tar.gz", hash = "sha256:16d5969b87f0859ef33a48b35d55ac1be6e42ae49d5e853b597db70c35c57e11"}, +] + +[[package]] +name = "certifi" +version = "2025.10.5" +description = "Python package for providing Mozilla's CA Bundle." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "certifi-2025.10.5-py3-none-any.whl", hash = "sha256:0f212c2744a9bb6de0c56639a6f68afe01ecd92d91f14ae897c4fe7bbeeef0de"}, + {file = "certifi-2025.10.5.tar.gz", hash = "sha256:47c09d31ccf2acf0be3f701ea53595ee7e0b8fa08801c6624be771df09ae7b43"}, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.4" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "charset_normalizer-3.4.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:e824f1492727fa856dd6eda4f7cee25f8518a12f3c4a56a74e8095695089cf6d"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4bd5d4137d500351a30687c2d3971758aac9a19208fc110ccb9d7188fbe709e8"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:027f6de494925c0ab2a55eab46ae5129951638a49a34d87f4c3eda90f696b4ad"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f820802628d2694cb7e56db99213f930856014862f3fd943d290ea8438d07ca8"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:798d75d81754988d2565bff1b97ba5a44411867c0cf32b77a7e8f8d84796b10d"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d1bb833febdff5c8927f922386db610b49db6e0d4f4ee29601d71e7c2694313"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9cd98cdc06614a2f768d2b7286d66805f94c48cde050acdbbb7db2600ab3197e"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:077fbb858e903c73f6c9db43374fd213b0b6a778106bc7032446a8e8b5b38b93"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:244bfb999c71b35de57821b8ea746b24e863398194a4014e4c76adc2bbdfeff0"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:64b55f9dce520635f018f907ff1b0df1fdc31f2795a922fb49dd14fbcdf48c84"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:faa3a41b2b66b6e50f84ae4a68c64fcd0c44355741c6374813a800cd6695db9e"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:6515f3182dbe4ea06ced2d9e8666d97b46ef4c75e326b79bb624110f122551db"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:cc00f04ed596e9dc0da42ed17ac5e596c6ccba999ba6bd92b0e0aef2f170f2d6"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-win32.whl", hash = "sha256:f34be2938726fc13801220747472850852fe6b1ea75869a048d6f896838c896f"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-win_amd64.whl", hash = "sha256:a61900df84c667873b292c3de315a786dd8dac506704dea57bc957bd31e22c7d"}, + {file = "charset_normalizer-3.4.4-cp310-cp310-win_arm64.whl", hash = "sha256:cead0978fc57397645f12578bfd2d5ea9138ea0fac82b2f63f7f7c6877986a69"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6e1fcf0720908f200cd21aa4e6750a48ff6ce4afe7ff5a79a90d5ed8a08296f8"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f819d5fe9234f9f82d75bdfa9aef3a3d72c4d24a6e57aeaebba32a704553aa0"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a59cb51917aa591b1c4e6a43c132f0cdc3c76dbad6155df4e28ee626cc77a0a3"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8ef3c867360f88ac904fd3f5e1f902f13307af9052646963ee08ff4f131adafc"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d9e45d7faa48ee908174d8fe84854479ef838fc6a705c9315372eacbc2f02897"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:840c25fb618a231545cbab0564a799f101b63b9901f2569faecd6b222ac72381"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ca5862d5b3928c4940729dacc329aa9102900382fea192fc5e52eb69d6093815"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d9c7f57c3d666a53421049053eaacdd14bbd0a528e2186fcb2e672effd053bb0"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:277e970e750505ed74c832b4bf75dac7476262ee2a013f5574dd49075879e161"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:31fd66405eaf47bb62e8cd575dc621c56c668f27d46a61d975a249930dd5e2a4"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:0d3d8f15c07f86e9ff82319b3d9ef6f4bf907608f53fe9d92b28ea9ae3d1fd89"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9f7fcd74d410a36883701fafa2482a6af2ff5ba96b9a620e9e0721e28ead5569"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ebf3e58c7ec8a8bed6d66a75d7fb37b55e5015b03ceae72a8e7c74495551e224"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-win32.whl", hash = "sha256:eecbc200c7fd5ddb9a7f16c7decb07b566c29fa2161a16cf67b8d068bd21690a"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-win_amd64.whl", hash = "sha256:5ae497466c7901d54b639cf42d5b8c1b6a4fead55215500d2f486d34db48d016"}, + {file = "charset_normalizer-3.4.4-cp311-cp311-win_arm64.whl", hash = "sha256:65e2befcd84bc6f37095f5961e68a6f077bf44946771354a28ad434c2cce0ae1"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0a98e6759f854bd25a58a73fa88833fba3b7c491169f86ce1180c948ab3fd394"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5b290ccc2a263e8d185130284f8501e3e36c5e02750fc6b6bdeb2e9e96f1e25"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:74bb723680f9f7a6234dcf67aea57e708ec1fbdf5699fb91dfd6f511b0a320ef"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f1e34719c6ed0b92f418c7c780480b26b5d9c50349e9a9af7d76bf757530350d"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2437418e20515acec67d86e12bf70056a33abdacb5cb1655042f6538d6b085a8"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:11d694519d7f29d6cd09f6ac70028dba10f92f6cdd059096db198c283794ac86"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ac1c4a689edcc530fc9d9aa11f5774b9e2f33f9a0c6a57864e90908f5208d30a"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:21d142cc6c0ec30d2efee5068ca36c128a30b0f2c53c1c07bd78cb6bc1d3be5f"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:5dbe56a36425d26d6cfb40ce79c314a2e4dd6211d51d6d2191c00bed34f354cc"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5bfbb1b9acf3334612667b61bd3002196fe2a1eb4dd74d247e0f2a4d50ec9bbf"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d055ec1e26e441f6187acf818b73564e6e6282709e9bcb5b63f5b23068356a15"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:af2d8c67d8e573d6de5bc30cdb27e9b95e49115cd9baad5ddbd1a6207aaa82a9"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:780236ac706e66881f3b7f2f32dfe90507a09e67d1d454c762cf642e6e1586e0"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-win32.whl", hash = "sha256:5833d2c39d8896e4e19b689ffc198f08ea58116bee26dea51e362ecc7cd3ed26"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-win_amd64.whl", hash = "sha256:a79cfe37875f822425b89a82333404539ae63dbdddf97f84dcbc3d339aae9525"}, + {file = "charset_normalizer-3.4.4-cp312-cp312-win_arm64.whl", hash = "sha256:376bec83a63b8021bb5c8ea75e21c4ccb86e7e45ca4eb81146091b56599b80c3"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:e1f185f86a6f3403aa2420e815904c67b2f9ebc443f045edd0de921108345794"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b39f987ae8ccdf0d2642338faf2abb1862340facc796048b604ef14919e55ed"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3162d5d8ce1bb98dd51af660f2121c55d0fa541b46dff7bb9b9f86ea1d87de72"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:81d5eb2a312700f4ecaa977a8235b634ce853200e828fbadf3a9c50bab278328"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5bd2293095d766545ec1a8f612559f6b40abc0eb18bb2f5d1171872d34036ede"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8a8b89589086a25749f471e6a900d3f662d1d3b6e2e59dcecf787b1cc3a1894"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bc7637e2f80d8530ee4a78e878bce464f70087ce73cf7c1caf142416923b98f1"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f8bf04158c6b607d747e93949aa60618b61312fe647a6369f88ce2ff16043490"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:554af85e960429cf30784dd47447d5125aaa3b99a6f0683589dbd27e2f45da44"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:74018750915ee7ad843a774364e13a3db91682f26142baddf775342c3f5b1133"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c0463276121fdee9c49b98908b3a89c39be45d86d1dbaa22957e38f6321d4ce3"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:362d61fd13843997c1c446760ef36f240cf81d3ebf74ac62652aebaf7838561e"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9a26f18905b8dd5d685d6d07b0cdf98a79f3c7a918906af7cc143ea2e164c8bc"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-win32.whl", hash = "sha256:9b35f4c90079ff2e2edc5b26c0c77925e5d2d255c42c74fdb70fb49b172726ac"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-win_amd64.whl", hash = "sha256:b435cba5f4f750aa6c0a0d92c541fb79f69a387c91e61f1795227e4ed9cece14"}, + {file = "charset_normalizer-3.4.4-cp313-cp313-win_arm64.whl", hash = "sha256:542d2cee80be6f80247095cc36c418f7bddd14f4a6de45af91dfad36d817bba2"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:da3326d9e65ef63a817ecbcc0df6e94463713b754fe293eaa03da99befb9a5bd"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8af65f14dc14a79b924524b1e7fffe304517b2bff5a58bf64f30b98bbc5079eb"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:74664978bb272435107de04e36db5a9735e78232b85b77d45cfb38f758efd33e"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:752944c7ffbfdd10c074dc58ec2d5a8a4cd9493b314d367c14d24c17684ddd14"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d1f13550535ad8cff21b8d757a3257963e951d96e20ec82ab44bc64aeb62a191"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ecaae4149d99b1c9e7b88bb03e3221956f68fd6d50be2ef061b2381b61d20838"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb6254dc36b47a990e59e1068afacdcd02958bdcce30bb50cc1700a8b9d624a6"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c8ae8a0f02f57a6e61203a31428fa1d677cbe50c93622b4149d5c0f319c1d19e"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:47cc91b2f4dd2833fddaedd2893006b0106129d4b94fdb6af1f4ce5a9965577c"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:82004af6c302b5d3ab2cfc4cc5f29db16123b1a8417f2e25f9066f91d4411090"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:2b7d8f6c26245217bd2ad053761201e9f9680f8ce52f0fcd8d0755aeae5b2152"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:799a7a5e4fb2d5898c60b640fd4981d6a25f1c11790935a44ce38c54e985f828"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:99ae2cffebb06e6c22bdc25801d7b30f503cc87dbd283479e7b606f70aff57ec"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-win32.whl", hash = "sha256:f9d332f8c2a2fcbffe1378594431458ddbef721c1769d78e2cbc06280d8155f9"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-win_amd64.whl", hash = "sha256:8a6562c3700cce886c5be75ade4a5db4214fda19fede41d9792d100288d8f94c"}, + {file = "charset_normalizer-3.4.4-cp314-cp314-win_arm64.whl", hash = "sha256:de00632ca48df9daf77a2c65a484531649261ec9f25489917f09e455cb09ddb2"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:ce8a0633f41a967713a59c4139d29110c07e826d131a316b50ce11b1d79b4f84"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaabd426fe94daf8fd157c32e571c85cb12e66692f15516a83a03264b08d06c3"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c4ef880e27901b6cc782f1b95f82da9313c0eb95c3af699103088fa0ac3ce9ac"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2aaba3b0819274cc41757a1da876f810a3e4d7b6eb25699253a4effef9e8e4af"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:778d2e08eda00f4256d7f672ca9fef386071c9202f5e4607920b86d7803387f2"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f155a433c2ec037d4e8df17d18922c3a0d9b3232a396690f17175d2946f0218d"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a8bf8d0f749c5757af2142fe7903a9df1d2e8aa3841559b2bad34b08d0e2bcf3"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:194f08cbb32dc406d6e1aea671a68be0823673db2832b38405deba2fb0d88f63"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-musllinux_1_2_armv7l.whl", hash = "sha256:6aee717dcfead04c6eb1ce3bd29ac1e22663cdea57f943c87d1eab9a025438d7"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-musllinux_1_2_ppc64le.whl", hash = "sha256:cd4b7ca9984e5e7985c12bc60a6f173f3c958eae74f3ef6624bb6b26e2abbae4"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-musllinux_1_2_riscv64.whl", hash = "sha256:b7cf1017d601aa35e6bb650b6ad28652c9cd78ee6caff19f3c28d03e1c80acbf"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-musllinux_1_2_s390x.whl", hash = "sha256:e912091979546adf63357d7e2ccff9b44f026c075aeaf25a52d0e95ad2281074"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:5cb4d72eea50c8868f5288b7f7f33ed276118325c1dfd3957089f6b519e1382a"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-win32.whl", hash = "sha256:837c2ce8c5a65a2035be9b3569c684358dfbf109fd3b6969630a87535495ceaa"}, + {file = "charset_normalizer-3.4.4-cp38-cp38-win_amd64.whl", hash = "sha256:44c2a8734b333e0578090c4cd6b16f275e07aa6614ca8715e6c038e865e70576"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:a9768c477b9d7bd54bc0c86dbaebdec6f03306675526c9927c0e8a04e8f94af9"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1bee1e43c28aa63cb16e5c14e582580546b08e535299b8b6158a7c9c768a1f3d"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:fd44c878ea55ba351104cb93cc85e74916eb8fa440ca7903e57575e97394f608"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0f04b14ffe5fdc8c4933862d8306109a2c51e0704acfa35d51598eb45a1e89fc"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:cd09d08005f958f370f539f186d10aec3377d55b9eeb0d796025d4886119d76e"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4fe7859a4e3e8457458e2ff592f15ccb02f3da787fcd31e0183879c3ad4692a1"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fa09f53c465e532f4d3db095e0c55b615f010ad81803d383195b6b5ca6cbf5f3"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:7fa17817dc5625de8a027cb8b26d9fefa3ea28c8253929b8d6649e705d2835b6"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:5947809c8a2417be3267efc979c47d76a079758166f7d43ef5ae8e9f92751f88"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:4902828217069c3c5c71094537a8e623f5d097858ac6ca8252f7b4d10b7560f1"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:7c308f7e26e4363d79df40ca5b2be1c6ba9f02bdbccfed5abddb7859a6ce72cf"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:2c9d3c380143a1fedbff95a312aa798578371eb29da42106a29019368a475318"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:cb01158d8b88ee68f15949894ccc6712278243d95f344770fa7593fa2d94410c"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-win32.whl", hash = "sha256:2677acec1a2f8ef614c6888b5b4ae4060cc184174a938ed4e8ef690e15d3e505"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-win_amd64.whl", hash = "sha256:f8e160feb2aed042cd657a72acc0b481212ed28b1b9a95c0cee1621b524e1966"}, + {file = "charset_normalizer-3.4.4-cp39-cp39-win_arm64.whl", hash = "sha256:b5d84d37db046c5ca74ee7bb47dd6cbc13f80665fdde3e8040bdd3fb015ecb50"}, + {file = "charset_normalizer-3.4.4-py3-none-any.whl", hash = "sha256:7a32c560861a02ff789ad905a2fe94e3f840803362c84fecf1851cb4cf3dc37f"}, + {file = "charset_normalizer-3.4.4.tar.gz", hash = "sha256:94537985111c35f28720e43603b8e7b43a6ecfb2ce1d3058bbe955b73404e21a"}, +] + +[[package]] +name = "cloudevents" +version = "1.12.0" +description = "CloudEvents Python SDK" +optional = false +python-versions = "*" +groups = ["main"] +files = [ + {file = "cloudevents-1.12.0-py3-none-any.whl", hash = "sha256:49196267f5f963d87ae156f93fc0fa32f4af69485f2c8e62e0db8b0b4b8b8921"}, + {file = "cloudevents-1.12.0.tar.gz", hash = "sha256:ebd5544ceb58c8378a0787b657a2ae895e929b80a82d6675cba63f0e8c5539e0"}, +] + +[package.dependencies] +deprecation = ">=2.0,<3.0" + +[package.extras] +pydantic = ["pydantic (>=1.0.0,<3.0)"] + +[[package]] +name = "corehttp" +version = "1.0.0b6" +description = "CoreHTTP Library for Python" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "corehttp-1.0.0b6-py3-none-any.whl", hash = "sha256:3cd421b9267350b7fb6b1bb06022f615a083a41352c766fc1cb490c4cf2c641e"}, + {file = "corehttp-1.0.0b6.tar.gz", hash = "sha256:ee2f16decb02fc1d6e5b4502404053937734f0740646be186fe4a98a7f2dbb18"}, +] + +[package.dependencies] +aiohttp = {version = ">=3.0", optional = true, markers = "extra == \"aiohttp\""} +requests = {version = ">=2.18.4", optional = true, markers = "extra == \"requests\""} +typing-extensions = ">=4.6.0" + +[package.extras] +aiohttp = ["aiohttp (>=3.0)"] +httpx = ["httpx (>=0.25.0)"] +requests = ["requests (>=2.18.4)"] + +[[package]] +name = "deprecation" +version = "2.1.0" +description = "A library to handle automated deprecations" +optional = false +python-versions = "*" +groups = ["main"] +files = [ + {file = "deprecation-2.1.0-py2.py3-none-any.whl", hash = "sha256:a10811591210e1fb0e768a8c25517cabeabcba6f0bf96564f8ff45189f90b14a"}, + {file = "deprecation-2.1.0.tar.gz", hash = "sha256:72b3bde64e5d778694b0cf68178aed03d15e15477116add3fb773e581f9518ff"}, +] + +[package.dependencies] +packaging = "*" + +[[package]] +name = "frozenlist" +version = "1.8.0" +description = "A list-like structure which implements collections.abc.MutableSequence" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "frozenlist-1.8.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b37f6d31b3dcea7deb5e9696e529a6aa4a898adc33db82da12e4c60a7c4d2011"}, + {file = "frozenlist-1.8.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ef2b7b394f208233e471abc541cc6991f907ffd47dc72584acee3147899d6565"}, + {file = "frozenlist-1.8.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a88f062f072d1589b7b46e951698950e7da00442fc1cacbe17e19e025dc327ad"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f57fb59d9f385710aa7060e89410aeb5058b99e62f4d16b08b91986b9a2140c2"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:799345ab092bee59f01a915620b5d014698547afd011e691a208637312db9186"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c23c3ff005322a6e16f71bf8692fcf4d5a304aaafe1e262c98c6d4adc7be863e"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8a76ea0f0b9dfa06f254ee06053d93a600865b3274358ca48a352ce4f0798450"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c7366fe1418a6133d5aa824ee53d406550110984de7637d65a178010f759c6ef"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:13d23a45c4cebade99340c4165bd90eeb4a56c6d8a9d8aa49568cac19a6d0dc4"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:e4a3408834f65da56c83528fb52ce7911484f0d1eaf7b761fc66001db1646eff"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:42145cd2748ca39f32801dad54aeea10039da6f86e303659db90db1c4b614c8c"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:e2de870d16a7a53901e41b64ffdf26f2fbb8917b3e6ebf398098d72c5b20bd7f"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:20e63c9493d33ee48536600d1a5c95eefc870cd71e7ab037763d1fbb89cc51e7"}, + {file = "frozenlist-1.8.0-cp310-cp310-win32.whl", hash = "sha256:adbeebaebae3526afc3c96fad434367cafbfd1b25d72369a9e5858453b1bb71a"}, + {file = "frozenlist-1.8.0-cp310-cp310-win_amd64.whl", hash = "sha256:667c3777ca571e5dbeb76f331562ff98b957431df140b54c85fd4d52eea8d8f6"}, + {file = "frozenlist-1.8.0-cp310-cp310-win_arm64.whl", hash = "sha256:80f85f0a7cc86e7a54c46d99c9e1318ff01f4687c172ede30fd52d19d1da1c8e"}, + {file = "frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84"}, + {file = "frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9"}, + {file = "frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967"}, + {file = "frozenlist-1.8.0-cp311-cp311-win32.whl", hash = "sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25"}, + {file = "frozenlist-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b"}, + {file = "frozenlist-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a"}, + {file = "frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1"}, + {file = "frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b"}, + {file = "frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa"}, + {file = "frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf"}, + {file = "frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746"}, + {file = "frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd"}, + {file = "frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a"}, + {file = "frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7"}, + {file = "frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed"}, + {file = "frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496"}, + {file = "frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231"}, + {file = "frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62"}, + {file = "frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94"}, + {file = "frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c"}, + {file = "frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41"}, + {file = "frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b"}, + {file = "frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888"}, + {file = "frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042"}, + {file = "frozenlist-1.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0"}, + {file = "frozenlist-1.8.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f"}, + {file = "frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7"}, + {file = "frozenlist-1.8.0-cp314-cp314-win32.whl", hash = "sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806"}, + {file = "frozenlist-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0"}, + {file = "frozenlist-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b"}, + {file = "frozenlist-1.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d"}, + {file = "frozenlist-1.8.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed"}, + {file = "frozenlist-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e"}, + {file = "frozenlist-1.8.0-cp314-cp314t-win32.whl", hash = "sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df"}, + {file = "frozenlist-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd"}, + {file = "frozenlist-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79"}, + {file = "frozenlist-1.8.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:d8b7138e5cd0647e4523d6685b0eac5d4be9a184ae9634492f25c6eb38c12a47"}, + {file = "frozenlist-1.8.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a6483e309ca809f1efd154b4d37dc6d9f61037d6c6a81c2dc7a15cb22c8c5dca"}, + {file = "frozenlist-1.8.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1b9290cf81e95e93fdf90548ce9d3c1211cf574b8e3f4b3b7cb0537cf2227068"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:59a6a5876ca59d1b63af8cd5e7ffffb024c3dc1e9cf9301b21a2e76286505c95"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6dc4126390929823e2d2d9dc79ab4046ed74680360fc5f38b585c12c66cdf459"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:332db6b2563333c5671fecacd085141b5800cb866be16d5e3eb15a2086476675"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9ff15928d62a0b80bb875655c39bf517938c7d589554cbd2669be42d97c2cb61"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7bf6cdf8e07c8151fba6fe85735441240ec7f619f935a5205953d58009aef8c6"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:48e6d3f4ec5c7273dfe83ff27c91083c6c9065af655dc2684d2c200c94308bb5"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:1a7607e17ad33361677adcd1443edf6f5da0ce5e5377b798fba20fae194825f3"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:5a3a935c3a4e89c733303a2d5a7c257ea44af3a56c8202df486b7f5de40f37e1"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:940d4a017dbfed9daf46a3b086e1d2167e7012ee297fef9e1c545c4d022f5178"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:b9be22a69a014bc47e78072d0ecae716f5eb56c15238acca0f43d6eb8e4a5bda"}, + {file = "frozenlist-1.8.0-cp39-cp39-win32.whl", hash = "sha256:1aa77cb5697069af47472e39612976ed05343ff2e84a3dcf15437b232cbfd087"}, + {file = "frozenlist-1.8.0-cp39-cp39-win_amd64.whl", hash = "sha256:7398c222d1d405e796970320036b1b563892b65809d9e5261487bb2c7f7b5c6a"}, + {file = "frozenlist-1.8.0-cp39-cp39-win_arm64.whl", hash = "sha256:b4f3b365f31c6cd4af24545ca0a244a53688cad8834e32f56831c4923b50a103"}, + {file = "frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d"}, + {file = "frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad"}, +] + +[[package]] +name = "idna" +version = "3.11" +description = "Internationalized Domain Names in Applications (IDNA)" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea"}, + {file = "idna-3.11.tar.gz", hash = "sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902"}, +] + +[package.extras] +all = ["flake8 (>=7.1.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2)"] + +[[package]] +name = "isodate" +version = "0.7.2" +description = "An ISO 8601 date/time/duration parser and formatter" +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "isodate-0.7.2-py3-none-any.whl", hash = "sha256:28009937d8031054830160fce6d409ed342816b543597cece116d966c6d99e15"}, + {file = "isodate-0.7.2.tar.gz", hash = "sha256:4cd1aa0f43ca76f4a6c6c0292a85f40b35ec2e43e315b59f06e6d32171a953e6"}, +] + +[[package]] +name = "multidict" +version = "6.7.0" +description = "multidict implementation" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "multidict-6.7.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:9f474ad5acda359c8758c8accc22032c6abe6dc87a8be2440d097785e27a9349"}, + {file = "multidict-6.7.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4b7a9db5a870f780220e931d0002bbfd88fb53aceb6293251e2c839415c1b20e"}, + {file = "multidict-6.7.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:03ca744319864e92721195fa28c7a3b2bc7b686246b35e4078c1e4d0eb5466d3"}, + {file = "multidict-6.7.0-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f0e77e3c0008bc9316e662624535b88d360c3a5d3f81e15cf12c139a75250046"}, + {file = "multidict-6.7.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:08325c9e5367aa379a3496aa9a022fe8837ff22e00b94db256d3a1378c76ab32"}, + {file = "multidict-6.7.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e2862408c99f84aa571ab462d25236ef9cb12a602ea959ba9c9009a54902fc73"}, + {file = "multidict-6.7.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4d72a9a2d885f5c208b0cb91ff2ed43636bb7e345ec839ff64708e04f69a13cc"}, + {file = "multidict-6.7.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:478cc36476687bac1514d651cbbaa94b86b0732fb6855c60c673794c7dd2da62"}, + {file = "multidict-6.7.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6843b28b0364dc605f21481c90fadb5f60d9123b442eb8a726bb74feef588a84"}, + {file = "multidict-6.7.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:23bfeee5316266e5ee2d625df2d2c602b829435fc3a235c2ba2131495706e4a0"}, + {file = "multidict-6.7.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:680878b9f3d45c31e1f730eef731f9b0bc1da456155688c6745ee84eb818e90e"}, + {file = "multidict-6.7.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:eb866162ef2f45063acc7a53a88ef6fe8bf121d45c30ea3c9cd87ce7e191a8d4"}, + {file = "multidict-6.7.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:df0e3bf7993bdbeca5ac25aa859cf40d39019e015c9c91809ba7093967f7a648"}, + {file = "multidict-6.7.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:661709cdcd919a2ece2234f9bae7174e5220c80b034585d7d8a755632d3e2111"}, + {file = "multidict-6.7.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:096f52730c3fb8ed419db2d44391932b63891b2c5ed14850a7e215c0ba9ade36"}, + {file = "multidict-6.7.0-cp310-cp310-win32.whl", hash = "sha256:afa8a2978ec65d2336305550535c9c4ff50ee527914328c8677b3973ade52b85"}, + {file = "multidict-6.7.0-cp310-cp310-win_amd64.whl", hash = "sha256:b15b3afff74f707b9275d5ba6a91ae8f6429c3ffb29bbfd216b0b375a56f13d7"}, + {file = "multidict-6.7.0-cp310-cp310-win_arm64.whl", hash = "sha256:4b73189894398d59131a66ff157837b1fafea9974be486d036bb3d32331fdbf0"}, + {file = "multidict-6.7.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4d409aa42a94c0b3fa617708ef5276dfe81012ba6753a0370fcc9d0195d0a1fc"}, + {file = "multidict-6.7.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:14c9e076eede3b54c636f8ce1c9c252b5f057c62131211f0ceeec273810c9721"}, + {file = "multidict-6.7.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4c09703000a9d0fa3c3404b27041e574cc7f4df4c6563873246d0e11812a94b6"}, + {file = "multidict-6.7.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:a265acbb7bb33a3a2d626afbe756371dce0279e7b17f4f4eda406459c2b5ff1c"}, + {file = "multidict-6.7.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51cb455de290ae462593e5b1cb1118c5c22ea7f0d3620d9940bf695cea5a4bd7"}, + {file = "multidict-6.7.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:db99677b4457c7a5c5a949353e125ba72d62b35f74e26da141530fbb012218a7"}, + {file = "multidict-6.7.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f470f68adc395e0183b92a2f4689264d1ea4b40504a24d9882c27375e6662bb9"}, + {file = "multidict-6.7.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0db4956f82723cc1c270de9c6e799b4c341d327762ec78ef82bb962f79cc07d8"}, + {file = "multidict-6.7.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3e56d780c238f9e1ae66a22d2adf8d16f485381878250db8d496623cd38b22bd"}, + {file = "multidict-6.7.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:9d14baca2ee12c1a64740d4531356ba50b82543017f3ad6de0deb943c5979abb"}, + {file = "multidict-6.7.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:295a92a76188917c7f99cda95858c822f9e4aae5824246bba9b6b44004ddd0a6"}, + {file = "multidict-6.7.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:39f1719f57adbb767ef592a50ae5ebb794220d1188f9ca93de471336401c34d2"}, + {file = "multidict-6.7.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:0a13fb8e748dfc94749f622de065dd5c1def7e0d2216dba72b1d8069a389c6ff"}, + {file = "multidict-6.7.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:e3aa16de190d29a0ea1b48253c57d99a68492c8dd8948638073ab9e74dc9410b"}, + {file = "multidict-6.7.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a048ce45dcdaaf1defb76b2e684f997fb5abf74437b6cb7b22ddad934a964e34"}, + {file = "multidict-6.7.0-cp311-cp311-win32.whl", hash = "sha256:a90af66facec4cebe4181b9e62a68be65e45ac9b52b67de9eec118701856e7ff"}, + {file = "multidict-6.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:95b5ffa4349df2887518bb839409bcf22caa72d82beec453216802f475b23c81"}, + {file = "multidict-6.7.0-cp311-cp311-win_arm64.whl", hash = "sha256:329aa225b085b6f004a4955271a7ba9f1087e39dcb7e65f6284a988264a63912"}, + {file = "multidict-6.7.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8a3862568a36d26e650a19bb5cbbba14b71789032aebc0423f8cc5f150730184"}, + {file = "multidict-6.7.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:960c60b5849b9b4f9dcc9bea6e3626143c252c74113df2c1540aebce70209b45"}, + {file = "multidict-6.7.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2049be98fb57a31b4ccf870bf377af2504d4ae35646a19037ec271e4c07998aa"}, + {file = "multidict-6.7.0-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:0934f3843a1860dd465d38895c17fce1f1cb37295149ab05cd1b9a03afacb2a7"}, + {file = "multidict-6.7.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b3e34f3a1b8131ba06f1a73adab24f30934d148afcd5f5de9a73565a4404384e"}, + {file = "multidict-6.7.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:efbb54e98446892590dc2458c19c10344ee9a883a79b5cec4bc34d6656e8d546"}, + {file = "multidict-6.7.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a35c5fc61d4f51eb045061e7967cfe3123d622cd500e8868e7c0c592a09fedc4"}, + {file = "multidict-6.7.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29fe6740ebccba4175af1b9b87bf553e9c15cd5868ee967e010efcf94e4fd0f1"}, + {file = "multidict-6.7.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:123e2a72e20537add2f33a79e605f6191fba2afda4cbb876e35c1a7074298a7d"}, + {file = "multidict-6.7.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b284e319754366c1aee2267a2036248b24eeb17ecd5dc16022095e747f2f4304"}, + {file = "multidict-6.7.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:803d685de7be4303b5a657b76e2f6d1240e7e0a8aa2968ad5811fa2285553a12"}, + {file = "multidict-6.7.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c04a328260dfd5db8c39538f999f02779012268f54614902d0afc775d44e0a62"}, + {file = "multidict-6.7.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8a19cdb57cd3df4cd865849d93ee14920fb97224300c88501f16ecfa2604b4e0"}, + {file = "multidict-6.7.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9b2fd74c52accced7e75de26023b7dccee62511a600e62311b918ec5c168fc2a"}, + {file = "multidict-6.7.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3e8bfdd0e487acf992407a140d2589fe598238eaeffa3da8448d63a63cd363f8"}, + {file = "multidict-6.7.0-cp312-cp312-win32.whl", hash = "sha256:dd32a49400a2c3d52088e120ee00c1e3576cbff7e10b98467962c74fdb762ed4"}, + {file = "multidict-6.7.0-cp312-cp312-win_amd64.whl", hash = "sha256:92abb658ef2d7ef22ac9f8bb88e8b6c3e571671534e029359b6d9e845923eb1b"}, + {file = "multidict-6.7.0-cp312-cp312-win_arm64.whl", hash = "sha256:490dab541a6a642ce1a9d61a4781656b346a55c13038f0b1244653828e3a83ec"}, + {file = "multidict-6.7.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:bee7c0588aa0076ce77c0ea5d19a68d76ad81fcd9fe8501003b9a24f9d4000f6"}, + {file = "multidict-6.7.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7ef6b61cad77091056ce0e7ce69814ef72afacb150b7ac6a3e9470def2198159"}, + {file = "multidict-6.7.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9c0359b1ec12b1d6849c59f9d319610b7f20ef990a6d454ab151aa0e3b9f78ca"}, + {file = "multidict-6.7.0-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cd240939f71c64bd658f186330603aac1a9a81bf6273f523fca63673cb7378a8"}, + {file = "multidict-6.7.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a60a4d75718a5efa473ebd5ab685786ba0c67b8381f781d1be14da49f1a2dc60"}, + {file = "multidict-6.7.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:53a42d364f323275126aff81fb67c5ca1b7a04fda0546245730a55c8c5f24bc4"}, + {file = "multidict-6.7.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3b29b980d0ddbecb736735ee5bef69bb2ddca56eff603c86f3f29a1128299b4f"}, + {file = "multidict-6.7.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f8a93b1c0ed2d04b97a5e9336fd2d33371b9a6e29ab7dd6503d63407c20ffbaf"}, + {file = "multidict-6.7.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ff96e8815eecacc6645da76c413eb3b3d34cfca256c70b16b286a687d013c32"}, + {file = "multidict-6.7.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:7516c579652f6a6be0e266aec0acd0db80829ca305c3d771ed898538804c2036"}, + {file = "multidict-6.7.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:040f393368e63fb0f3330e70c26bfd336656bed925e5cbe17c9da839a6ab13ec"}, + {file = "multidict-6.7.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b3bc26a951007b1057a1c543af845f1c7e3e71cc240ed1ace7bf4484aa99196e"}, + {file = "multidict-6.7.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7b022717c748dd1992a83e219587aabe45980d88969f01b316e78683e6285f64"}, + {file = "multidict-6.7.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:9600082733859f00d79dee64effc7aef1beb26adb297416a4ad2116fd61374bd"}, + {file = "multidict-6.7.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:94218fcec4d72bc61df51c198d098ce2b378e0ccbac41ddbed5ef44092913288"}, + {file = "multidict-6.7.0-cp313-cp313-win32.whl", hash = "sha256:a37bd74c3fa9d00be2d7b8eca074dc56bd8077ddd2917a839bd989612671ed17"}, + {file = "multidict-6.7.0-cp313-cp313-win_amd64.whl", hash = "sha256:30d193c6cc6d559db42b6bcec8a5d395d34d60c9877a0b71ecd7c204fcf15390"}, + {file = "multidict-6.7.0-cp313-cp313-win_arm64.whl", hash = "sha256:ea3334cabe4d41b7ccd01e4d349828678794edbc2d3ae97fc162a3312095092e"}, + {file = "multidict-6.7.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:ad9ce259f50abd98a1ca0aa6e490b58c316a0fce0617f609723e40804add2c00"}, + {file = "multidict-6.7.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07f5594ac6d084cbb5de2df218d78baf55ef150b91f0ff8a21cc7a2e3a5a58eb"}, + {file = "multidict-6.7.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:0591b48acf279821a579282444814a2d8d0af624ae0bc600aa4d1b920b6e924b"}, + {file = "multidict-6.7.0-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:749a72584761531d2b9467cfbdfd29487ee21124c304c4b6cb760d8777b27f9c"}, + {file = "multidict-6.7.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b4c3d199f953acd5b446bf7c0de1fe25d94e09e79086f8dc2f48a11a129cdf1"}, + {file = "multidict-6.7.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:9fb0211dfc3b51efea2f349ec92c114d7754dd62c01f81c3e32b765b70c45c9b"}, + {file = "multidict-6.7.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a027ec240fe73a8d6281872690b988eed307cd7d91b23998ff35ff577ca688b5"}, + {file = "multidict-6.7.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d1d964afecdf3a8288789df2f5751dc0a8261138c3768d9af117ed384e538fad"}, + {file = "multidict-6.7.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:caf53b15b1b7df9fbd0709aa01409000a2b4dd03a5f6f5cc548183c7c8f8b63c"}, + {file = "multidict-6.7.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:654030da3197d927f05a536a66186070e98765aa5142794c9904555d3a9d8fb5"}, + {file = "multidict-6.7.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:2090d3718829d1e484706a2f525e50c892237b2bf9b17a79b059cb98cddc2f10"}, + {file = "multidict-6.7.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:2d2cfeec3f6f45651b3d408c4acec0ebf3daa9bc8a112a084206f5db5d05b754"}, + {file = "multidict-6.7.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:4ef089f985b8c194d341eb2c24ae6e7408c9a0e2e5658699c92f497437d88c3c"}, + {file = "multidict-6.7.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:e93a0617cd16998784bf4414c7e40f17a35d2350e5c6f0bd900d3a8e02bd3762"}, + {file = "multidict-6.7.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:f0feece2ef8ebc42ed9e2e8c78fc4aa3cf455733b507c09ef7406364c94376c6"}, + {file = "multidict-6.7.0-cp313-cp313t-win32.whl", hash = "sha256:19a1d55338ec1be74ef62440ca9e04a2f001a04d0cc49a4983dc320ff0f3212d"}, + {file = "multidict-6.7.0-cp313-cp313t-win_amd64.whl", hash = "sha256:3da4fb467498df97e986af166b12d01f05d2e04f978a9c1c680ea1988e0bc4b6"}, + {file = "multidict-6.7.0-cp313-cp313t-win_arm64.whl", hash = "sha256:b4121773c49a0776461f4a904cdf6264c88e42218aaa8407e803ca8025872792"}, + {file = "multidict-6.7.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3bab1e4aff7adaa34410f93b1f8e57c4b36b9af0426a76003f441ee1d3c7e842"}, + {file = "multidict-6.7.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b8512bac933afc3e45fb2b18da8e59b78d4f408399a960339598374d4ae3b56b"}, + {file = "multidict-6.7.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:79dcf9e477bc65414ebfea98ffd013cb39552b5ecd62908752e0e413d6d06e38"}, + {file = "multidict-6.7.0-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:31bae522710064b5cbeddaf2e9f32b1abab70ac6ac91d42572502299e9953128"}, + {file = "multidict-6.7.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a0df7ff02397bb63e2fd22af2c87dfa39e8c7f12947bc524dbdc528282c7e34"}, + {file = "multidict-6.7.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a0222514e8e4c514660e182d5156a415c13ef0aabbd71682fc714e327b95e99"}, + {file = "multidict-6.7.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2397ab4daaf2698eb51a76721e98db21ce4f52339e535725de03ea962b5a3202"}, + {file = "multidict-6.7.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8891681594162635948a636c9fe0ff21746aeb3dd5463f6e25d9bea3a8a39ca1"}, + {file = "multidict-6.7.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18706cc31dbf402a7945916dd5cddf160251b6dab8a2c5f3d6d5a55949f676b3"}, + {file = "multidict-6.7.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f844a1bbf1d207dd311a56f383f7eda2d0e134921d45751842d8235e7778965d"}, + {file = "multidict-6.7.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:d4393e3581e84e5645506923816b9cc81f5609a778c7e7534054091acc64d1c6"}, + {file = "multidict-6.7.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:fbd18dc82d7bf274b37aa48d664534330af744e03bccf696d6f4c6042e7d19e7"}, + {file = "multidict-6.7.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:b6234e14f9314731ec45c42fc4554b88133ad53a09092cc48a88e771c125dadb"}, + {file = "multidict-6.7.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:08d4379f9744d8f78d98c8673c06e202ffa88296f009c71bbafe8a6bf847d01f"}, + {file = "multidict-6.7.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9fe04da3f79387f450fd0061d4dd2e45a72749d31bf634aecc9e27f24fdc4b3f"}, + {file = "multidict-6.7.0-cp314-cp314-win32.whl", hash = "sha256:fbafe31d191dfa7c4c51f7a6149c9fb7e914dcf9ffead27dcfd9f1ae382b3885"}, + {file = "multidict-6.7.0-cp314-cp314-win_amd64.whl", hash = "sha256:2f67396ec0310764b9222a1728ced1ab638f61aadc6226f17a71dd9324f9a99c"}, + {file = "multidict-6.7.0-cp314-cp314-win_arm64.whl", hash = "sha256:ba672b26069957ee369cfa7fc180dde1fc6f176eaf1e6beaf61fbebbd3d9c000"}, + {file = "multidict-6.7.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:c1dcc7524066fa918c6a27d61444d4ee7900ec635779058571f70d042d86ed63"}, + {file = "multidict-6.7.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:27e0b36c2d388dc7b6ced3406671b401e84ad7eb0656b8f3a2f46ed0ce483718"}, + {file = "multidict-6.7.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2a7baa46a22e77f0988e3b23d4ede5513ebec1929e34ee9495be535662c0dfe2"}, + {file = "multidict-6.7.0-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7bf77f54997a9166a2f5675d1201520586439424c2511723a7312bdb4bcc034e"}, + {file = "multidict-6.7.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e011555abada53f1578d63389610ac8a5400fc70ce71156b0aa30d326f1a5064"}, + {file = "multidict-6.7.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:28b37063541b897fd6a318007373930a75ca6d6ac7c940dbe14731ffdd8d498e"}, + {file = "multidict-6.7.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:05047ada7a2fde2631a0ed706f1fd68b169a681dfe5e4cf0f8e4cb6618bbc2cd"}, + {file = "multidict-6.7.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:716133f7d1d946a4e1b91b1756b23c088881e70ff180c24e864c26192ad7534a"}, + {file = "multidict-6.7.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d1bed1b467ef657f2a0ae62844a607909ef1c6889562de5e1d505f74457d0b96"}, + {file = "multidict-6.7.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca43bdfa5d37bd6aee89d85e1d0831fb86e25541be7e9d376ead1b28974f8e5e"}, + {file = "multidict-6.7.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:44b546bd3eb645fd26fb949e43c02a25a2e632e2ca21a35e2e132c8105dc8599"}, + {file = "multidict-6.7.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:a6ef16328011d3f468e7ebc326f24c1445f001ca1dec335b2f8e66bed3006394"}, + {file = "multidict-6.7.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:5aa873cbc8e593d361ae65c68f85faadd755c3295ea2c12040ee146802f23b38"}, + {file = "multidict-6.7.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:3d7b6ccce016e29df4b7ca819659f516f0bc7a4b3efa3bb2012ba06431b044f9"}, + {file = "multidict-6.7.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:171b73bd4ee683d307599b66793ac80981b06f069b62eea1c9e29c9241aa66b0"}, + {file = "multidict-6.7.0-cp314-cp314t-win32.whl", hash = "sha256:b2d7f80c4e1fd010b07cb26820aae86b7e73b681ee4889684fb8d2d4537aab13"}, + {file = "multidict-6.7.0-cp314-cp314t-win_amd64.whl", hash = "sha256:09929cab6fcb68122776d575e03c6cc64ee0b8fca48d17e135474b042ce515cd"}, + {file = "multidict-6.7.0-cp314-cp314t-win_arm64.whl", hash = "sha256:cc41db090ed742f32bd2d2c721861725e6109681eddf835d0a82bd3a5c382827"}, + {file = "multidict-6.7.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:363eb68a0a59bd2303216d2346e6c441ba10d36d1f9969fcb6f1ba700de7bb5c"}, + {file = "multidict-6.7.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:d874eb056410ca05fed180b6642e680373688efafc7f077b2a2f61811e873a40"}, + {file = "multidict-6.7.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8b55d5497b51afdfde55925e04a022f1de14d4f4f25cdfd4f5d9b0aa96166851"}, + {file = "multidict-6.7.0-cp39-cp39-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f8e5c0031b90ca9ce555e2e8fd5c3b02a25f14989cbc310701823832c99eb687"}, + {file = "multidict-6.7.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9cf41880c991716f3c7cec48e2f19ae4045fc9db5fc9cff27347ada24d710bb5"}, + {file = "multidict-6.7.0-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8cfc12a8630a29d601f48d47787bd7eb730e475e83edb5d6c5084317463373eb"}, + {file = "multidict-6.7.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3996b50c3237c4aec17459217c1e7bbdead9a22a0fcd3c365564fbd16439dde6"}, + {file = "multidict-6.7.0-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7f5170993a0dd3ab871c74f45c0a21a4e2c37a2f2b01b5f722a2ad9c6650469e"}, + {file = "multidict-6.7.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ec81878ddf0e98817def1e77d4f50dae5ef5b0e4fe796fae3bd674304172416e"}, + {file = "multidict-6.7.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:9281bf5b34f59afbc6b1e477a372e9526b66ca446f4bf62592839c195a718b32"}, + {file = "multidict-6.7.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:68af405971779d8b37198726f2b6fe3955db846fee42db7a4286fc542203934c"}, + {file = "multidict-6.7.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:3ba3ef510467abb0667421a286dc906e30eb08569365f5cdb131d7aff7c2dd84"}, + {file = "multidict-6.7.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:b61189b29081a20c7e4e0b49b44d5d44bb0dc92be3c6d06a11cc043f81bf9329"}, + {file = "multidict-6.7.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:fb287618b9c7aa3bf8d825f02d9201b2f13078a5ed3b293c8f4d953917d84d5e"}, + {file = "multidict-6.7.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:521f33e377ff64b96c4c556b81c55d0cfffb96a11c194fd0c3f1e56f3d8dd5a4"}, + {file = "multidict-6.7.0-cp39-cp39-win32.whl", hash = "sha256:ce8fdc2dca699f8dbf055a61d73eaa10482569ad20ee3c36ef9641f69afa8c91"}, + {file = "multidict-6.7.0-cp39-cp39-win_amd64.whl", hash = "sha256:7e73299c99939f089dd9b2120a04a516b95cdf8c1cd2b18c53ebf0de80b1f18f"}, + {file = "multidict-6.7.0-cp39-cp39-win_arm64.whl", hash = "sha256:6bdce131e14b04fd34a809b6380dbfd826065c3e2fe8a50dbae659fa0c390546"}, + {file = "multidict-6.7.0-py3-none-any.whl", hash = "sha256:394fc5c42a333c9ffc3e421a4c85e08580d990e08b99f6bf35b4132114c5dcb3"}, + {file = "multidict-6.7.0.tar.gz", hash = "sha256:c6e99d9a65ca282e578dfea819cfa9c0a62b2499d8677392e09feaf305e9e6f5"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.1.0", markers = "python_version < \"3.11\""} + +[[package]] +name = "nodeenv" +version = "1.9.1" +description = "Node.js virtual environment builder" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["dev"] +files = [ + {file = "nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9"}, + {file = "nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f"}, +] + +[[package]] +name = "openmeter" +version = "0.0.0" +description = "Client for OpenMeter: Real-Time and Scalable Usage Metering" +optional = false +python-versions = "^3.9" +groups = ["main"] +files = [] +develop = true + +[package.dependencies] +cloudevents = "^1.10.0" +corehttp = {version = ">=1.0.0b6", extras = ["aiohttp", "requests"]} +isodate = ">=0.6.1,<0.8.0" +typing-extensions = ">=4.6.0" +urllib3 = "^2.0.0" + +[package.source] +type = "directory" +url = ".." + +[[package]] +name = "packaging" +version = "25.0" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484"}, + {file = "packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f"}, +] + +[[package]] +name = "propcache" +version = "0.4.1" +description = "Accelerated property cache" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "propcache-0.4.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7c2d1fa3201efaf55d730400d945b5b3ab6e672e100ba0f9a409d950ab25d7db"}, + {file = "propcache-0.4.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1eb2994229cc8ce7fe9b3db88f5465f5fd8651672840b2e426b88cdb1a30aac8"}, + {file = "propcache-0.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:66c1f011f45a3b33d7bcb22daed4b29c0c9e2224758b6be00686731e1b46f925"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9a52009f2adffe195d0b605c25ec929d26b36ef986ba85244891dee3b294df21"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5d4e2366a9c7b837555cf02fb9be2e3167d333aff716332ef1b7c3a142ec40c5"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9d2b6caef873b4f09e26ea7e33d65f42b944837563a47a94719cc3544319a0db"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2b16ec437a8c8a965ecf95739448dd938b5c7f56e67ea009f4300d8df05f32b7"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:296f4c8ed03ca7476813fe666c9ea97869a8d7aec972618671b33a38a5182ef4"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:1f0978529a418ebd1f49dad413a2b68af33f85d5c5ca5c6ca2a3bed375a7ac60"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:fd138803047fb4c062b1c1dd95462f5209456bfab55c734458f15d11da288f8f"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:8c9b3cbe4584636d72ff556d9036e0c9317fa27b3ac1f0f558e7e84d1c9c5900"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:f93243fdc5657247533273ac4f86ae106cc6445a0efacb9a1bfe982fcfefd90c"}, + {file = "propcache-0.4.1-cp310-cp310-win32.whl", hash = "sha256:a0ee98db9c5f80785b266eb805016e36058ac72c51a064040f2bc43b61101cdb"}, + {file = "propcache-0.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:1cdb7988c4e5ac7f6d175a28a9aa0c94cb6f2ebe52756a3c0cda98d2809a9e37"}, + {file = "propcache-0.4.1-cp310-cp310-win_arm64.whl", hash = "sha256:d82ad62b19645419fe79dd63b3f9253e15b30e955c0170e5cebc350c1844e581"}, + {file = "propcache-0.4.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:60a8fda9644b7dfd5dece8c61d8a85e271cb958075bfc4e01083c148b61a7caf"}, + {file = "propcache-0.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c30b53e7e6bda1d547cabb47c825f3843a0a1a42b0496087bb58d8fedf9f41b5"}, + {file = "propcache-0.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6918ecbd897443087a3b7cd978d56546a812517dcaaca51b49526720571fa93e"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3d902a36df4e5989763425a8ab9e98cd8ad5c52c823b34ee7ef307fd50582566"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a9695397f85973bb40427dedddf70d8dc4a44b22f1650dd4af9eedf443d45165"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2bb07ffd7eaad486576430c89f9b215f9e4be68c4866a96e97db9e97fead85dc"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fd6f30fdcf9ae2a70abd34da54f18da086160e4d7d9251f81f3da0ff84fc5a48"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fc38cba02d1acba4e2869eef1a57a43dfbd3d49a59bf90dda7444ec2be6a5570"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:67fad6162281e80e882fb3ec355398cf72864a54069d060321f6cd0ade95fe85"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f10207adf04d08bec185bae14d9606a1444715bc99180f9331c9c02093e1959e"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:e9b0d8d0845bbc4cfcdcbcdbf5086886bc8157aa963c31c777ceff7846c77757"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:981333cb2f4c1896a12f4ab92a9cc8f09ea664e9b7dbdc4eff74627af3a11c0f"}, + {file = "propcache-0.4.1-cp311-cp311-win32.whl", hash = "sha256:f1d2f90aeec838a52f1c1a32fe9a619fefd5e411721a9117fbf82aea638fe8a1"}, + {file = "propcache-0.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:364426a62660f3f699949ac8c621aad6977be7126c5807ce48c0aeb8e7333ea6"}, + {file = "propcache-0.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:e53f3a38d3510c11953f3e6a33f205c6d1b001129f972805ca9b42fc308bc239"}, + {file = "propcache-0.4.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e153e9cd40cc8945138822807139367f256f89c6810c2634a4f6902b52d3b4e2"}, + {file = "propcache-0.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cd547953428f7abb73c5ad82cbb32109566204260d98e41e5dfdc682eb7f8403"}, + {file = "propcache-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f048da1b4f243fc44f205dfd320933a951b8d89e0afd4c7cacc762a8b9165207"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ec17c65562a827bba85e3872ead335f95405ea1674860d96483a02f5c698fa72"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:405aac25c6394ef275dee4c709be43745d36674b223ba4eb7144bf4d691b7367"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0013cb6f8dde4b2a2f66903b8ba740bdfe378c943c4377a200551ceb27f379e4"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15932ab57837c3368b024473a525e25d316d8353016e7cc0e5ba9eb343fbb1cf"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:031dce78b9dc099f4c29785d9cf5577a3faf9ebf74ecbd3c856a7b92768c3df3"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:ab08df6c9a035bee56e31af99be621526bd237bea9f32def431c656b29e41778"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4d7af63f9f93fe593afbf104c21b3b15868efb2c21d07d8732c0c4287e66b6a6"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:cfc27c945f422e8b5071b6e93169679e4eb5bf73bbcbf1ba3ae3a83d2f78ebd9"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:35c3277624a080cc6ec6f847cbbbb5b49affa3598c4535a0a4682a697aaa5c75"}, + {file = "propcache-0.4.1-cp312-cp312-win32.whl", hash = "sha256:671538c2262dadb5ba6395e26c1731e1d52534bfe9ae56d0b5573ce539266aa8"}, + {file = "propcache-0.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:cb2d222e72399fcf5890d1d5cc1060857b9b236adff2792ff48ca2dfd46c81db"}, + {file = "propcache-0.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:204483131fb222bdaaeeea9f9e6c6ed0cac32731f75dfc1d4a567fc1926477c1"}, + {file = "propcache-0.4.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:43eedf29202c08550aac1d14e0ee619b0430aaef78f85864c1a892294fbc28cf"}, + {file = "propcache-0.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d62cdfcfd89ccb8de04e0eda998535c406bf5e060ffd56be6c586cbcc05b3311"}, + {file = "propcache-0.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cae65ad55793da34db5f54e4029b89d3b9b9490d8abe1b4c7ab5d4b8ec7ebf74"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:333ddb9031d2704a301ee3e506dc46b1fe5f294ec198ed6435ad5b6a085facfe"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:fd0858c20f078a32cf55f7e81473d96dcf3b93fd2ccdb3d40fdf54b8573df3af"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:678ae89ebc632c5c204c794f8dab2837c5f159aeb59e6ed0539500400577298c"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d472aeb4fbf9865e0c6d622d7f4d54a4e101a89715d8904282bb5f9a2f476c3f"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d3df5fa7e36b3225954fba85589da77a0fe6a53e3976de39caf04a0db4c36f1"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:ee17f18d2498f2673e432faaa71698032b0127ebf23ae5974eeaf806c279df24"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:580e97762b950f993ae618e167e7be9256b8353c2dcd8b99ec100eb50f5286aa"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:501d20b891688eb8e7aa903021f0b72d5a55db40ffaab27edefd1027caaafa61"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9a0bd56e5b100aef69bd8562b74b46254e7c8812918d3baa700c8a8009b0af66"}, + {file = "propcache-0.4.1-cp313-cp313-win32.whl", hash = "sha256:bcc9aaa5d80322bc2fb24bb7accb4a30f81e90ab8d6ba187aec0744bc302ad81"}, + {file = "propcache-0.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:381914df18634f5494334d201e98245c0596067504b9372d8cf93f4bb23e025e"}, + {file = "propcache-0.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:8873eb4460fd55333ea49b7d189749ecf6e55bf85080f11b1c4530ed3034cba1"}, + {file = "propcache-0.4.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:92d1935ee1f8d7442da9c0c4fa7ac20d07e94064184811b685f5c4fada64553b"}, + {file = "propcache-0.4.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:473c61b39e1460d386479b9b2f337da492042447c9b685f28be4f74d3529e566"}, + {file = "propcache-0.4.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c0ef0aaafc66fbd87842a3fe3902fd889825646bc21149eafe47be6072725835"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f95393b4d66bfae908c3ca8d169d5f79cd65636ae15b5e7a4f6e67af675adb0e"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c07fda85708bc48578467e85099645167a955ba093be0a2dcba962195676e859"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:af223b406d6d000830c6f65f1e6431783fc3f713ba3e6cc8c024d5ee96170a4b"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a78372c932c90ee474559c5ddfffd718238e8673c340dc21fe45c5b8b54559a0"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:564d9f0d4d9509e1a870c920a89b2fec951b44bf5ba7d537a9e7c1ccec2c18af"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:17612831fda0138059cc5546f4d12a2aacfb9e47068c06af35c400ba58ba7393"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:41a89040cb10bd345b3c1a873b2bf36413d48da1def52f268a055f7398514874"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:e35b88984e7fa64aacecea39236cee32dd9bd8c55f57ba8a75cf2399553f9bd7"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6f8b465489f927b0df505cbe26ffbeed4d6d8a2bbc61ce90eb074ff129ef0ab1"}, + {file = "propcache-0.4.1-cp313-cp313t-win32.whl", hash = "sha256:2ad890caa1d928c7c2965b48f3a3815c853180831d0e5503d35cf00c472f4717"}, + {file = "propcache-0.4.1-cp313-cp313t-win_amd64.whl", hash = "sha256:f7ee0e597f495cf415bcbd3da3caa3bd7e816b74d0d52b8145954c5e6fd3ff37"}, + {file = "propcache-0.4.1-cp313-cp313t-win_arm64.whl", hash = "sha256:929d7cbe1f01bb7baffb33dc14eb5691c95831450a26354cd210a8155170c93a"}, + {file = "propcache-0.4.1-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3f7124c9d820ba5548d431afb4632301acf965db49e666aa21c305cbe8c6de12"}, + {file = "propcache-0.4.1-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:c0d4b719b7da33599dfe3b22d3db1ef789210a0597bc650b7cee9c77c2be8c5c"}, + {file = "propcache-0.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:9f302f4783709a78240ebc311b793f123328716a60911d667e0c036bc5dcbded"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c80ee5802e3fb9ea37938e7eecc307fb984837091d5fd262bb37238b1ae97641"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ed5a841e8bb29a55fb8159ed526b26adc5bdd7e8bd7bf793ce647cb08656cdf4"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:55c72fd6ea2da4c318e74ffdf93c4fe4e926051133657459131a95c846d16d44"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8326e144341460402713f91df60ade3c999d601e7eb5ff8f6f7862d54de0610d"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:060b16ae65bc098da7f6d25bf359f1f31f688384858204fe5d652979e0015e5b"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:89eb3fa9524f7bec9de6e83cf3faed9d79bffa560672c118a96a171a6f55831e"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:dee69d7015dc235f526fe80a9c90d65eb0039103fe565776250881731f06349f"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:5558992a00dfd54ccbc64a32726a3357ec93825a418a401f5cc67df0ac5d9e49"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c9b822a577f560fbd9554812526831712c1436d2c046cedee4c3796d3543b144"}, + {file = "propcache-0.4.1-cp314-cp314-win32.whl", hash = "sha256:ab4c29b49d560fe48b696cdcb127dd36e0bc2472548f3bf56cc5cb3da2b2984f"}, + {file = "propcache-0.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:5a103c3eb905fcea0ab98be99c3a9a5ab2de60228aa5aceedc614c0281cf6153"}, + {file = "propcache-0.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:74c1fb26515153e482e00177a1ad654721bf9207da8a494a0c05e797ad27b992"}, + {file = "propcache-0.4.1-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:824e908bce90fb2743bd6b59db36eb4f45cd350a39637c9f73b1c1ea66f5b75f"}, + {file = "propcache-0.4.1-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:c2b5e7db5328427c57c8e8831abda175421b709672f6cfc3d630c3b7e2146393"}, + {file = "propcache-0.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6f6ff873ed40292cd4969ef5310179afd5db59fdf055897e282485043fc80ad0"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49a2dc67c154db2c1463013594c458881a069fcf98940e61a0569016a583020a"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:005f08e6a0529984491e37d8dbc3dd86f84bd78a8ceb5fa9a021f4c48d4984be"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5c3310452e0d31390da9035c348633b43d7e7feb2e37be252be6da45abd1abcc"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c3c70630930447f9ef1caac7728c8ad1c56bc5015338b20fed0d08ea2480b3a"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8e57061305815dfc910a3634dcf584f08168a8836e6999983569f51a8544cd89"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:521a463429ef54143092c11a77e04056dd00636f72e8c45b70aaa3140d639726"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:120c964da3fdc75e3731aa392527136d4ad35868cc556fd09bb6d09172d9a367"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:d8f353eb14ee3441ee844ade4277d560cdd68288838673273b978e3d6d2c8f36"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ab2943be7c652f09638800905ee1bab2c544e537edb57d527997a24c13dc1455"}, + {file = "propcache-0.4.1-cp314-cp314t-win32.whl", hash = "sha256:05674a162469f31358c30bcaa8883cb7829fa3110bf9c0991fe27d7896c42d85"}, + {file = "propcache-0.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:990f6b3e2a27d683cb7602ed6c86f15ee6b43b1194736f9baaeb93d0016633b1"}, + {file = "propcache-0.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ecef2343af4cc68e05131e45024ba34f6095821988a9d0a02aa7c73fcc448aa9"}, + {file = "propcache-0.4.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:3d233076ccf9e450c8b3bc6720af226b898ef5d051a2d145f7d765e6e9f9bcff"}, + {file = "propcache-0.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:357f5bb5c377a82e105e44bd3d52ba22b616f7b9773714bff93573988ef0a5fb"}, + {file = "propcache-0.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:cbc3b6dfc728105b2a57c06791eb07a94229202ea75c59db644d7d496b698cac"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:182b51b421f0501952d938dc0b0eb45246a5b5153c50d42b495ad5fb7517c888"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4b536b39c5199b96fc6245eb5fb796c497381d3942f169e44e8e392b29c9ebcc"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:db65d2af507bbfbdcedb254a11149f894169d90488dd3e7190f7cdcb2d6cd57a"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fd2dbc472da1f772a4dae4fa24be938a6c544671a912e30529984dd80400cd88"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:daede9cd44e0f8bdd9e6cc9a607fc81feb80fae7a5fc6cecaff0e0bb32e42d00"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:71b749281b816793678ae7f3d0d84bd36e694953822eaad408d682efc5ca18e0"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:0002004213ee1f36cfb3f9a42b5066100c44276b9b72b4e1504cddd3d692e86e"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:fe49d0a85038f36ba9e3ffafa1103e61170b28e95b16622e11be0a0ea07c6781"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:99d43339c83aaf4d32bda60928231848eee470c6bda8d02599cc4cebe872d183"}, + {file = "propcache-0.4.1-cp39-cp39-win32.whl", hash = "sha256:a129e76735bc792794d5177069691c3217898b9f5cee2b2661471e52ffe13f19"}, + {file = "propcache-0.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:948dab269721ae9a87fd16c514a0a2c2a1bdb23a9a61b969b0f9d9ee2968546f"}, + {file = "propcache-0.4.1-cp39-cp39-win_arm64.whl", hash = "sha256:5fd37c406dd6dc85aa743e214cef35dc54bbdd1419baac4f6ae5e5b1a2976938"}, + {file = "propcache-0.4.1-py3-none-any.whl", hash = "sha256:af2a6052aeb6cf17d3e46ee169099044fd8224cbaf75c76a2ef596e8163e2237"}, + {file = "propcache-0.4.1.tar.gz", hash = "sha256:f48107a8c637e80362555f37ecf49abe20370e557cc4ab374f04ec4423c97c3d"}, +] + +[[package]] +name = "pyright" +version = "1.1.407" +description = "Command line wrapper for pyright" +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "pyright-1.1.407-py3-none-any.whl", hash = "sha256:6dd419f54fcc13f03b52285796d65e639786373f433e243f8b94cf93a7444d21"}, + {file = "pyright-1.1.407.tar.gz", hash = "sha256:099674dba5c10489832d4a4b2d302636152a9a42d317986c38474c76fe562262"}, +] + +[package.dependencies] +nodeenv = ">=1.6.0" +typing-extensions = ">=4.1" + +[package.extras] +all = ["nodejs-wheel-binaries", "twine (>=3.4.1)"] +dev = ["twine (>=3.4.1)"] +nodejs = ["nodejs-wheel-binaries"] + +[[package]] +name = "requests" +version = "2.32.5" +description = "Python HTTP for Humans." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6"}, + {file = "requests-2.32.5.tar.gz", hash = "sha256:dbba0bac56e100853db0ea71b82b4dfd5fe2bf6d3754a8893c3af500cec7d7cf"}, +] + +[package.dependencies] +certifi = ">=2017.4.17" +charset_normalizer = ">=2,<4" +idna = ">=2.5,<4" +urllib3 = ">=1.21.1,<3" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] + +[[package]] +name = "typing-extensions" +version = "4.15.0" +description = "Backported and Experimental Type Hints for Python 3.9+" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548"}, + {file = "typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466"}, +] + +[[package]] +name = "urllib3" +version = "2.6.3" +description = "HTTP library with thread-safe connection pooling, file post, and more." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4"}, + {file = "urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed"}, +] + +[package.extras] +brotli = ["brotli (>=1.2.0) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=1.2.0.0) ; platform_python_implementation != \"CPython\""] +h2 = ["h2 (>=4,<5)"] +socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] +zstd = ["backports-zstd (>=1.0.0) ; python_version < \"3.14\""] + +[[package]] +name = "yarl" +version = "1.22.0" +description = "Yet another URL library" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "yarl-1.22.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c7bd6683587567e5a49ee6e336e0612bec8329be1b7d4c8af5687dcdeb67ee1e"}, + {file = "yarl-1.22.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:5cdac20da754f3a723cceea5b3448e1a2074866406adeb4ef35b469d089adb8f"}, + {file = "yarl-1.22.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:07a524d84df0c10f41e3ee918846e1974aba4ec017f990dc735aad487a0bdfdf"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e1b329cb8146d7b736677a2440e422eadd775d1806a81db2d4cded80a48efc1a"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:75976c6945d85dbb9ee6308cd7ff7b1fb9409380c82d6119bd778d8fcfe2931c"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:80ddf7a5f8c86cb3eb4bc9028b07bbbf1f08a96c5c0bc1244be5e8fefcb94147"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d332fc2e3c94dad927f2112395772a4e4fedbcf8f80efc21ed7cdfae4d574fdb"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0cf71bf877efeac18b38d3930594c0948c82b64547c1cf420ba48722fe5509f6"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:663e1cadaddae26be034a6ab6072449a8426ddb03d500f43daf952b74553bba0"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:6dcbb0829c671f305be48a7227918cfcd11276c2d637a8033a99a02b67bf9eda"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:f0d97c18dfd9a9af4490631905a3f131a8e4c9e80a39353919e2cfed8f00aedc"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:437840083abe022c978470b942ff832c3940b2ad3734d424b7eaffcd07f76737"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:a899cbd98dce6f5d8de1aad31cb712ec0a530abc0a86bd6edaa47c1090138467"}, + {file = "yarl-1.22.0-cp310-cp310-win32.whl", hash = "sha256:595697f68bd1f0c1c159fcb97b661fc9c3f5db46498043555d04805430e79bea"}, + {file = "yarl-1.22.0-cp310-cp310-win_amd64.whl", hash = "sha256:cb95a9b1adaa48e41815a55ae740cfda005758104049a640a398120bf02515ca"}, + {file = "yarl-1.22.0-cp310-cp310-win_arm64.whl", hash = "sha256:b85b982afde6df99ecc996990d4ad7ccbdbb70e2a4ba4de0aecde5922ba98a0b"}, + {file = "yarl-1.22.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1ab72135b1f2db3fed3997d7e7dc1b80573c67138023852b6efb336a5eae6511"}, + {file = "yarl-1.22.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:669930400e375570189492dc8d8341301578e8493aec04aebc20d4717f899dd6"}, + {file = "yarl-1.22.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:792a2af6d58177ef7c19cbf0097aba92ca1b9cb3ffdd9c7470e156c8f9b5e028"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ea66b1c11c9150f1372f69afb6b8116f2dd7286f38e14ea71a44eee9ec51b9d"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3e2daa88dc91870215961e96a039ec73e4937da13cf77ce17f9cad0c18df3503"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ba440ae430c00eee41509353628600212112cd5018d5def7e9b05ea7ac34eb65"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e6438cc8f23a9c1478633d216b16104a586b9761db62bfacb6425bac0a36679e"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c52a6e78aef5cf47a98ef8e934755abf53953379b7d53e68b15ff4420e6683d"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:3b06bcadaac49c70f4c88af4ffcfbe3dc155aab3163e75777818092478bcbbe7"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:6944b2dc72c4d7f7052683487e3677456050ff77fcf5e6204e98caf785ad1967"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d5372ca1df0f91a86b047d1277c2aaf1edb32d78bbcefffc81b40ffd18f027ed"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:51af598701f5299012b8416486b40fceef8c26fc87dc6d7d1f6fc30609ea0aa6"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b266bd01fedeffeeac01a79ae181719ff848a5a13ce10075adbefc8f1daee70e"}, + {file = "yarl-1.22.0-cp311-cp311-win32.whl", hash = "sha256:a9b1ba5610a4e20f655258d5a1fdc7ebe3d837bb0e45b581398b99eb98b1f5ca"}, + {file = "yarl-1.22.0-cp311-cp311-win_amd64.whl", hash = "sha256:078278b9b0b11568937d9509b589ee83ef98ed6d561dfe2020e24a9fd08eaa2b"}, + {file = "yarl-1.22.0-cp311-cp311-win_arm64.whl", hash = "sha256:b6a6f620cfe13ccec221fa312139135166e47ae169f8253f72a0abc0dae94376"}, + {file = "yarl-1.22.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e340382d1afa5d32b892b3ff062436d592ec3d692aeea3bef3a5cfe11bbf8c6f"}, + {file = "yarl-1.22.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f1e09112a2c31ffe8d80be1b0988fa6a18c5d5cad92a9ffbb1c04c91bfe52ad2"}, + {file = "yarl-1.22.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:939fe60db294c786f6b7c2d2e121576628468f65453d86b0fe36cb52f987bd74"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e1651bf8e0398574646744c1885a41198eba53dc8a9312b954073f845c90a8df"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b8a0588521a26bf92a57a1705b77b8b59044cdceccac7151bd8d229e66b8dedb"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:42188e6a615c1a75bcaa6e150c3fe8f3e8680471a6b10150c5f7e83f47cc34d2"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f6d2cb59377d99718913ad9a151030d6f83ef420a2b8f521d94609ecc106ee82"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50678a3b71c751d58d7908edc96d332af328839eea883bb554a43f539101277a"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1e8fbaa7cec507aa24ea27a01456e8dd4b6fab829059b69844bd348f2d467124"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:433885ab5431bc3d3d4f2f9bd15bfa1614c522b0f1405d62c4f926ccd69d04fa"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b790b39c7e9a4192dc2e201a282109ed2985a1ddbd5ac08dc56d0e121400a8f7"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:31f0b53913220599446872d757257be5898019c85e7971599065bc55065dc99d"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a49370e8f711daec68d09b821a34e1167792ee2d24d405cbc2387be4f158b520"}, + {file = "yarl-1.22.0-cp312-cp312-win32.whl", hash = "sha256:70dfd4f241c04bd9239d53b17f11e6ab672b9f1420364af63e8531198e3f5fe8"}, + {file = "yarl-1.22.0-cp312-cp312-win_amd64.whl", hash = "sha256:8884d8b332a5e9b88e23f60bb166890009429391864c685e17bd73a9eda9105c"}, + {file = "yarl-1.22.0-cp312-cp312-win_arm64.whl", hash = "sha256:ea70f61a47f3cc93bdf8b2f368ed359ef02a01ca6393916bc8ff877427181e74"}, + {file = "yarl-1.22.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8dee9c25c74997f6a750cd317b8ca63545169c098faee42c84aa5e506c819b53"}, + {file = "yarl-1.22.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:01e73b85a5434f89fc4fe27dcda2aff08ddf35e4d47bbbea3bdcd25321af538a"}, + {file = "yarl-1.22.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:22965c2af250d20c873cdbee8ff958fb809940aeb2e74ba5f20aaf6b7ac8c70c"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4f15793aa49793ec8d1c708ab7f9eded1aa72edc5174cae703651555ed1b601"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e5542339dcf2747135c5c85f68680353d5cb9ffd741c0f2e8d832d054d41f35a"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5c401e05ad47a75869c3ab3e35137f8468b846770587e70d71e11de797d113df"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:243dda95d901c733f5b59214d28b0120893d91777cb8aa043e6ef059d3cddfe2"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bec03d0d388060058f5d291a813f21c011041938a441c593374da6077fe21b1b"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b0748275abb8c1e1e09301ee3cf90c8a99678a4e92e4373705f2a2570d581273"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:47fdb18187e2a4e18fda2c25c05d8251a9e4a521edaed757fef033e7d8498d9a"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c7044802eec4524fde550afc28edda0dd5784c4c45f0be151a2d3ba017daca7d"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:139718f35149ff544caba20fce6e8a2f71f1e39b92c700d8438a0b1d2a631a02"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e1b51bebd221006d3d2f95fbe124b22b247136647ae5dcc8c7acafba66e5ee67"}, + {file = "yarl-1.22.0-cp313-cp313-win32.whl", hash = "sha256:d3e32536234a95f513bd374e93d717cf6b2231a791758de6c509e3653f234c95"}, + {file = "yarl-1.22.0-cp313-cp313-win_amd64.whl", hash = "sha256:47743b82b76d89a1d20b83e60d5c20314cbd5ba2befc9cda8f28300c4a08ed4d"}, + {file = "yarl-1.22.0-cp313-cp313-win_arm64.whl", hash = "sha256:5d0fcda9608875f7d052eff120c7a5da474a6796fe4d83e152e0e4d42f6d1a9b"}, + {file = "yarl-1.22.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:719ae08b6972befcba4310e49edb1161a88cdd331e3a694b84466bd938a6ab10"}, + {file = "yarl-1.22.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:47d8a5c446df1c4db9d21b49619ffdba90e77c89ec6e283f453856c74b50b9e3"}, + {file = "yarl-1.22.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:cfebc0ac8333520d2d0423cbbe43ae43c8838862ddb898f5ca68565e395516e9"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4398557cbf484207df000309235979c79c4356518fd5c99158c7d38203c4da4f"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2ca6fd72a8cd803be290d42f2dec5cdcd5299eeb93c2d929bf060ad9efaf5de0"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ca1f59c4e1ab6e72f0a23c13fca5430f889634166be85dbf1013683e49e3278e"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6c5010a52015e7c70f86eb967db0f37f3c8bd503a695a49f8d45700144667708"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d7672ecf7557476642c88497c2f8d8542f8e36596e928e9bcba0e42e1e7d71f"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:3b7c88eeef021579d600e50363e0b6ee4f7f6f728cd3486b9d0f3ee7b946398d"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f4afb5c34f2c6fecdcc182dfcfc6af6cccf1aa923eed4d6a12e9d96904e1a0d8"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:59c189e3e99a59cf8d83cbb31d4db02d66cda5a1a4374e8a012b51255341abf5"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:5a3bf7f62a289fa90f1990422dc8dff5a458469ea71d1624585ec3a4c8d6960f"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:de6b9a04c606978fdfe72666fa216ffcf2d1a9f6a381058d4378f8d7b1e5de62"}, + {file = "yarl-1.22.0-cp313-cp313t-win32.whl", hash = "sha256:1834bb90991cc2999f10f97f5f01317f99b143284766d197e43cd5b45eb18d03"}, + {file = "yarl-1.22.0-cp313-cp313t-win_amd64.whl", hash = "sha256:ff86011bd159a9d2dfc89c34cfd8aff12875980e3bd6a39ff097887520e60249"}, + {file = "yarl-1.22.0-cp313-cp313t-win_arm64.whl", hash = "sha256:7861058d0582b847bc4e3a4a4c46828a410bca738673f35a29ba3ca5db0b473b"}, + {file = "yarl-1.22.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:34b36c2c57124530884d89d50ed2c1478697ad7473efd59cfd479945c95650e4"}, + {file = "yarl-1.22.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:0dd9a702591ca2e543631c2a017e4a547e38a5c0f29eece37d9097e04a7ac683"}, + {file = "yarl-1.22.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:594fcab1032e2d2cc3321bb2e51271e7cd2b516c7d9aee780ece81b07ff8244b"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f3d7a87a78d46a2e3d5b72587ac14b4c16952dd0887dbb051451eceac774411e"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:852863707010316c973162e703bddabec35e8757e67fcb8ad58829de1ebc8590"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:131a085a53bfe839a477c0845acf21efc77457ba2bcf5899618136d64f3303a2"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:078a8aefd263f4d4f923a9677b942b445a2be970ca24548a8102689a3a8ab8da"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bca03b91c323036913993ff5c738d0842fc9c60c4648e5c8d98331526df89784"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:68986a61557d37bb90d3051a45b91fa3d5c516d177dfc6dd6f2f436a07ff2b6b"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:4792b262d585ff0dff6bcb787f8492e40698443ec982a3568c2096433660c694"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:ebd4549b108d732dba1d4ace67614b9545b21ece30937a63a65dd34efa19732d"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f87ac53513d22240c7d59203f25cc3beac1e574c6cd681bbfd321987b69f95fd"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:22b029f2881599e2f1b06f8f1db2ee63bd309e2293ba2d566e008ba12778b8da"}, + {file = "yarl-1.22.0-cp314-cp314-win32.whl", hash = "sha256:6a635ea45ba4ea8238463b4f7d0e721bad669f80878b7bfd1f89266e2ae63da2"}, + {file = "yarl-1.22.0-cp314-cp314-win_amd64.whl", hash = "sha256:0d6e6885777af0f110b0e5d7e5dda8b704efed3894da26220b7f3d887b839a79"}, + {file = "yarl-1.22.0-cp314-cp314-win_arm64.whl", hash = "sha256:8218f4e98d3c10d683584cb40f0424f4b9fd6e95610232dd75e13743b070ee33"}, + {file = "yarl-1.22.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:45c2842ff0e0d1b35a6bf1cd6c690939dacb617a70827f715232b2e0494d55d1"}, + {file = "yarl-1.22.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:d947071e6ebcf2e2bee8fce76e10faca8f7a14808ca36a910263acaacef08eca"}, + {file = "yarl-1.22.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:334b8721303e61b00019474cc103bdac3d7b1f65e91f0bfedeec2d56dfe74b53"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e7ce67c34138a058fd092f67d07a72b8e31ff0c9236e751957465a24b28910c"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d77e1b2c6d04711478cb1c4ab90db07f1609ccf06a287d5607fcd90dc9863acf"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4647674b6150d2cae088fc07de2738a84b8bcedebef29802cf0b0a82ab6face"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efb07073be061c8f79d03d04139a80ba33cbd390ca8f0297aae9cce6411e4c6b"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e51ac5435758ba97ad69617e13233da53908beccc6cfcd6c34bbed8dcbede486"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:33e32a0dd0c8205efa8e83d04fc9f19313772b78522d1bdc7d9aed706bfd6138"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:bf4a21e58b9cde0e401e683ebd00f6ed30a06d14e93f7c8fd059f8b6e8f87b6a"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:e4b582bab49ac33c8deb97e058cd67c2c50dac0dd134874106d9c774fd272529"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:0b5bcc1a9c4839e7e30b7b30dd47fe5e7e44fb7054ec29b5bb8d526aa1041093"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c0232bce2170103ec23c454e54a57008a9a72b5d1c3105dc2496750da8cfa47c"}, + {file = "yarl-1.22.0-cp314-cp314t-win32.whl", hash = "sha256:8009b3173bcd637be650922ac455946197d858b3630b6d8787aa9e5c4564533e"}, + {file = "yarl-1.22.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9fb17ea16e972c63d25d4a97f016d235c78dd2344820eb35bc034bc32012ee27"}, + {file = "yarl-1.22.0-cp314-cp314t-win_arm64.whl", hash = "sha256:9f6d73c1436b934e3f01df1e1b21ff765cd1d28c77dfb9ace207f746d4610ee1"}, + {file = "yarl-1.22.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:3aa27acb6de7a23785d81557577491f6c38a5209a254d1191519d07d8fe51748"}, + {file = "yarl-1.22.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:af74f05666a5e531289cb1cc9c883d1de2088b8e5b4de48004e5ca8a830ac859"}, + {file = "yarl-1.22.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:62441e55958977b8167b2709c164c91a6363e25da322d87ae6dd9c6019ceecf9"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b580e71cac3f8113d3135888770903eaf2f507e9421e5697d6ee6d8cd1c7f054"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e81fda2fb4a07eda1a2252b216aa0df23ebcd4d584894e9612e80999a78fd95b"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:99b6fc1d55782461b78221e95fc357b47ad98b041e8e20f47c1411d0aacddc60"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:088e4e08f033db4be2ccd1f34cf29fe994772fb54cfe004bbf54db320af56890"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e4e1f6f0b4da23e61188676e3ed027ef0baa833a2e633c29ff8530800edccba"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:84fc3ec96fce86ce5aa305eb4aa9358279d1aa644b71fab7b8ed33fe3ba1a7ca"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:5dbeefd6ca588b33576a01b0ad58aa934bc1b41ef89dee505bf2932b22ddffba"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:14291620375b1060613f4aab9ebf21850058b6b1b438f386cc814813d901c60b"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:a4fcfc8eb2c34148c118dfa02e6427ca278bfd0f3df7c5f99e33d2c0e81eae3e"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:029866bde8d7b0878b9c160e72305bbf0a7342bcd20b9999381704ae03308dc8"}, + {file = "yarl-1.22.0-cp39-cp39-win32.whl", hash = "sha256:4dcc74149ccc8bba31ce1944acee24813e93cfdee2acda3c172df844948ddf7b"}, + {file = "yarl-1.22.0-cp39-cp39-win_amd64.whl", hash = "sha256:10619d9fdee46d20edc49d3479e2f8269d0779f1b031e6f7c2aa1c76be04b7ed"}, + {file = "yarl-1.22.0-cp39-cp39-win_arm64.whl", hash = "sha256:dd7afd3f8b0bfb4e0d9fc3c31bfe8a4ec7debe124cfd90619305def3c8ca8cd2"}, + {file = "yarl-1.22.0-py3-none-any.whl", hash = "sha256:1380560bdba02b6b6c90de54133c81c9f2a453dee9912fe58c1dcced1edb7cff"}, + {file = "yarl-1.22.0.tar.gz", hash = "sha256:bebf8557577d4401ba8bd9ff33906f1376c877aa78d1fe216ad01b4d6745af71"}, +] + +[package.dependencies] +idna = ">=2.0" +multidict = ">=4.0" +propcache = ">=0.2.1" + +[metadata] +lock-version = "2.1" +python-versions = "^3.9" +content-hash = "b7fda54a5c7fba3a08d2eea0cb439c37c4f05adb72f055f30786c20193b7cba0" diff --git a/api/client/python/examples/pyproject.toml b/api/client/python/examples/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..465e3f02a5bed8ca5c067f1a1cdb3a1dfe393dad --- /dev/null +++ b/api/client/python/examples/pyproject.toml @@ -0,0 +1,16 @@ +[tool.poetry] +name = "openmeter-examples" +version = "0.0.0" +description = "OpenMeter examples" +package-mode = false + +[tool.poetry.dependencies] +python = "^3.9" +openmeter = { path = "..", develop = true } + +[tool.poetry.group.dev.dependencies] +pyright = "^1.1.407" + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" diff --git a/api/client/python/examples/pyrightconfig.json b/api/client/python/examples/pyrightconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..11c92f6c4c176d401273989ec2dc3c1e5dc3c412 --- /dev/null +++ b/api/client/python/examples/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "include": ["async", "sync"], + "typeCheckingMode": "basic" +} diff --git a/api/client/python/examples/sync/customer.py b/api/client/python/examples/sync/customer.py new file mode 100644 index 0000000000000000000000000000000000000000..c77f009a226822982c6dddbd3a70c7f141a0e6fc --- /dev/null +++ b/api/client/python/examples/sync/customer.py @@ -0,0 +1,77 @@ +from os import environ +from typing import Optional + +from openmeter import Client +from openmeter.models import ( + CustomerCreate, + CustomerReplaceUpdate, + CustomerUsageAttribution, + Metadata, +) +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") +customer_key: str = environ.get("OPENMETER_CUSTOMER_KEY") or "acme-corp-1" +subject_key: str = environ.get("OPENMETER_SUBJECT_KEY") or "acme-user-1" + +client = Client( + endpoint=ENDPOINT, + token=token, +) + + +def main() -> None: + try: + # Create a customer + customer_create = CustomerCreate( + name="Acme Corporation", + usage_attribution=CustomerUsageAttribution(subject_keys=[subject_key]), + description="A demo customer for testing", + metadata=Metadata( + { + "industry": "technology", + } + ), + key=customer_key, + primary_email="contact@acme-corp.example.com", + currency="EUR", + ) + + created_customer = client.customers.create(customer_create) + print(f"Customer created successfully with ID: {created_customer.id}") + print(f"Customer name: {created_customer.name}") + print(f"Customer key: {created_customer.key}") + + # Get the customer by ID or key + customer = client.customers.get(created_customer.id) + print(f"\nRetrieved customer: {customer.name}") + print(f"Primary email: {customer.primary_email}") + print(f"Currency: {customer.currency}") + + # Update the customer + customer_update = CustomerReplaceUpdate( + name="Acme Corporation Ltd.", + usage_attribution=CustomerUsageAttribution(subject_keys=[subject_key]), + description="Updated demo customer", + metadata=Metadata( + { + "industry": "technology", + } + ), + key=customer_key, + primary_email="info@acme-corp.example.com", + currency="USD", + ) + + updated_customer = client.customers.update(created_customer.id, customer_update) + print(f"\nCustomer updated successfully") + print(f"Updated name: {updated_customer.name}") + print(f"Updated email: {updated_customer.primary_email}") + print(f"Updated currency: {updated_customer.currency}") + + except HttpResponseError as e: + print(f"Error: {e}") + + +main() diff --git a/api/client/python/examples/sync/entitlement.py b/api/client/python/examples/sync/entitlement.py new file mode 100644 index 0000000000000000000000000000000000000000..e22652b2440887c4473f9aed28857270986cf77b --- /dev/null +++ b/api/client/python/examples/sync/entitlement.py @@ -0,0 +1,86 @@ +from os import environ +from typing import Optional + +from openmeter import Client +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") +customer_key: str = environ.get("OPENMETER_CUSTOMER_KEY") or "acme-corp-1" +feature_key: str = environ.get("OPENMETER_FEATURE_KEY") or "api_access" + +client = Client( + endpoint=ENDPOINT, + token=token, +) + + +def main() -> None: + try: + # Check customer access to a specific feature + print(f"Checking access for customer '{customer_key}' to feature '{feature_key}'...") + + entitlement_value = client.customer_entitlement.get_customer_entitlement_value(customer_key, feature_key) + + print(f"\nEntitlement Value:") + print(f"Has Access: {entitlement_value.has_access}") + + # For metered entitlements, additional properties are available + if entitlement_value.balance is not None: + print(f"Balance: {entitlement_value.balance}") + if entitlement_value.usage is not None: + print(f"Usage: {entitlement_value.usage}") + if entitlement_value.overage is not None: + print(f"Overage: {entitlement_value.overage}") + + # For static entitlements, config is available + if entitlement_value.config is not None: + print(f"Config: {entitlement_value.config}") + + # List customer entitlements and demonstrate type-specific handling + print(f"\nListing all entitlements for customer '{customer_key}'...") + entitlements_response = client.customer_entitlements_v2.list(customer_key) + + print(f"\nEntitlements by Type:") + for entitlement in entitlements_response.items_property: + # Note: Due to a deserialization issue in the SDK, items come back as dicts + # Access fields using dict syntax or .get() + print(f"\n Feature: {entitlement.get('featureKey')}") + print(f" ID: {entitlement.get('id')}") + + # Handle different entitlement types using discriminator + entitlement_type = entitlement.get("type") + if entitlement_type == "metered": + # Metered entitlement + print(f" Type: Metered") + print(f" Soft Limit: {entitlement.get('isSoftLimit')}") + if entitlement.get("issueAfterReset") is not None: + print(f" Issue After Reset: {entitlement.get('issueAfterReset')}") + elif entitlement_type == "static": + # Static entitlement + print(f" Type: Static") + if entitlement.get("config") is not None: + print(f" Config: {entitlement.get('config')}") + elif entitlement_type == "boolean": + # Boolean entitlement + print(f" Type: Boolean") + + # Get overall customer access to all features + print(f"\nGetting overall access for customer '{customer_key}'...") + customer_access = client.customer.get_customer_access(customer_key) + + print(f"\nCustomer Access Summary:") + print(f"Total entitlements: {len(customer_access.entitlements)}") + for feature, value in customer_access.entitlements.items(): + access_status = "✓" if value.has_access else "✗" + print(f" {access_status} {feature}: has_access={value.has_access}") + if value.balance is not None: + print(f" Balance: {value.balance}") + if value.usage is not None: + print(f" Usage: {value.usage}") + + except HttpResponseError as e: + print(f"Error: {e}") + + +main() diff --git a/api/client/python/examples/sync/ingest.py b/api/client/python/examples/sync/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..f21fe7163aa204cf6175e694060c07ee8238a936 --- /dev/null +++ b/api/client/python/examples/sync/ingest.py @@ -0,0 +1,44 @@ +from os import environ +from typing import Optional +import datetime +import uuid + +from openmeter import Client +from openmeter.models import Event +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") + + +client = Client( + endpoint=ENDPOINT, + token=token, +) + + +def main() -> None: + try: + # Create a CloudEvents event + event = Event( + id=str(uuid.uuid4()), + source="my-app", + specversion="1.0", + type="prompt", + subject="customer-1", + time=datetime.datetime.now(datetime.timezone.utc), + data={ + "tokens": 100, + "model": "gpt-4o", + "type": "input", + }, + ) + + # Ingest the event + client.events.ingest_event(event) + print("Event ingested successfully") + except HttpResponseError as e: + print(f"Error ingesting event: {e}") + + +main() diff --git a/api/client/python/examples/sync/query.py b/api/client/python/examples/sync/query.py new file mode 100644 index 0000000000000000000000000000000000000000..35b665a5146f16201bce11537059be91dac38631 --- /dev/null +++ b/api/client/python/examples/sync/query.py @@ -0,0 +1,48 @@ +from os import environ +from typing import Optional + +from openmeter import Client +from openmeter.models import MeterQueryResult, FilterString +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") + +client = Client( + endpoint=ENDPOINT, + token=token, +) + + +def main() -> None: + try: + # Query total values + r: MeterQueryResult = client.meters.query_json(meter_id_or_slug="tokens_total") + if r.data and len(r.data) > 0: + print("Query total values:", r.data[0].value) + else: + print("Query total values: No data returned") + + # Query total values grouped by language + r = client.meters.query_json( + meter_id_or_slug="tokens_total", + group_by=["model"], + ) + print("Query total values grouped by model:") + for row in r.data: + print("\t", row.group_by["model"], ":", row.value) + + # Query total values for model=gpt-4o + r = client.meters.query_json( + meter_id_or_slug="tokens_total", + advanced_meter_group_by_filters={"model": FilterString(eq="gpt-4o")}, + ) + if r.data and len(r.data) > 0: + print("Query total values for model=gpt-4o:", r.data[0].value) + else: + print("Query total values for model=gpt-4o: No data returned") + except HttpResponseError as e: + print(e) + + +main() diff --git a/api/client/python/examples/sync/subscription.py b/api/client/python/examples/sync/subscription.py new file mode 100644 index 0000000000000000000000000000000000000000..32406a3b6f3e1f1ad00898ae9e6a65b3f653e9e8 --- /dev/null +++ b/api/client/python/examples/sync/subscription.py @@ -0,0 +1,74 @@ +from os import environ +from typing import Optional + +from openmeter import Client +from openmeter.models import ( + Metadata, + PlanSubscriptionCreate, + PlanReferenceInput, + SubscriptionStatus, +) +from corehttp.exceptions import HttpResponseError + +ENDPOINT: str = environ.get("OPENMETER_ENDPOINT") or "https://openmeter.cloud" +token: Optional[str] = environ.get("OPENMETER_TOKEN") +customer_key: str = environ.get("OPENMETER_CUSTOMER_KEY") or "acme-corp-1" +plan_key: str = environ.get("OPENMETER_PLAN_KEY") or "free" + +client = Client( + endpoint=ENDPOINT, + token=token, +) + + +def main() -> None: + try: + # Create a subscription for the customer using the free plan + print(f"Creating subscription for customer '{customer_key}' with plan '{plan_key}'...") + + subscription_create = PlanSubscriptionCreate( + plan=PlanReferenceInput( + key=plan_key, + ), + name="Free Plan Subscription", + description="Subscription to the free plan for Acme Corporation", + customer_key=customer_key, + metadata=Metadata( + { + "source": "example", + "environment": "development", + } + ), + ) + + subscription = client.subscriptions.create(subscription_create) + print(f"Subscription created successfully with ID: {subscription.id}") + print(f"Subscription name: {subscription.name}") + print(f"Subscription status: {subscription.status}") + print(f"Customer ID: {subscription.customer_id}") + print(f"Active from: {subscription.active_from}") + print(f"Active to: {subscription.active_to}") + print(f"Currency: {subscription.currency}") + print(f"Billing cadence: {subscription.billing_cadence}") + + # Retrieve the subscription to verify + retrieved_subscription = client.subscriptions.get_expanded(subscription.id) + print(f"\nRetrieved subscription: {retrieved_subscription.name}") + print(f"Status: {retrieved_subscription.status}") + if retrieved_subscription.plan: + print(f"Plan key: {retrieved_subscription.plan.key}") + print(f"Plan version: {retrieved_subscription.plan.version}") + + # List subscriptions for the customer + print(f"\nListing subscriptions for customer '{customer_key}'...") + subscriptions_response = client.customers.list_customer_subscriptions( + customer_key, status=[SubscriptionStatus.ACTIVE] + ) + for sub in subscriptions_response.items_property: + print(f"\t{sub.name} (ID: {sub.id}, Status: {sub.status})") + + except HttpResponseError as e: + print(f"Error: {e}") + + +main() diff --git a/api/client/python/openmeter/__init__.py b/api/client/python/openmeter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d55ccad1f573f71f48240d0c9f020cd71047c2bc --- /dev/null +++ b/api/client/python/openmeter/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/api/client/python/openmeter/_client.py b/api/client/python/openmeter/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..61f87b21348ce986200a0df7efbce8c902a93586 --- /dev/null +++ b/api/client/python/openmeter/_client.py @@ -0,0 +1,31 @@ +# coding=utf-8 + +from typing import Any, Optional +from typing_extensions import Self + +from corehttp.credentials import ServiceKeyCredential +from corehttp.runtime import policies + +from ._generated._client import OpenMeterClient + + +class Client(OpenMeterClient): + def __init__( + self, + endpoint: str = "https://openmeter.cloud", + token: Optional[str] = None, + **kwargs: Any, + ) -> None: + if token and not kwargs.get("authentication_policy"): + credential = ServiceKeyCredential(token) + kwargs["authentication_policy"] = policies.ServiceKeyCredentialPolicy( + credential, "Authorization", prefix="Bearer" + ) + + super().__init__(endpoint=endpoint, **kwargs) + + def __enter__(self) -> Self: + return super().__enter__() + + def __exit__(self, *exc_details: Any) -> None: + return super().__exit__(*exc_details) diff --git a/api/client/python/openmeter/_commit.py b/api/client/python/openmeter/_commit.py new file mode 100644 index 0000000000000000000000000000000000000000..3e909f82e3582f926aae4686c8a8922a6e04ff96 --- /dev/null +++ b/api/client/python/openmeter/_commit.py @@ -0,0 +1,3 @@ +# coding=utf-8 + +COMMIT = "000000000000" diff --git a/api/client/python/openmeter/_generated/__init__.py b/api/client/python/openmeter/_generated/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8014ba859b60199795e43c75fc556acad66cf02a --- /dev/null +++ b/api/client/python/openmeter/_generated/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import OpenMeterClient # type: ignore +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "OpenMeterClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/api/client/python/openmeter/_generated/_client.py b/api/client/python/openmeter/_generated/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..8891d6b73e3460635a26f4359072c781b24bb731 --- /dev/null +++ b/api/client/python/openmeter/_generated/_client.py @@ -0,0 +1,254 @@ +# coding=utf-8 + +from copy import deepcopy +from typing import Any +from typing_extensions import Self + +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient, policies + +from ._configuration import OpenMeterClientConfiguration +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + AddonsOperations, + AppCustomInvoicingOperations, + AppStripeOperations, + AppsOperations, + BillingProfilesOperations, + CurrenciesOperations, + CustomerAppsOperations, + CustomerEntitlementOperations, + CustomerEntitlementV2Operations, + CustomerEntitlementsV2Operations, + CustomerInvoiceOperations, + CustomerOperations, + CustomerOverridesOperations, + CustomerStripeOperations, + CustomersOperations, + DebugOperations, + EntitlementsOperations, + EntitlementsV2Operations, + EventsOperations, + EventsV2Operations, + FeaturesOperations, + GrantsOperations, + GrantsV2Operations, + InvoiceOperations, + InvoicesOperations, + MarketplaceOperations, + MetersOperations, + NotificationChannelsOperations, + NotificationEventsOperations, + NotificationRulesOperations, + PlanAddonsOperations, + PlansOperations, + PortalOperations, + ProgressOperations, + SubjectsOperations, + SubscriptionAddonsOperations, + SubscriptionsOperations, +) + + +class OpenMeterClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """OpenMeter is a cloud native usage metering service. The OpenMeter API allows you to ingest + events, query meter usage, and manage resources. + + :ivar portal: PortalOperations operations + :vartype portal: openmeter.operations.PortalOperations + :ivar apps: AppsOperations operations + :vartype apps: openmeter.operations.AppsOperations + :ivar app_stripe: AppStripeOperations operations + :vartype app_stripe: openmeter.operations.AppStripeOperations + :ivar customer_apps: CustomerAppsOperations operations + :vartype customer_apps: openmeter.operations.CustomerAppsOperations + :ivar customers: CustomersOperations operations + :vartype customers: openmeter.operations.CustomersOperations + :ivar features: FeaturesOperations operations + :vartype features: openmeter.operations.FeaturesOperations + :ivar plans: PlansOperations operations + :vartype plans: openmeter.operations.PlansOperations + :ivar plan_addons: PlanAddonsOperations operations + :vartype plan_addons: openmeter.operations.PlanAddonsOperations + :ivar addons: AddonsOperations operations + :vartype addons: openmeter.operations.AddonsOperations + :ivar subscriptions: SubscriptionsOperations operations + :vartype subscriptions: openmeter.operations.SubscriptionsOperations + :ivar subscription_addons: SubscriptionAddonsOperations operations + :vartype subscription_addons: openmeter.operations.SubscriptionAddonsOperations + :ivar entitlements: EntitlementsOperations operations + :vartype entitlements: openmeter.operations.EntitlementsOperations + :ivar grants: GrantsOperations operations + :vartype grants: openmeter.operations.GrantsOperations + :ivar subjects: SubjectsOperations operations + :vartype subjects: openmeter.operations.SubjectsOperations + :ivar customer: CustomerOperations operations + :vartype customer: openmeter.operations.CustomerOperations + :ivar customer_entitlement: CustomerEntitlementOperations operations + :vartype customer_entitlement: openmeter.operations.CustomerEntitlementOperations + :ivar customer_stripe: CustomerStripeOperations operations + :vartype customer_stripe: openmeter.operations.CustomerStripeOperations + :ivar marketplace: MarketplaceOperations operations + :vartype marketplace: openmeter.operations.MarketplaceOperations + :ivar app_custom_invoicing: AppCustomInvoicingOperations operations + :vartype app_custom_invoicing: openmeter.operations.AppCustomInvoicingOperations + :ivar events: EventsOperations operations + :vartype events: openmeter.operations.EventsOperations + :ivar events_v2: EventsV2Operations operations + :vartype events_v2: openmeter.operations.EventsV2Operations + :ivar meters: MetersOperations operations + :vartype meters: openmeter.operations.MetersOperations + :ivar subjects: SubjectsOperations operations + :vartype subjects: openmeter.operations.SubjectsOperations + :ivar debug: DebugOperations operations + :vartype debug: openmeter.operations.DebugOperations + :ivar notification_channels: NotificationChannelsOperations operations + :vartype notification_channels: openmeter.operations.NotificationChannelsOperations + :ivar notification_rules: NotificationRulesOperations operations + :vartype notification_rules: openmeter.operations.NotificationRulesOperations + :ivar notification_events: NotificationEventsOperations operations + :vartype notification_events: openmeter.operations.NotificationEventsOperations + :ivar entitlements_v2: EntitlementsV2Operations operations + :vartype entitlements_v2: openmeter.operations.EntitlementsV2Operations + :ivar customer_entitlements_v2: CustomerEntitlementsV2Operations operations + :vartype customer_entitlements_v2: openmeter.operations.CustomerEntitlementsV2Operations + :ivar customer_entitlement_v2: CustomerEntitlementV2Operations operations + :vartype customer_entitlement_v2: openmeter.operations.CustomerEntitlementV2Operations + :ivar grants_v2: GrantsV2Operations operations + :vartype grants_v2: openmeter.operations.GrantsV2Operations + :ivar billing_profiles: BillingProfilesOperations operations + :vartype billing_profiles: openmeter.operations.BillingProfilesOperations + :ivar customer_overrides: CustomerOverridesOperations operations + :vartype customer_overrides: openmeter.operations.CustomerOverridesOperations + :ivar invoices: InvoicesOperations operations + :vartype invoices: openmeter.operations.InvoicesOperations + :ivar invoice: InvoiceOperations operations + :vartype invoice: openmeter.operations.InvoiceOperations + :ivar customer_invoice: CustomerInvoiceOperations operations + :vartype customer_invoice: openmeter.operations.CustomerInvoiceOperations + :ivar progress: ProgressOperations operations + :vartype progress: openmeter.operations.ProgressOperations + :ivar currencies: CurrenciesOperations operations + :vartype currencies: openmeter.operations.CurrenciesOperations + :keyword endpoint: Service host. Default value is "https://127.0.0.1". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "https://127.0.0.1", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = OpenMeterClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.retry_policy, + self._config.authentication_policy, + self._config.logging_policy, + ] + self._client: PipelineClient = PipelineClient(endpoint=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.portal = PortalOperations(self._client, self._config, self._serialize, self._deserialize) + self.apps = AppsOperations(self._client, self._config, self._serialize, self._deserialize) + self.app_stripe = AppStripeOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer_apps = CustomerAppsOperations(self._client, self._config, self._serialize, self._deserialize) + self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + self.plans = PlansOperations(self._client, self._config, self._serialize, self._deserialize) + self.plan_addons = PlanAddonsOperations(self._client, self._config, self._serialize, self._deserialize) + self.addons = AddonsOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscriptions = SubscriptionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscription_addons = SubscriptionAddonsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.entitlements = EntitlementsOperations(self._client, self._config, self._serialize, self._deserialize) + self.grants = GrantsOperations(self._client, self._config, self._serialize, self._deserialize) + self.subjects = SubjectsOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer = CustomerOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer_entitlement = CustomerEntitlementOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.customer_stripe = CustomerStripeOperations(self._client, self._config, self._serialize, self._deserialize) + self.marketplace = MarketplaceOperations(self._client, self._config, self._serialize, self._deserialize) + self.app_custom_invoicing = AppCustomInvoicingOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize) + self.events_v2 = EventsV2Operations(self._client, self._config, self._serialize, self._deserialize) + self.meters = MetersOperations(self._client, self._config, self._serialize, self._deserialize) + self.subjects = SubjectsOperations(self._client, self._config, self._serialize, self._deserialize) + self.debug = DebugOperations(self._client, self._config, self._serialize, self._deserialize) + self.notification_channels = NotificationChannelsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.notification_rules = NotificationRulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.notification_events = NotificationEventsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.entitlements_v2 = EntitlementsV2Operations(self._client, self._config, self._serialize, self._deserialize) + self.customer_entitlements_v2 = CustomerEntitlementsV2Operations( + self._client, self._config, self._serialize, self._deserialize + ) + self.customer_entitlement_v2 = CustomerEntitlementV2Operations( + self._client, self._config, self._serialize, self._deserialize + ) + self.grants_v2 = GrantsV2Operations(self._client, self._config, self._serialize, self._deserialize) + self.billing_profiles = BillingProfilesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.customer_overrides = CustomerOverridesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) + self.invoice = InvoiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer_invoice = CustomerInvoiceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.progress = ProgressOperations(self._client, self._config, self._serialize, self._deserialize) + self.currencies = CurrenciesOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from corehttp.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~corehttp.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~corehttp.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/api/client/python/openmeter/_generated/_configuration.py b/api/client/python/openmeter/_generated/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..1ccd2e2be5116f58474d887b06f1c00d1ad91d2f --- /dev/null +++ b/api/client/python/openmeter/_generated/_configuration.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +from typing import Any + +from corehttp.runtime import policies + +from ._version import VERSION + + +class OpenMeterClientConfiguration: + """Configuration for OpenMeterClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "https://127.0.0.1". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "https://127.0.0.1", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "openmeter/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/api/client/python/openmeter/_generated/_patch.py b/api/client/python/openmeter/_generated/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b208fb11fbc2e1955c43275aa4e1482dec7e5d6f --- /dev/null +++ b/api/client/python/openmeter/_generated/_patch.py @@ -0,0 +1,17 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/api/client/python/openmeter/_generated/_types.py b/api/client/python/openmeter/_generated/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..a279e3119db8117db1c237d1c1e4f830feda2277 --- /dev/null +++ b/api/client/python/openmeter/_generated/_types.py @@ -0,0 +1,89 @@ +# coding=utf-8 + +import datetime +from typing import TYPE_CHECKING, Union + +if TYPE_CHECKING: + from . import models as _models +App = Union["_models.StripeApp", "_models.SandboxApp", "_models.CustomInvoicingApp"] +CustomerAppData = Union[ + "_models.StripeCustomerAppData", "_models.SandboxCustomerAppData", "_models.CustomInvoicingCustomerAppData" +] +FeatureUnitCost = Union["_models.FeatureManualUnitCost", "_models.FeatureLLMUnitCost"] +RateCardEntitlement = Union[ + "_models.RateCardMeteredEntitlement", "_models.RateCardStaticEntitlement", "_models.RateCardBooleanEntitlement" +] +RateCardUsageBasedPrice = Union[ + "_models.FlatPriceWithPaymentTerm", + "_models.UnitPriceWithCommitments", + "_models.TieredPriceWithCommitments", + "_models.DynamicPriceWithCommitments", + "_models.PackagePriceWithCommitments", +] +RateCard = Union["_models.RateCardFlatFee", "_models.RateCardUsageBased"] +RecurringPeriodInterval = Union[str, str, "_models.RecurringPeriodIntervalEnum"] +Entitlement = Union["_models.EntitlementMetered", "_models.EntitlementStatic", "_models.EntitlementBoolean"] +SubscriptionErrorExtensions = "_models.SubscriptionBadRequestErrorResponseExtensions" +SubscriptionTiming = Union[str, "_models.SubscriptionTimingEnum", datetime.datetime] +SubscriptionEditOperation = Union[ + "_models.EditSubscriptionAddItem", + "_models.EditSubscriptionRemoveItem", + "_models.EditSubscriptionAddPhase", + "_models.EditSubscriptionRemovePhase", + "_models.EditSubscriptionStretchPhase", + "_models.EditSubscriptionUnscheduleEdit", +] +MeasureUsageFrom = Union[str, "_models.MeasureUsageFromPreset", datetime.datetime] +App = Union["_models.StripeApp", "_models.SandboxApp", "_models.CustomInvoicingApp"] +NotificationChannel = "_models.NotificationChannelWebhook" +NotificationRule = Union[ + "_models.NotificationRuleBalanceThreshold", + "_models.NotificationRuleEntitlementReset", + "_models.NotificationRuleInvoiceCreated", + "_models.NotificationRuleInvoiceUpdated", +] +InvoiceDocumentRef = "_models.CreditNoteOriginalInvoiceRef" +BillingProfileAppsOrReference = Union["_models.BillingProfileApps", "_models.BillingProfileAppReferences"] +BillingWorkflowCollectionAlignment = Union[ + "_models.BillingWorkflowCollectionAlignmentSubscription", "_models.BillingWorkflowCollectionAlignmentAnchored" +] +BillingDiscountReason = Union[ + "_models.DiscountReasonMaximumSpend", + "_models.DiscountReasonRatecardPercentage", + "_models.DiscountReasonRatecardUsage", +] +PaymentTerms = Union["_models.PaymentTermInstant", "_models.PaymentTermDueDate"] +NotificationEventPayload = Union[ + "_models.NotificationEventResetPayload", + "_models.NotificationEventBalanceThresholdPayload", + "_models.NotificationEventInvoiceCreatedPayload", + "_models.NotificationEventInvoiceUpdatedPayload", +] +EntitlementV2 = Union["_models.EntitlementMeteredV2", "_models.EntitlementStaticV2", "_models.EntitlementBooleanV2"] +VoidInvoiceLineAction = Union["_models.VoidInvoiceLineDiscardAction", "_models.VoidInvoiceLinePendingAction"] +AppReplaceUpdate = Union[ + "_models.StripeAppReplaceUpdate", "_models.SandboxAppReplaceUpdate", "_models.CustomInvoicingAppReplaceUpdate" +] +ULIDOrExternalKey = str +ListFeaturesResult = Union[list["_models.Feature"], "_models.FeaturePaginatedResponse"] +SubscriptionCreate = Union["_models.PlanSubscriptionCreate", "_models.CustomSubscriptionCreate"] +SubscriptionChange = Union["_models.PlanSubscriptionChange", "_models.CustomSubscriptionChange"] +ListEntitlementsResult = Union[list["_types.Entitlement"], "_models.EntitlementPaginatedResponse"] +EntitlementCreateInputs = Union[ + "_models.EntitlementMeteredCreateInputs", + "_models.EntitlementStaticCreateInputs", + "_models.EntitlementBooleanCreateInputs", +] +IngestEventsBody = Union["_models.Event", list["_models.Event"]] +NotificationChannelCreateRequest = "_models.NotificationChannelWebhookCreateRequest" +NotificationRuleCreateRequest = Union[ + "_models.NotificationRuleBalanceThresholdCreateRequest", + "_models.NotificationRuleEntitlementResetCreateRequest", + "_models.NotificationRuleInvoiceCreatedCreateRequest", + "_models.NotificationRuleInvoiceUpdatedCreateRequest", +] +EntitlementV2CreateInputs = Union[ + "_models.EntitlementMeteredV2CreateInputs", + "_models.EntitlementStaticCreateInputs", + "_models.EntitlementBooleanCreateInputs", +] diff --git a/api/client/python/openmeter/_generated/_utils/__init__.py b/api/client/python/openmeter/_generated/_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/api/client/python/openmeter/_generated/_utils/model_base.py b/api/client/python/openmeter/_generated/_utils/model_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4bce0460ec2e3423d4e92b55bc61f077cee44e14 --- /dev/null +++ b/api/client/python/openmeter/_generated/_utils/model_base.py @@ -0,0 +1,1453 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from corehttp.exceptions import DeserializationError +from corehttp.utils import CaseInsensitiveEnumMeta +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.serialization import _Null +from corehttp.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + model_meta = getattr(self, "_xml", {}) + existed_attr_keys: list[str] = [] + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + original_tsp_name=original_tsp_name, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/api/client/python/openmeter/_generated/_utils/serialization.py b/api/client/python/openmeter/_generated/_utils/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..029256399ed161967769676c3e1c88e2245975dd --- /dev/null +++ b/api/client/python/openmeter/_generated/_utils/serialization.py @@ -0,0 +1,2035 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 + +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore +from typing_extensions import Self + +from corehttp.exceptions import DeserializationError, SerializationError +from corehttp.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + :return: The deserialized data. + :rtype: object + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) from err + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + +TZ_UTC = datetime.timezone.utc + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[dict[str, Any]] = {} + for k in kwargs: # pylint: disable=consider-using-dict-items + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: # pylint: disable=broad-exception-caught + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> Self: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises DeserializationError: if something went wrong + :rtype: Self + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str + """ + return key.replace("\\.", ".") + + +class Serializer: # pylint: disable=too-many-public-methods + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): + """Serialize data into a string according to type. + + :param object target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises SerializationError: if serialization fails. + :returns: The serialized data. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() # pylint: disable=protected-access + try: + attributes = target_obj._attribute_map # pylint: disable=protected-access + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized |= target_obj.additional_properties + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param str name: The name of the query parameter. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, list + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param str name: The name of the header. + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param object data: The data to be serialized. + :param str data_type: The type to be serialized from. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + if data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param obj data: Object to be serialized. + :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object + :raises TypeError: raise if data_type is not one of str, int, float, bool. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + if data_type == "int": + return int(data) + if data_type == "float": + return float(data) + if data_type == "bool": + return bool(data) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param str data: Object to be serialized. + :rtype: str + :return: serialized object + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list data: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + Defaults to False. + :rtype: list, str + :return: serialized iterable + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :rtype: dict + :return: serialized dictionary + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + :return: serialized object + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + if obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError as exc: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) from exc + + @staticmethod + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument + """Serialize bytearray into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument + """Serialize str into base-64 string. + + :param str attr: Object to be serialized. + :rtype: str + :return: serialized base64 + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Decimal object to float. + + :param decimal attr: Object to be serialized. + :rtype: float + :return: serialized decimal + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument + """Serialize long (Py2) or int (Py3). + + :param int attr: Object to be serialized. + :rtype: int/long + :return: serialized long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + :return: serialized date + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + :return: serialized time + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises TypeError: if format invalid. + :return: serialized rfc + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises SerializationError: if format invalid. + :return: serialized iso + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises SerializationError: if format invalid + :return: serialied unix + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc + + +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(list[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer: + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: dict[str, type] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, str): + return self.deserialize_data(data, response) + if isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None or data is CoreNull: + return data + try: + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple + """ + if target is None: + return None, None + + if isinstance(target, str): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object + """ + try: + return self(target_obj, data, content_type=content_type) + except: # pylint: disable=bare-except + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties # type: ignore + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) from exp + + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises DeserializationError: if deserialization fails. + :return: Deserialized object. + :rtype: object + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. + :rtype: dict + :raises TypeError: if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, str): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :return: Deserialized basic type. + :rtype: str, int, float or bool + :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + if isinstance(attr, str): + if attr.lower() in ["true", "1"]: + return True + if attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + if data_type == "int": + return int(attr) + if data_type == "float": + return float(attr) + raise TypeError("Unknown basic data type: {}".format(data_type)) + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :return: Deserialized string. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError as exc: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) from exc + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :return: Deserialized bytearray + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :return: Deserialized base64 string + :rtype: bytearray + :raises TypeError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :return: Deserialized int + :rtype: long or int + :raises ValueError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :return: Deserialized date + :rtype: Date + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :return: Deserialized time + :rtype: datetime.time + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime + :rtype: Datetime + :raises DeserializationError: if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :return: Deserialized datetime + :rtype: Datetime + :raises DeserializationError: if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + return date_obj diff --git a/api/client/python/openmeter/_generated/_version.py b/api/client/python/openmeter/_generated/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..4c354e371612255573d6f48d7125b88efa5a76a0 --- /dev/null +++ b/api/client/python/openmeter/_generated/_version.py @@ -0,0 +1,3 @@ +# coding=utf-8 + +VERSION = "0.0.0" diff --git a/api/client/python/openmeter/_generated/aio/__init__.py b/api/client/python/openmeter/_generated/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad67f13df75ba0f25a01bdb1b65b1badf2566c80 --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import OpenMeterClient # type: ignore + +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "OpenMeterClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/api/client/python/openmeter/_generated/aio/_client.py b/api/client/python/openmeter/_generated/aio/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a808d8142e7f63e5b9473bbbf624be2a29c046b8 --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/_client.py @@ -0,0 +1,256 @@ +# coding=utf-8 + +from copy import deepcopy +from typing import Any, Awaitable +from typing_extensions import Self + +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient, policies + +from .._utils.serialization import Deserializer, Serializer +from ._configuration import OpenMeterClientConfiguration +from .operations import ( + AddonsOperations, + AppCustomInvoicingOperations, + AppStripeOperations, + AppsOperations, + BillingProfilesOperations, + CurrenciesOperations, + CustomerAppsOperations, + CustomerEntitlementOperations, + CustomerEntitlementV2Operations, + CustomerEntitlementsV2Operations, + CustomerInvoiceOperations, + CustomerOperations, + CustomerOverridesOperations, + CustomerStripeOperations, + CustomersOperations, + DebugOperations, + EntitlementsOperations, + EntitlementsV2Operations, + EventsOperations, + EventsV2Operations, + FeaturesOperations, + GrantsOperations, + GrantsV2Operations, + InvoiceOperations, + InvoicesOperations, + MarketplaceOperations, + MetersOperations, + NotificationChannelsOperations, + NotificationEventsOperations, + NotificationRulesOperations, + PlanAddonsOperations, + PlansOperations, + PortalOperations, + ProgressOperations, + SubjectsOperations, + SubscriptionAddonsOperations, + SubscriptionsOperations, +) + + +class OpenMeterClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes + """OpenMeter is a cloud native usage metering service. The OpenMeter API allows you to ingest + events, query meter usage, and manage resources. + + :ivar portal: PortalOperations operations + :vartype portal: openmeter.aio.operations.PortalOperations + :ivar apps: AppsOperations operations + :vartype apps: openmeter.aio.operations.AppsOperations + :ivar app_stripe: AppStripeOperations operations + :vartype app_stripe: openmeter.aio.operations.AppStripeOperations + :ivar customer_apps: CustomerAppsOperations operations + :vartype customer_apps: openmeter.aio.operations.CustomerAppsOperations + :ivar customers: CustomersOperations operations + :vartype customers: openmeter.aio.operations.CustomersOperations + :ivar features: FeaturesOperations operations + :vartype features: openmeter.aio.operations.FeaturesOperations + :ivar plans: PlansOperations operations + :vartype plans: openmeter.aio.operations.PlansOperations + :ivar plan_addons: PlanAddonsOperations operations + :vartype plan_addons: openmeter.aio.operations.PlanAddonsOperations + :ivar addons: AddonsOperations operations + :vartype addons: openmeter.aio.operations.AddonsOperations + :ivar subscriptions: SubscriptionsOperations operations + :vartype subscriptions: openmeter.aio.operations.SubscriptionsOperations + :ivar subscription_addons: SubscriptionAddonsOperations operations + :vartype subscription_addons: openmeter.aio.operations.SubscriptionAddonsOperations + :ivar entitlements: EntitlementsOperations operations + :vartype entitlements: openmeter.aio.operations.EntitlementsOperations + :ivar grants: GrantsOperations operations + :vartype grants: openmeter.aio.operations.GrantsOperations + :ivar subjects: SubjectsOperations operations + :vartype subjects: openmeter.aio.operations.SubjectsOperations + :ivar customer: CustomerOperations operations + :vartype customer: openmeter.aio.operations.CustomerOperations + :ivar customer_entitlement: CustomerEntitlementOperations operations + :vartype customer_entitlement: openmeter.aio.operations.CustomerEntitlementOperations + :ivar customer_stripe: CustomerStripeOperations operations + :vartype customer_stripe: openmeter.aio.operations.CustomerStripeOperations + :ivar marketplace: MarketplaceOperations operations + :vartype marketplace: openmeter.aio.operations.MarketplaceOperations + :ivar app_custom_invoicing: AppCustomInvoicingOperations operations + :vartype app_custom_invoicing: openmeter.aio.operations.AppCustomInvoicingOperations + :ivar events: EventsOperations operations + :vartype events: openmeter.aio.operations.EventsOperations + :ivar events_v2: EventsV2Operations operations + :vartype events_v2: openmeter.aio.operations.EventsV2Operations + :ivar meters: MetersOperations operations + :vartype meters: openmeter.aio.operations.MetersOperations + :ivar subjects: SubjectsOperations operations + :vartype subjects: openmeter.aio.operations.SubjectsOperations + :ivar debug: DebugOperations operations + :vartype debug: openmeter.aio.operations.DebugOperations + :ivar notification_channels: NotificationChannelsOperations operations + :vartype notification_channels: openmeter.aio.operations.NotificationChannelsOperations + :ivar notification_rules: NotificationRulesOperations operations + :vartype notification_rules: openmeter.aio.operations.NotificationRulesOperations + :ivar notification_events: NotificationEventsOperations operations + :vartype notification_events: openmeter.aio.operations.NotificationEventsOperations + :ivar entitlements_v2: EntitlementsV2Operations operations + :vartype entitlements_v2: openmeter.aio.operations.EntitlementsV2Operations + :ivar customer_entitlements_v2: CustomerEntitlementsV2Operations operations + :vartype customer_entitlements_v2: openmeter.aio.operations.CustomerEntitlementsV2Operations + :ivar customer_entitlement_v2: CustomerEntitlementV2Operations operations + :vartype customer_entitlement_v2: openmeter.aio.operations.CustomerEntitlementV2Operations + :ivar grants_v2: GrantsV2Operations operations + :vartype grants_v2: openmeter.aio.operations.GrantsV2Operations + :ivar billing_profiles: BillingProfilesOperations operations + :vartype billing_profiles: openmeter.aio.operations.BillingProfilesOperations + :ivar customer_overrides: CustomerOverridesOperations operations + :vartype customer_overrides: openmeter.aio.operations.CustomerOverridesOperations + :ivar invoices: InvoicesOperations operations + :vartype invoices: openmeter.aio.operations.InvoicesOperations + :ivar invoice: InvoiceOperations operations + :vartype invoice: openmeter.aio.operations.InvoiceOperations + :ivar customer_invoice: CustomerInvoiceOperations operations + :vartype customer_invoice: openmeter.aio.operations.CustomerInvoiceOperations + :ivar progress: ProgressOperations operations + :vartype progress: openmeter.aio.operations.ProgressOperations + :ivar currencies: CurrenciesOperations operations + :vartype currencies: openmeter.aio.operations.CurrenciesOperations + :keyword endpoint: Service host. Default value is "https://127.0.0.1". + :paramtype endpoint: str + """ + + def __init__( # pylint: disable=missing-client-constructor-parameter-credential + self, *, endpoint: str = "https://127.0.0.1", **kwargs: Any + ) -> None: + _endpoint = "{endpoint}" + self._config = OpenMeterClientConfiguration(endpoint=endpoint, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.retry_policy, + self._config.authentication_policy, + self._config.logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(endpoint=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.portal = PortalOperations(self._client, self._config, self._serialize, self._deserialize) + self.apps = AppsOperations(self._client, self._config, self._serialize, self._deserialize) + self.app_stripe = AppStripeOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer_apps = CustomerAppsOperations(self._client, self._config, self._serialize, self._deserialize) + self.customers = CustomersOperations(self._client, self._config, self._serialize, self._deserialize) + self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize) + self.plans = PlansOperations(self._client, self._config, self._serialize, self._deserialize) + self.plan_addons = PlanAddonsOperations(self._client, self._config, self._serialize, self._deserialize) + self.addons = AddonsOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscriptions = SubscriptionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.subscription_addons = SubscriptionAddonsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.entitlements = EntitlementsOperations(self._client, self._config, self._serialize, self._deserialize) + self.grants = GrantsOperations(self._client, self._config, self._serialize, self._deserialize) + self.subjects = SubjectsOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer = CustomerOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer_entitlement = CustomerEntitlementOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.customer_stripe = CustomerStripeOperations(self._client, self._config, self._serialize, self._deserialize) + self.marketplace = MarketplaceOperations(self._client, self._config, self._serialize, self._deserialize) + self.app_custom_invoicing = AppCustomInvoicingOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize) + self.events_v2 = EventsV2Operations(self._client, self._config, self._serialize, self._deserialize) + self.meters = MetersOperations(self._client, self._config, self._serialize, self._deserialize) + self.subjects = SubjectsOperations(self._client, self._config, self._serialize, self._deserialize) + self.debug = DebugOperations(self._client, self._config, self._serialize, self._deserialize) + self.notification_channels = NotificationChannelsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.notification_rules = NotificationRulesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.notification_events = NotificationEventsOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.entitlements_v2 = EntitlementsV2Operations(self._client, self._config, self._serialize, self._deserialize) + self.customer_entitlements_v2 = CustomerEntitlementsV2Operations( + self._client, self._config, self._serialize, self._deserialize + ) + self.customer_entitlement_v2 = CustomerEntitlementV2Operations( + self._client, self._config, self._serialize, self._deserialize + ) + self.grants_v2 = GrantsV2Operations(self._client, self._config, self._serialize, self._deserialize) + self.billing_profiles = BillingProfilesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.customer_overrides = CustomerOverridesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.invoices = InvoicesOperations(self._client, self._config, self._serialize, self._deserialize) + self.invoice = InvoiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.customer_invoice = CustomerInvoiceOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.progress = ProgressOperations(self._client, self._config, self._serialize, self._deserialize) + self.currencies = CurrenciesOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from corehttp.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~corehttp.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~corehttp.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/api/client/python/openmeter/_generated/aio/_configuration.py b/api/client/python/openmeter/_generated/aio/_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..28fb19f5c67d67a08d831960b80e9a352d378c4e --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/_configuration.py @@ -0,0 +1,33 @@ +# coding=utf-8 + +from typing import Any + +from corehttp.runtime import policies + +from .._version import VERSION + + +class OpenMeterClientConfiguration: + """Configuration for OpenMeterClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Service host. Default value is "https://127.0.0.1". + :type endpoint: str + """ + + def __init__(self, endpoint: str = "https://127.0.0.1", **kwargs: Any) -> None: + + self.endpoint = endpoint + kwargs.setdefault("sdk_moniker", "openmeter/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") diff --git a/api/client/python/openmeter/_generated/aio/_patch.py b/api/client/python/openmeter/_generated/aio/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b208fb11fbc2e1955c43275aa4e1482dec7e5d6f --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/_patch.py @@ -0,0 +1,17 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/api/client/python/openmeter/_generated/aio/operations/__init__.py b/api/client/python/openmeter/_generated/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..291d5bb58714572fb0a528e2dd2de5b69e9865e7 --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/operations/__init__.py @@ -0,0 +1,93 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PortalOperations # type: ignore +from ._operations import AppsOperations # type: ignore +from ._operations import AppStripeOperations # type: ignore +from ._operations import CustomerAppsOperations # type: ignore +from ._operations import CustomersOperations # type: ignore +from ._operations import FeaturesOperations # type: ignore +from ._operations import PlansOperations # type: ignore +from ._operations import PlanAddonsOperations # type: ignore +from ._operations import AddonsOperations # type: ignore +from ._operations import SubscriptionsOperations # type: ignore +from ._operations import SubscriptionAddonsOperations # type: ignore +from ._operations import EntitlementsOperations # type: ignore +from ._operations import GrantsOperations # type: ignore +from ._operations import SubjectsOperations # type: ignore +from ._operations import CustomerOperations # type: ignore +from ._operations import CustomerEntitlementOperations # type: ignore +from ._operations import CustomerStripeOperations # type: ignore +from ._operations import MarketplaceOperations # type: ignore +from ._operations import AppCustomInvoicingOperations # type: ignore +from ._operations import EventsOperations # type: ignore +from ._operations import EventsV2Operations # type: ignore +from ._operations import MetersOperations # type: ignore +from ._operations import SubjectsOperations # type: ignore +from ._operations import DebugOperations # type: ignore +from ._operations import NotificationChannelsOperations # type: ignore +from ._operations import NotificationRulesOperations # type: ignore +from ._operations import NotificationEventsOperations # type: ignore +from ._operations import EntitlementsV2Operations # type: ignore +from ._operations import CustomerEntitlementsV2Operations # type: ignore +from ._operations import CustomerEntitlementV2Operations # type: ignore +from ._operations import GrantsV2Operations # type: ignore +from ._operations import BillingProfilesOperations # type: ignore +from ._operations import CustomerOverridesOperations # type: ignore +from ._operations import InvoicesOperations # type: ignore +from ._operations import InvoiceOperations # type: ignore +from ._operations import CustomerInvoiceOperations # type: ignore +from ._operations import ProgressOperations # type: ignore +from ._operations import CurrenciesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PortalOperations", + "AppsOperations", + "AppStripeOperations", + "CustomerAppsOperations", + "CustomersOperations", + "FeaturesOperations", + "PlansOperations", + "PlanAddonsOperations", + "AddonsOperations", + "SubscriptionsOperations", + "SubscriptionAddonsOperations", + "EntitlementsOperations", + "GrantsOperations", + "SubjectsOperations", + "CustomerOperations", + "CustomerEntitlementOperations", + "CustomerStripeOperations", + "MarketplaceOperations", + "AppCustomInvoicingOperations", + "EventsOperations", + "EventsV2Operations", + "MetersOperations", + "SubjectsOperations", + "DebugOperations", + "NotificationChannelsOperations", + "NotificationRulesOperations", + "NotificationEventsOperations", + "EntitlementsV2Operations", + "CustomerEntitlementsV2Operations", + "CustomerEntitlementV2Operations", + "GrantsV2Operations", + "BillingProfilesOperations", + "CustomerOverridesOperations", + "InvoicesOperations", + "InvoiceOperations", + "CustomerInvoiceOperations", + "ProgressOperations", + "CurrenciesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/api/client/python/openmeter/_generated/aio/operations/_operations.py b/api/client/python/openmeter/_generated/aio/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7804d6235e06008b9f07e138df68eb7683cd76 --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/operations/_operations.py @@ -0,0 +1,20168 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +from collections.abc import MutableMapping +import datetime +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TYPE_CHECKING, TypeVar, Union, overload + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from corehttp.paging import AsyncItemPaged, AsyncList +from corehttp.rest import AsyncHttpResponse, HttpRequest +from corehttp.runtime import AsyncPipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_addons_archive_request, + build_addons_create_request, + build_addons_delete_request, + build_addons_get_request, + build_addons_list_request, + build_addons_publish_request, + build_addons_update_request, + build_app_custom_invoicing_draft_syncronized_request, + build_app_custom_invoicing_finalized_request, + build_app_custom_invoicing_payment_status_request, + build_app_stripe_create_checkout_session_request, + build_app_stripe_update_stripe_api_key_request, + build_app_stripe_webhook_request, + build_apps_get_request, + build_apps_list_request, + build_apps_uninstall_request, + build_apps_update_request, + build_billing_profiles_create_request, + build_billing_profiles_delete_request, + build_billing_profiles_get_request, + build_billing_profiles_list_request, + build_billing_profiles_update_request, + build_currencies_list_currencies_request, + build_customer_apps_delete_app_data_request, + build_customer_apps_list_app_data_request, + build_customer_apps_upsert_app_data_request, + build_customer_entitlement_get_customer_entitlement_value_request, + build_customer_entitlement_v2_create_customer_entitlement_grant_request, + build_customer_entitlement_v2_get_customer_entitlement_history_request, + build_customer_entitlement_v2_get_customer_entitlement_value_request, + build_customer_entitlement_v2_get_grants_request, + build_customer_entitlement_v2_reset_customer_entitlement_request, + build_customer_entitlements_v2_delete_request, + build_customer_entitlements_v2_get_request, + build_customer_entitlements_v2_list_request, + build_customer_entitlements_v2_override_request, + build_customer_entitlements_v2_post_request, + build_customer_get_customer_access_request, + build_customer_invoice_create_pending_invoice_line_request, + build_customer_invoice_simulate_invoice_request, + build_customer_overrides_delete_request, + build_customer_overrides_get_request, + build_customer_overrides_list_request, + build_customer_overrides_upsert_request, + build_customer_stripe_create_portal_session_request, + build_customer_stripe_get_request, + build_customer_stripe_upsert_request, + build_customers_create_request, + build_customers_delete_request, + build_customers_get_request, + build_customers_list_customer_subscriptions_request, + build_customers_list_request, + build_customers_update_request, + build_debug_metrics_request, + build_entitlements_get_request, + build_entitlements_list_request, + build_entitlements_v2_get_request, + build_entitlements_v2_list_request, + build_events_ingest_event_request, + build_events_ingest_events_json_request, + build_events_ingest_events_request, + build_events_list_request, + build_events_v2_list_request, + build_features_create_request, + build_features_delete_request, + build_features_get_request, + build_features_list_request, + build_grants_delete_request, + build_grants_list_request, + build_grants_v2_list_request, + build_invoice_advance_action_request, + build_invoice_approve_action_request, + build_invoice_delete_invoice_request, + build_invoice_get_invoice_request, + build_invoice_recalculate_tax_action_request, + build_invoice_retry_action_request, + build_invoice_snapshot_quantities_action_request, + build_invoice_update_invoice_request, + build_invoice_void_invoice_action_request, + build_invoices_invoice_pending_lines_action_request, + build_invoices_list_request, + build_marketplace_authorize_o_auth2_install_request, + build_marketplace_get_o_auth2_install_url_request, + build_marketplace_get_request, + build_marketplace_install_request, + build_marketplace_install_with_api_key_request, + build_marketplace_list_request, + build_meters_create_request, + build_meters_delete_request, + build_meters_get_request, + build_meters_list_group_by_values_request, + build_meters_list_request, + build_meters_list_subjects_request, + build_meters_query_csv_post_request, + build_meters_query_csv_request, + build_meters_query_json_request, + build_meters_query_request, + build_meters_update_request, + build_notification_channels_create_request, + build_notification_channels_delete_request, + build_notification_channels_get_request, + build_notification_channels_list_request, + build_notification_channels_update_request, + build_notification_events_get_request, + build_notification_events_list_request, + build_notification_events_resend_request, + build_notification_rules_create_request, + build_notification_rules_delete_request, + build_notification_rules_get_request, + build_notification_rules_list_request, + build_notification_rules_test_request, + build_notification_rules_update_request, + build_plan_addons_create_request, + build_plan_addons_delete_request, + build_plan_addons_get_request, + build_plan_addons_list_request, + build_plan_addons_update_request, + build_plans_archive_request, + build_plans_create_request, + build_plans_delete_request, + build_plans_get_request, + build_plans_list_request, + build_plans_next_request, + build_plans_publish_request, + build_plans_update_request, + build_portal_portal_meters_query_csv_request, + build_portal_portal_meters_query_json_request, + build_portal_portal_tokens_create_request, + build_portal_portal_tokens_invalidate_request, + build_portal_portal_tokens_list_request, + build_progress_get_progress_request, + build_subjects_create_grant_request, + build_subjects_delete_request, + build_subjects_get_entitlement_history_request, + build_subjects_get_entitlement_value_request, + build_subjects_get_grants_request, + build_subjects_get_request, + build_subjects_list_request, + build_subjects_override_request, + build_subjects_post_request, + build_subjects_reset_request, + build_subjects_upsert_request, + build_subscription_addons_create_request, + build_subscription_addons_get_request, + build_subscription_addons_list_request, + build_subscription_addons_update_request, + build_subscriptions_cancel_request, + build_subscriptions_change_request, + build_subscriptions_create_request, + build_subscriptions_delete_request, + build_subscriptions_edit_request, + build_subscriptions_get_expanded_request, + build_subscriptions_migrate_request, + build_subscriptions_restore_request, + build_subscriptions_unschedule_cancelation_request, +) +from .._configuration import OpenMeterClientConfiguration + +if TYPE_CHECKING: + from ... import _types +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +_Unset: Any = object() +List = list + + +class PortalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`portal` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + self.portal_tokens = PortalPortalTokensOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.portal_meters = PortalPortalMetersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + +class AppsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`apps` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, *, page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any + ) -> _models.AppPaginatedResponse: + """List apps. + + List apps. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: AppPaginatedResponse. The AppPaginatedResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.AppPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AppPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_apps_list_request( + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AppPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, id: str, **kwargs: Any) -> "_types.App": + """Get app. + + Get the app. + + :param id: Required. + :type id: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.App"] = kwargs.pop("cls", None) + + _request = build_apps_get_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.App", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, id: str, app: _models.StripeAppReplaceUpdate, *, content_type: str = "application/json", **kwargs: Any + ) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Required. + :type app: ~openmeter._generated.models.StripeAppReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, id: str, app: _models.SandboxAppReplaceUpdate, *, content_type: str = "application/json", **kwargs: Any + ) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Required. + :type app: ~openmeter._generated.models.SandboxAppReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + id: str, + app: _models.CustomInvoicingAppReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Required. + :type app: ~openmeter._generated.models.CustomInvoicingAppReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update(self, id: str, app: "_types.AppReplaceUpdate", **kwargs: Any) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Is one of the following types: StripeAppReplaceUpdate, SandboxAppReplaceUpdate, + CustomInvoicingAppReplaceUpdate Required. + :type app: ~openmeter._generated.models.StripeAppReplaceUpdate or + ~openmeter._generated.models.SandboxAppReplaceUpdate or + ~openmeter._generated.models.CustomInvoicingAppReplaceUpdate + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.App"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(app, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_apps_update_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.App", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def uninstall(self, id: str, **kwargs: Any) -> None: + """Uninstall app. + + Uninstall an app. + + :param id: Required. + :type id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_apps_uninstall_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class AppStripeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`app_stripe` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def webhook( + self, id: str, body: _models.StripeWebhookEvent, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Required. + :type body: ~openmeter._generated.models.StripeWebhookEvent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def webhook( + self, id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def webhook( + self, id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def webhook( + self, id: str, body: Union[_models.StripeWebhookEvent, JSON, IO[bytes]], **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Is one of the following types: StripeWebhookEvent, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.StripeWebhookEvent or JSON or IO[bytes] + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.StripeWebhookResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_stripe_webhook_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeWebhookResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_stripe_api_key( + self, id: str, request: _models.StripeAPIKeyInput, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Required. + :type request: ~openmeter._generated.models.StripeAPIKeyInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update_stripe_api_key( + self, id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update_stripe_api_key( + self, id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update_stripe_api_key( + self, id: str, request: Union[_models.StripeAPIKeyInput, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Is one of the following types: StripeAPIKeyInput, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.StripeAPIKeyInput or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_stripe_update_stripe_api_key_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def create_checkout_session( + self, body: _models.CreateStripeCheckoutSessionRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Required. + :type body: ~openmeter._generated.models.CreateStripeCheckoutSessionRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_checkout_session( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_checkout_session( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create_checkout_session( + self, body: Union[_models.CreateStripeCheckoutSessionRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Is one of the following types: CreateStripeCheckoutSessionRequest, JSON, IO[bytes] + Required. + :type body: ~openmeter._generated.models.CreateStripeCheckoutSessionRequest or JSON or + IO[bytes] + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CreateStripeCheckoutSessionResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_stripe_create_checkout_session_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CreateStripeCheckoutSessionResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerAppsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_apps` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + type: Optional[Union[str, _models.AppType]] = None, + **kwargs: Any + ) -> _models.CustomerAppDataPaginatedResponse: + """List customer app data. + + List customers app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword type: Filter customer data by app type. Known values are: "stripe", "sandbox", and + "custom_invoicing". Default value is None. + :paramtype type: str or ~openmeter.models.AppType + :return: CustomerAppDataPaginatedResponse. The CustomerAppDataPaginatedResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CustomerAppDataPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.CustomerAppDataPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_apps_list_app_data_request( + customer_id_or_key=customer_id_or_key, + page=page, + page_size=page_size, + type=type, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CustomerAppDataPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def upsert_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: List["_types.CustomerAppData"], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> List["_types.CustomerAppData"]: + """Upsert customer app data. + + Upsert customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of StripeCustomerAppData or SandboxCustomerAppData or + CustomInvoicingCustomerAppData + :rtype: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> List["_types.CustomerAppData"]: + """Upsert customer app data. + + Upsert customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of StripeCustomerAppData or SandboxCustomerAppData or + CustomInvoicingCustomerAppData + :rtype: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def upsert_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: Union[List["_types.CustomerAppData"], IO[bytes]], + **kwargs: Any + ) -> List["_types.CustomerAppData"]: + """Upsert customer app data. + + Upsert customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Is either a ["_types.CustomerAppData"] type or a IO[bytes] type. Required. + :type app_data: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] or IO[bytes] + :return: list of StripeCustomerAppData or SandboxCustomerAppData or + CustomInvoicingCustomerAppData + :rtype: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List["_types.CustomerAppData"]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(app_data, (IOBase, bytes)): + _content = app_data + else: + _content = json.dumps(app_data, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_apps_upsert_app_data_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List["_types.CustomerAppData"], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete_app_data(self, customer_id_or_key: "_types.ULIDOrExternalKey", app_id: str, **kwargs: Any) -> None: + """Delete customer app data. + + Delete customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_id: Required. + :type app_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customer_apps_delete_app_data_request( + customer_id_or_key=customer_id_or_key, + app_id=app_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class CustomersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customers` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, customer: _models.CustomerCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Required. + :type customer: ~openmeter._generated.models.CustomerCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, customer: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Required. + :type customer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, customer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Required. + :type customer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, customer: Union[_models.CustomerCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Is one of the following types: CustomerCreate, JSON, IO[bytes] Required. + :type customer: ~openmeter._generated.models.CustomerCreate or JSON or IO[bytes] + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Customer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(customer, (IOBase, bytes)): + _content = customer + else: + _content = json.dumps(customer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customers_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Customer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list( + self, + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.CustomerOrderBy]] = None, + include_deleted: Optional[bool] = None, + key: Optional[str] = None, + name: Optional[str] = None, + primary_email: Optional[str] = None, + subject: Optional[str] = None, + plan_key: Optional[str] = None, + expand: Optional[List[Union[str, _models.CustomerExpand]]] = None, + **kwargs: Any + ) -> _models.CustomerPaginatedResponse: + """List customers. + + List customers. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "name", and "createdAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.CustomerOrderBy + :keyword include_deleted: Include deleted customers. Default value is None. + :paramtype include_deleted: bool + :keyword key: Filter customers by key. + Case-insensitive partial match. Default value is None. + :paramtype key: str + :keyword name: Filter customers by name. + Case-insensitive partial match. Default value is None. + :paramtype name: str + :keyword primary_email: Filter customers by primary email. + Case-insensitive partial match. Default value is None. + :paramtype primary_email: str + :keyword subject: Filter customers by usage attribution subject. + Case-insensitive partial match. Default value is None. + :paramtype subject: str + :keyword plan_key: Filter customers by the plan key of their susbcription. Default value is + None. + :paramtype plan_key: str + :keyword expand: What parts of the list output to expand in listings. Default value is None. + :paramtype expand: list[str or ~openmeter.models.CustomerExpand] + :return: CustomerPaginatedResponse. The CustomerPaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.CustomerPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.CustomerPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customers_list_request( + page=page, + page_size=page_size, + order=order, + order_by=order_by, + include_deleted=include_deleted, + key=key, + name=name, + primary_email=primary_email, + subject=subject, + plan_key=plan_key, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CustomerPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + expand: Optional[List[Union[str, _models.CustomerExpand]]] = None, + **kwargs: Any + ) -> _models.Customer: + """Get customer. + + Get a customer by ID or key. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword expand: What parts of the customer output to expand. Default value is None. + :paramtype expand: list[str or ~openmeter.models.CustomerExpand] + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Customer] = kwargs.pop("cls", None) + + _request = build_customers_get_request( + customer_id_or_key=customer_id_or_key, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Customer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: _models.CustomerReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Required. + :type customer: ~openmeter._generated.models.CustomerReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Required. + :type customer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Required. + :type customer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: Union[_models.CustomerReplaceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Is one of the following types: CustomerReplaceUpdate, JSON, IO[bytes] + Required. + :type customer: ~openmeter._generated.models.CustomerReplaceUpdate or JSON or IO[bytes] + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Customer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(customer, (IOBase, bytes)): + _content = customer + else: + _content = json.dumps(customer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customers_update_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Customer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> None: + """Delete customer. + + Delete a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customers_delete_request( + customer_id_or_key=customer_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def list_customer_subscriptions( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + status: Optional[List[Union[str, _models.SubscriptionStatus]]] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.CustomerSubscriptionOrderBy]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + **kwargs: Any + ) -> _models.SubscriptionPaginatedResponse: + """List customer subscriptions. + + Lists all subscriptions for a customer. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword status: Default value is None. + :paramtype status: list[str or ~openmeter.models.SubscriptionStatus] + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "activeFrom" and "activeTo". Default + value is None. + :paramtype order_by: str or ~openmeter.models.CustomerSubscriptionOrderBy + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: SubscriptionPaginatedResponse. The SubscriptionPaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SubscriptionPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customers_list_customer_subscriptions_request( + customer_id_or_key=customer_id_or_key, + status=status, + order=order, + order_by=order_by, + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`features` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + meter_slug: Optional[List[str]] = None, + include_archived: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.FeatureOrderBy]] = None, + **kwargs: Any + ) -> "_types.ListFeaturesResult": + """List features. + + List features. + + :keyword meter_slug: Filter by meterSlug. Default value is None. + :paramtype meter_slug: list[str] + :keyword include_archived: Include archived features in response. Default value is None. + :paramtype include_archived: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "name", "createdAt", and + "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.FeatureOrderBy + :return: list of Feature or FeaturePaginatedResponse + :rtype: list[~openmeter._generated.models.Feature] or + ~openmeter._generated.models.FeaturePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.ListFeaturesResult"] = kwargs.pop("cls", None) + + _request = build_features_list_request( + meter_slug=meter_slug, + include_archived=include_archived, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.ListFeaturesResult", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, feature: _models.FeatureCreateInputs, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Required. + :type feature: ~openmeter._generated.models.FeatureCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create(self, feature: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Required. + :type feature: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, feature: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Required. + :type feature: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create( + self, feature: Union[_models.FeatureCreateInputs, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Is one of the following types: FeatureCreateInputs, JSON, IO[bytes] Required. + :type feature: ~openmeter._generated.models.FeatureCreateInputs or JSON or IO[bytes] + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Feature] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(feature, (IOBase, bytes)): + _content = feature + else: + _content = json.dumps(feature, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_features_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Feature, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, feature_id: str, **kwargs: Any) -> _models.Feature: + """Get feature. + + Get a feature by ID. + + :param feature_id: Required. + :type feature_id: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Feature] = kwargs.pop("cls", None) + + _request = build_features_get_request( + feature_id=feature_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Feature, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, feature_id: str, **kwargs: Any) -> None: + """Delete feature. + + Archive a feature by ID. + + Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements + cannot be created for it, but archiving the feature does not affect existing entitlements. + This means, if you want to create a new feature with the same key, and then create entitlements + for it, the previous entitlements have to be deleted first on a per subject basis. + + :param feature_id: Required. + :type feature_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_features_delete_request( + feature_id=feature_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class PlansOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`plans` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + status: Optional[List[Union[str, _models.PlanStatus]]] = None, + currency: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.PlanOrderBy]] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.Plan"]: + """List plans. + + List all plans. + + :keyword include_deleted: Include deleted plans in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword id: Filter by plan.id attribute. Default value is None. + :paramtype id: list[str] + :keyword key: Filter by plan.key attribute. Default value is None. + :paramtype key: list[str] + :keyword key_version: Filter by plan.key and plan.version attributes. Default value is None. + :paramtype key_version: dict[str, list[int]] + :keyword status: Only return plans with the given status. + + Usage: + + * `?status=active`: return only the currently active plan + * `?status=draft`: return only the draft plan + * `?status=archived`: return only the archived plans. Default value is None. + :paramtype status: list[str or ~openmeter.models.PlanStatus] + :keyword currency: Filter by plan.currency attribute. Default value is None. + :paramtype currency: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "version", "created_at", + and "updated_at". Default value is None. + :paramtype order_by: str or ~openmeter.models.PlanOrderBy + :return: An iterator like instance of Plan + :rtype: ~corehttp.paging.AsyncItemPaged[~openmeter._generated.models.Plan] + :raises ~corehttp.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Plan]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_plans_list_request( + include_deleted=include_deleted, + id=id, + key=key, + key_version=key_version, + status=status, + currency=currency, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + _request = HttpRequest("GET", next_link, headers=_headers) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Plan], + deserialized.get("items", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create( + self, request: _models.PlanCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Required. + :type request: ~openmeter._generated.models.PlanCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create(self, request: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, request: Union[_models.PlanCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Is one of the following types: PlanCreate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.PlanCreate or JSON or IO[bytes] + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plans_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, plan_id: str, body: _models.PlanReplaceUpdate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, plan_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, plan_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, plan_id: str, body: Union[_models.PlanReplaceUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Is one of the following types: PlanReplaceUpdate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.PlanReplaceUpdate or JSON or IO[bytes] + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plans_update_request( + plan_id=plan_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, plan_id: str, *, include_latest: Optional[bool] = None, **kwargs: Any) -> _models.Plan: + """Get plan. + + Get a plan by id or key. The latest published version is returned if latter is used. + + :param plan_id: Required. + :type plan_id: str + :keyword include_latest: Include latest version of the Plan instead of the version in active + state. + + Usage: ``?includeLatest=true``. Default value is None. + :paramtype include_latest: bool + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_get_request( + plan_id=plan_id, + include_latest=include_latest, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, plan_id: str, **kwargs: Any) -> None: + """Delete plan. + + Soft delete plan by plan.id. + + Once a plan is deleted it cannot be undeleted. + + :param plan_id: Required. + :type plan_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_plans_delete_request( + plan_id=plan_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def publish(self, plan_id: str, **kwargs: Any) -> _models.Plan: + """Publish plan. + + Publish a plan version. + + :param plan_id: Required. + :type plan_id: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_publish_request( + plan_id=plan_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def archive(self, plan_id: str, **kwargs: Any) -> _models.Plan: + """Archive plan version. + + Archive a plan version. + + :param plan_id: Required. + :type plan_id: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_archive_request( + plan_id=plan_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def next(self, plan_id_or_key: str, **kwargs: Any) -> _models.Plan: + """New draft plan. + + Create a new draft version from plan. It returns error if there is already a plan in draft or + planId does not reference the latest published version. + + :param plan_id_or_key: Required. + :type plan_id_or_key: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_next_request( + plan_id_or_key=plan_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PlanAddonsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`plan_addons` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + plan_id: str, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.PlanAddonOrderBy]] = None, + **kwargs: Any + ) -> _models.PlanAddonPaginatedResponse: + """List all available add-ons for plan. + + List all available add-ons for plan. + + :param plan_id: Required. + :type plan_id: str + :keyword include_deleted: Include deleted plan add-on assignments. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword id: Filter by addon.id attribute. Default value is None. + :paramtype id: list[str] + :keyword key: Filter by addon.key attribute. Default value is None. + :paramtype key: list[str] + :keyword key_version: Filter by addon.key and addon.version attributes. Default value is None. + :paramtype key_version: dict[str, list[int]] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "version", "created_at", + and "updated_at". Default value is None. + :paramtype order_by: str or ~openmeter.models.PlanAddonOrderBy + :return: PlanAddonPaginatedResponse. The PlanAddonPaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.PlanAddonPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PlanAddonPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_plan_addons_list_request( + plan_id=plan_id, + include_deleted=include_deleted, + id=id, + key=key, + key_version=key_version, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddonPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, plan_id: str, body: _models.PlanAddonCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanAddonCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, plan_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, plan_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create( + self, plan_id: str, body: Union[_models.PlanAddonCreate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Is one of the following types: PlanAddonCreate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.PlanAddonCreate or JSON or IO[bytes] + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PlanAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plan_addons_create_request( + plan_id=plan_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + plan_id: str, + plan_addon_id: str, + body: _models.PlanAddonReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanAddonReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, plan_id: str, plan_addon_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + plan_id: str, + plan_addon_id: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, + plan_id: str, + plan_addon_id: str, + body: Union[_models.PlanAddonReplaceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Is one of the following types: PlanAddonReplaceUpdate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.PlanAddonReplaceUpdate or JSON or IO[bytes] + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PlanAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plan_addons_update_request( + plan_id=plan_id, + plan_addon_id=plan_addon_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, plan_id: str, plan_addon_id: str, **kwargs: Any) -> _models.PlanAddon: + """Get add-on assignment for plan. + + Get add-on assignment for plan by id. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PlanAddon] = kwargs.pop("cls", None) + + _request = build_plan_addons_get_request( + plan_id=plan_id, + plan_addon_id=plan_addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, plan_id: str, plan_addon_id: str, **kwargs: Any) -> None: + """Delete add-on assignment for plan. + + Delete add-on assignment for plan. + + Once a plan is deleted it cannot be undeleted. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_plan_addons_delete_request( + plan_id=plan_id, + plan_addon_id=plan_addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class AddonsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`addons` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + status: Optional[List[Union[str, _models.AddonStatus]]] = None, + currency: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.AddonOrderBy]] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.Addon"]: + """List add-ons. + + List all add-ons. + + :keyword include_deleted: Include deleted add-ons in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword id: Filter by addon.id attribute. Default value is None. + :paramtype id: list[str] + :keyword key: Filter by addon.key attribute. Default value is None. + :paramtype key: list[str] + :keyword key_version: Filter by addon.key and addon.version attributes. Default value is None. + :paramtype key_version: dict[str, list[int]] + :keyword status: Only return add-ons with the given status. + + Usage: + + * `?status=active`: return only the currently active add-ons + * `?status=draft`: return only the draft add-ons + * `?status=archived`: return only the archived add-ons. Default value is None. + :paramtype status: list[str or ~openmeter.models.AddonStatus] + :keyword currency: Filter by addon.currency attribute. Default value is None. + :paramtype currency: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "version", "created_at", + and "updated_at". Default value is None. + :paramtype order_by: str or ~openmeter.models.AddonOrderBy + :return: An iterator like instance of Addon + :rtype: ~corehttp.paging.AsyncItemPaged[~openmeter._generated.models.Addon] + :raises ~corehttp.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Addon]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_addons_list_request( + include_deleted=include_deleted, + id=id, + key=key, + key_version=key_version, + status=status, + currency=currency, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + _request = HttpRequest("GET", next_link, headers=_headers) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Addon], + deserialized.get("items", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @overload + async def create( + self, request: _models.AddonCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Required. + :type request: ~openmeter._generated.models.AddonCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create(self, request: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, request: Union[_models.AddonCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Is one of the following types: AddonCreate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.AddonCreate or JSON or IO[bytes] + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_addons_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + addon_id: str, + request: _models.AddonReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Required. + :type request: ~openmeter._generated.models.AddonReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, addon_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, addon_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, addon_id: str, request: Union[_models.AddonReplaceUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Is one of the following types: AddonReplaceUpdate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.AddonReplaceUpdate or JSON or IO[bytes] + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_addons_update_request( + addon_id=addon_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, addon_id: str, *, include_latest: Optional[bool] = None, **kwargs: Any) -> _models.Addon: + """Get add-on. + + Get add-on by id or key. The latest published version is returned if latter is used. + + :param addon_id: Required. + :type addon_id: str + :keyword include_latest: Include latest version of the add-on instead of the version in active + state. + + Usage: ``?includeLatest=true``. Default value is None. + :paramtype include_latest: bool + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + _request = build_addons_get_request( + addon_id=addon_id, + include_latest=include_latest, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, addon_id: str, **kwargs: Any) -> None: + """Delete add-on. + + Soft delete add-on by id. + + Once a add-on is deleted it cannot be undeleted. + + :param addon_id: Required. + :type addon_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_addons_delete_request( + addon_id=addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def publish(self, addon_id: str, **kwargs: Any) -> _models.Addon: + """Publish add-on. + + Publish a add-on version. + + :param addon_id: Required. + :type addon_id: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + _request = build_addons_publish_request( + addon_id=addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def archive(self, addon_id: str, **kwargs: Any) -> _models.Addon: + """Archive add-on version. + + Archive a add-on version. + + :param addon_id: Required. + :type addon_id: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + _request = build_addons_archive_request( + addon_id=addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SubscriptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`subscriptions` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get_expanded( + self, subscription_id: str, *, at: Optional[datetime.datetime] = None, **kwargs: Any + ) -> _models.SubscriptionExpanded: + """Get subscription. + + get_expanded. + + :param subscription_id: Required. + :type subscription_id: str + :keyword at: The time at which the subscription should be queried. If not provided the current + time is used. Default value is None. + :paramtype at: ~datetime.datetime + :return: SubscriptionExpanded. The SubscriptionExpanded is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionExpanded + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SubscriptionExpanded] = kwargs.pop("cls", None) + + _request = build_subscriptions_get_expanded_request( + subscription_id=subscription_id, + at=at, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionExpanded, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, body: _models.PlanSubscriptionCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Create subscription. + + create. + + :param body: Required. + :type body: ~openmeter._generated.models.PlanSubscriptionCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, body: _models.CustomSubscriptionCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Create subscription. + + create. + + :param body: Required. + :type body: ~openmeter._generated.models.CustomSubscriptionCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, body: "_types.SubscriptionCreate", **kwargs: Any) -> _models.Subscription: + """Create subscription. + + create. + + :param body: Is either a PlanSubscriptionCreate type or a CustomSubscriptionCreate type. + Required. + :type body: ~openmeter._generated.models.PlanSubscriptionCreate or + ~openmeter._generated.models.CustomSubscriptionCreate + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def edit( + self, + subscription_id: str, + body: _models.SubscriptionEdit, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.SubscriptionEdit + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def edit( + self, subscription_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def edit( + self, subscription_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def edit( + self, subscription_id: str, body: Union[_models.SubscriptionEdit, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is one of the following types: SubscriptionEdit, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.SubscriptionEdit or JSON or IO[bytes] + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_edit_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def change( + self, + subscription_id: str, + body: _models.PlanSubscriptionChange, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Change subscription. + + Closes a running subscription and starts a new one according to the specification. Can be used + for upgrades, downgrades, and plan changes. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanSubscriptionChange + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def change( + self, + subscription_id: str, + body: _models.CustomSubscriptionChange, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Change subscription. + + Closes a running subscription and starts a new one according to the specification. Can be used + for upgrades, downgrades, and plan changes. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomSubscriptionChange + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def change( + self, subscription_id: str, body: "_types.SubscriptionChange", **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Change subscription. + + Closes a running subscription and starts a new one according to the specification. Can be used + for upgrades, downgrades, and plan changes. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is either a PlanSubscriptionChange type or a CustomSubscriptionChange type. + Required. + :type body: ~openmeter._generated.models.PlanSubscriptionChange or + ~openmeter._generated.models.CustomSubscriptionChange + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionChangeResponseBody] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_change_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionChangeResponseBody, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def migrate( + self, + subscription_id: str, + body: _models.MigrateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.MigrateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def migrate( + self, subscription_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def migrate( + self, subscription_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def migrate( + self, subscription_id: str, body: Union[_models.MigrateRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is one of the following types: MigrateRequest, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.MigrateRequest or JSON or IO[bytes] + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionChangeResponseBody] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_migrate_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionChangeResponseBody, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def restore(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: + """Restore subscription. + + Restores a canceled subscription. Any subscription scheduled to start later will be deleted and + this subscription will be continued indefinitely. + + :param subscription_id: Required. + :type subscription_id: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + _request = build_subscriptions_restore_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def cancel( + self, + subscription_id: str, + body: _models.CancelRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CancelRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def cancel( + self, subscription_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def cancel( + self, subscription_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def cancel( + self, subscription_id: str, body: Union[_models.CancelRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is one of the following types: CancelRequest, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.CancelRequest or JSON or IO[bytes] + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_cancel_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def unschedule_cancelation(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: + """Unschedule cancelation. + + Cancels the scheduled cancelation. + + :param subscription_id: Required. + :type subscription_id: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + _request = build_subscriptions_unschedule_cancelation_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, subscription_id: str, **kwargs: Any) -> None: + """Delete subscription. + + Deletes a subscription. Only scheduled subscriptions can be deleted. + + :param subscription_id: Required. + :type subscription_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subscriptions_delete_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class SubscriptionAddonsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`subscription_addons` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, + subscription_id: str, + request: _models.SubscriptionAddonCreate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Required. + :type request: ~openmeter._generated.models.SubscriptionAddonCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, subscription_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, subscription_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create( + self, subscription_id: str, request: Union[_models.SubscriptionAddonCreate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Is one of the following types: SubscriptionAddonCreate, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.SubscriptionAddonCreate or JSON or IO[bytes] + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscription_addons_create_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list(self, subscription_id: str, **kwargs: Any) -> List[_models.SubscriptionAddon]: + """List subscription addons. + + List all addons of a subscription. In the returned list will match to a set unique by addonId. + + :param subscription_id: Required. + :type subscription_id: str + :return: list of SubscriptionAddon + :rtype: list[~openmeter._generated.models.SubscriptionAddon] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.SubscriptionAddon]] = kwargs.pop("cls", None) + + _request = build_subscription_addons_list_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.SubscriptionAddon], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, subscription_id: str, subscription_addon_id: str, **kwargs: Any) -> _models.SubscriptionAddon: + """Get subscription addon. + + Get a subscription addon by id. + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SubscriptionAddon] = kwargs.pop("cls", None) + + _request = build_subscription_addons_get_request( + subscription_id=subscription_id, + subscription_addon_id=subscription_addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: _models.SubscriptionAddonUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Required. + :type body: ~openmeter._generated.models.SubscriptionAddonUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: Union[_models.SubscriptionAddonUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Is one of the following types: SubscriptionAddonUpdate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.SubscriptionAddonUpdate or JSON or IO[bytes] + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscription_addons_update_request( + subscription_id=subscription_id, + subscription_addon_id=subscription_addon_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class EntitlementsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`entitlements` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + entitlement_type: Optional[List[Union[str, _models.EntitlementType]]] = None, + exclude_inactive: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any + ) -> "_types.ListEntitlementsResult": + """List all entitlements. + + List all entitlements for all the subjects and features. This endpoint is intended for + administrative purposes only. + To fetch the entitlements of a specific subject please use the + /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ **Deprecated**: Use ``GET /api/v2/entitlements` + <#tag/entitlements/get/api/v2/entitlements>`_ instead. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword subject: Filtering by multiple subjects. + + Usage: ``?subject=customer-1&subject=customer-2``. Default value is None. + :paramtype subject: list[str] + :keyword entitlement_type: Filtering by multiple entitlement types. + + Usage: ``?entitlementType=metered&entitlementType=boolean``. Default value is None. + :paramtype entitlement_type: list[str or ~openmeter.models.EntitlementType] + :keyword exclude_inactive: Exclude inactive entitlements in the response (those scheduled for + later or earlier). Default value is None. + :paramtype exclude_inactive: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt" and "updatedAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.EntitlementOrderBy + :return: list of EntitlementMetered or EntitlementStatic or EntitlementBoolean or + EntitlementPaginatedResponse + :rtype: list[~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean] or + ~openmeter._generated.models.EntitlementPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.ListEntitlementsResult"] = kwargs.pop("cls", None) + + _request = build_entitlements_list_request( + feature=feature, + subject=subject, + entitlement_type=entitlement_type, + exclude_inactive=exclude_inactive, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.ListEntitlementsResult", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, entitlement_id: str, **kwargs: Any) -> "_types.Entitlement": + """Get entitlement by ID. + + Get entitlement by ID. + + ⚠️ **Deprecated**: Use ``GET /api/v2/entitlements/{entitlementId}` + <#tag/entitlements/get/api/v2/entitlements/{entitlementId}>`_ instead. + + :param entitlement_id: Required. + :type entitlement_id: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + _request = build_entitlements_get_request( + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class GrantsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`grants` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> Union[List[_models.EntitlementGrant], _models.GrantPaginatedResponse]: + """List grants. + + List all grants for all the subjects and entitlements. This endpoint is intended for + administrative purposes only. + To fetch the grants of a specific entitlement please use the + /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ **Deprecated**: Use ``GET /api/v2/grants` <#tag/entitlements/get/api/v2/grants>`_ instead. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword subject: Filtering by multiple subjects. + + Usage: ``?subject=customer-1&subject=customer-2``. Default value is None. + :paramtype subject: list[str] + :keyword include_deleted: Include deleted. Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "createdAt", and "updatedAt". + Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: list of EntitlementGrant or GrantPaginatedResponse + :rtype: list[~openmeter._generated.models.EntitlementGrant] or + ~openmeter._generated.models.GrantPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Union[List[_models.EntitlementGrant], _models.GrantPaginatedResponse]] = kwargs.pop("cls", None) + + _request = build_grants_list_request( + feature=feature, + subject=subject, + include_deleted=include_deleted, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize( + Union[List[_models.EntitlementGrant], _models.GrantPaginatedResponse], response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, grant_id: str, *, at: Optional[datetime.datetime] = None, **kwargs: Any) -> None: + """Void grant. + + Voiding a grant means it is no longer valid, it doesn't take part in further balance + calculations. Voiding a grant does not retroactively take effect, meaning any usage that has + already been attributed to the grant will remain, but future usage cannot be burnt down from + the grant. For example, if you have a single grant for your metered entitlement with an initial + amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) + would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous + usage will not be affected. + + :param grant_id: Required. + :type grant_id: str + :keyword at: The time at which the grant should be voided. + Must not be in the future and must be within the current usage period of the entitlement. + Defaults to the current time if not specified. Default value is None. + :paramtype at: ~datetime.datetime + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_grants_delete_request( + grant_id=grant_id, + at=at, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class SubjectsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`subjects` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def post( + self, + subject_id_or_key: str, + entitlement: _models.EntitlementMeteredCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, + subject_id_or_key: str, + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, + subject_id_or_key: str, + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def post( + self, subject_id_or_key: str, entitlement: "_types.EntitlementCreateInputs", **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Is one of the following types: EntitlementMeteredCreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_post_request( + subject_id_or_key=subject_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list( + self, subject_id_or_key: str, *, include_deleted: Optional[bool] = None, **kwargs: Any + ) -> List["_types.Entitlement"]: + """List subject entitlements. + + List all entitlements for a subject. For checking entitlement access, use the /value endpoint + instead. + + ⚠️ **Deprecated**: Use ``GET /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :return: list of EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: list[~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List["_types.Entitlement"]] = kwargs.pop("cls", None) + + _request = build_subjects_list_request( + subject_id_or_key=subject_id_or_key, + include_deleted=include_deleted, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List["_types.Entitlement"], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> "_types.Entitlement": + """Get subject entitlement. + + Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + _request = build_subjects_get_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> None: + """Delete subject entitlement. + + Deleting an entitlement revokes access to the associated feature. As a single subject can only + have one entitlement per featureKey, when "migrating" features you have to delete the old + entitlements as well. + As access and status checks can be historical queries, deleting an entitlement populates the + deletedAt timestamp. When queried for a time before that, the entitlement is still considered + active, you cannot have retroactive changes to access, which is important for, among other + things, auditing. + + ⚠️ **Deprecated**: Use ``DELETE + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}` + <#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subjects_delete_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: _models.EntitlementMeteredCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: "_types.EntitlementCreateInputs", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Is one of the following types: EntitlementMeteredCreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_override_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get_grants( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> List[_models.EntitlementGrant]: + """List subject entitlement grants. + + List all grants issued for an entitlement. The entitlement can be defined either by its id or + featureKey. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :keyword order_by: Known values are: "id", "createdAt", and "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: list of EntitlementGrant + :rtype: list[~openmeter._generated.models.EntitlementGrant] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EntitlementGrant]] = kwargs.pop("cls", None) + + _request = build_subjects_get_grants_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + include_deleted=include_deleted, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.EntitlementGrant], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: _models.EntitlementGrantCreateInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: Union[_models.EntitlementGrantCreateInput, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Is one of the following types: EntitlementGrantCreateInput, JSON, IO[bytes] + Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInput or JSON or IO[bytes] + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EntitlementGrant] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(grant, (IOBase, bytes)): + _content = grant + else: + _content = json.dumps(grant, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_create_grant_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementGrant, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get_entitlement_value( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> _models.EntitlementValue: + """Get subject entitlement value. + + This endpoint should be used for access checks and enforcement. All entitlement types share the + hasAccess property in their value response, but multiple other properties are returned based on + the entitlement type. + + For convenience reasons, /value works with both entitlementId and featureKey. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword time: Default value is None. + :paramtype time: ~datetime.datetime + :return: EntitlementValue. The EntitlementValue is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementValue + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementValue] = kwargs.pop("cls", None) + + _request = build_subjects_get_entitlement_value_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + time=time, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementValue, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get_entitlement_history( + self, + subject_id_or_key: str, + entitlement_id: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any + ) -> _models.WindowedBalanceHistory: + """Get subject entitlement history. + + Returns historical balance and usage data for the entitlement. The queried history can span + accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by + events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information + and the list of grants that were being burnt down in that window. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :keyword window_size: Windowsize. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". + Required. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword from_parameter: Start of time range to query entitlement: date-time in RFC 3339 + format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End of time range to query entitlement: date-time in RFC 3339 format. Defaults to + now. + If not now then gets truncated to the granularity of the underlying meter. Default value is + None. + :paramtype to: ~datetime.datetime + :keyword window_time_zone: The timezone used when calculating the windows. Default value is + None. + :paramtype window_time_zone: str + :return: WindowedBalanceHistory. The WindowedBalanceHistory is compatible with MutableMapping + :rtype: ~openmeter._generated.models.WindowedBalanceHistory + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.WindowedBalanceHistory] = kwargs.pop("cls", None) + + _request = build_subjects_get_entitlement_history_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + window_size=window_size, + from_parameter=from_parameter, + to=to, + window_time_zone=window_time_zone, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.WindowedBalanceHistory, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: _models.ResetEntitlementUsageInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Required. + :type reset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Required. + :type reset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: Union[_models.ResetEntitlementUsageInput, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Is one of the following types: ResetEntitlementUsageInput, JSON, IO[bytes] + Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(reset, (IOBase, bytes)): + _content = reset + else: + _content = json.dumps(reset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_reset_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class CustomerOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get_customer_access( + self, customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any + ) -> _models.CustomerAccess: + """Get customer access. + + Get the overall access of a customer. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :return: CustomerAccess. The CustomerAccess is compatible with MutableMapping + :rtype: ~openmeter._generated.models.CustomerAccess + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.CustomerAccess] = kwargs.pop("cls", None) + + _request = build_customer_get_customer_access_request( + customer_id_or_key=customer_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CustomerAccess, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerEntitlementOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_entitlement` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get_customer_entitlement_value( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> _models.EntitlementValue: + """Get customer entitlement value. + + Checks customer access to a given feature (by key). All entitlement types share the hasAccess + property in their value response, but multiple other properties are returned based on the + entitlement type. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param feature_key: Required. + :type feature_key: str + :keyword time: Default value is None. + :paramtype time: ~datetime.datetime + :return: EntitlementValue. The EntitlementValue is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementValue + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementValue] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_get_customer_entitlement_value_request( + customer_id_or_key=customer_id_or_key, + feature_key=feature_key, + time=time, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementValue, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerStripeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_stripe` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get(self, customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> _models.StripeCustomerAppData: + """Get customer stripe app data. + + Get stripe app data for a customer. Only returns data if the customer billing profile is linked + to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.StripeCustomerAppData] = kwargs.pop("cls", None) + + _request = build_customer_stripe_get_request( + customer_id_or_key=customer_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeCustomerAppData, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: _models.StripeCustomerAppDataBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: ~openmeter._generated.models.StripeCustomerAppDataBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: Union[_models.StripeCustomerAppDataBase, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Is one of the following types: StripeCustomerAppDataBase, JSON, IO[bytes] + Required. + :type app_data: ~openmeter._generated.models.StripeCustomerAppDataBase or JSON or IO[bytes] + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.StripeCustomerAppData] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(app_data, (IOBase, bytes)): + _content = app_data + else: + _content = json.dumps(app_data, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_stripe_upsert_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeCustomerAppData, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: _models.CreateStripeCustomerPortalSessionParams, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Required. + :type params: ~openmeter._generated.models.CreateStripeCustomerPortalSessionParams + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Required. + :type params: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Required. + :type params: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: Union[_models.CreateStripeCustomerPortalSessionParams, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Is one of the following types: CreateStripeCustomerPortalSessionParams, JSON, + IO[bytes] Required. + :type params: ~openmeter._generated.models.CreateStripeCustomerPortalSessionParams or JSON or + IO[bytes] + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.StripeCustomerPortalSession] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(params, (IOBase, bytes)): + _content = params + else: + _content = json.dumps(params, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_stripe_create_portal_session_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeCustomerPortalSession, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class MarketplaceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`marketplace` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, *, page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any + ) -> _models.MarketplaceListingPaginatedResponse: + """List available apps. + + List available apps of the app marketplace. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: MarketplaceListingPaginatedResponse. The MarketplaceListingPaginatedResponse is + compatible with MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceListingPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MarketplaceListingPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_marketplace_list_request( + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceListingPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, type: Union[str, _models.AppType], **kwargs: Any) -> _models.MarketplaceListing: + """Get app details by type. + + Get a marketplace listing by type. + + :param type: Known values are: "stripe", "sandbox", and "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :return: MarketplaceListing. The MarketplaceListing is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceListing + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MarketplaceListing] = kwargs.pop("cls", None) + + _request = build_marketplace_get_request( + type=type, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceListing, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get_o_auth2_install_url( + self, type: Union[str, _models.AppType], **kwargs: Any + ) -> _models.ClientAppStartResponse: + """Get OAuth2 install URL. + + Install an app via OAuth. Returns a URL to start the OAuth 2.0 flow. + + :param type: Known values are: "stripe", "sandbox", and "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :return: ClientAppStartResponse. The ClientAppStartResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.ClientAppStartResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ClientAppStartResponse] = kwargs.pop("cls", None) + + _request = build_marketplace_get_o_auth2_install_url_request( + type=type, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ClientAppStartResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def authorize_o_auth2_install( + self, + type: Union[str, _models.AppType], + *, + state: Optional[str] = None, + code: Optional[str] = None, + error: Optional[Union[str, _models.OAuth2AuthorizationCodeGrantErrorType]] = None, + error_description: Optional[str] = None, + error_uri: Optional[str] = None, + **kwargs: Any + ) -> None: + """Install app via OAuth2. + + Authorize OAuth2 code. Verifies the OAuth code and exchanges it for a token and refresh token. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :keyword state: Required if the "state" parameter was present in the client authorization + request. + The exact value received from the client: + + Unique, randomly generated, opaque, and non-guessable string that is sent + when starting an authentication request and validated when processing the response. Default + value is None. + :paramtype state: str + :keyword code: Authorization code which the client will later exchange for an access token. + Required with the success response. Default value is None. + :paramtype code: str + :keyword error: Error code. + Required with the error response. Known values are: "invalid_request", "unauthorized_client", + "access_denied", "unsupported_response_type", "invalid_scope", "server_error", and + "temporarily_unavailable". Default value is None. + :paramtype error: str or ~openmeter.models.OAuth2AuthorizationCodeGrantErrorType + :keyword error_description: Optional human-readable text providing additional information, + used to assist the client developer in understanding the error that occurred. Default value is + None. + :paramtype error_description: str + :keyword error_uri: Optional uri identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error. Default value is None. + :paramtype error_uri: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_marketplace_authorize_o_auth2_install_request( + type=type, + state=state, + code=code, + error=error, + error_description=error_description, + error_uri=error_uri, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [303]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def install_with_api_key( + self, + type: Union[str, _models.AppType], + _: _models.InstallWithApiKeyRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: ~openmeter._generated.models.InstallWithApiKeyRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def install_with_api_key( + self, type: Union[str, _models.AppType], _: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def install_with_api_key( + self, type: Union[str, _models.AppType], _: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def install_with_api_key( + self, + type: Union[str, _models.AppType], + _: Union[_models.InstallWithApiKeyRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Is one of the following types: InstallWithApiKeyRequest, JSON, IO[bytes] Required. + :type _: ~openmeter._generated.models.InstallWithApiKeyRequest or JSON or IO[bytes] + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MarketplaceInstallResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(_, (IOBase, bytes)): + _content = _ + else: + _content = json.dumps(_, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_marketplace_install_with_api_key_request( + type=type, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceInstallResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def install( + self, + type: Union[str, _models.AppType], + _: _models.MarketplaceInstallRequestPayload, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: ~openmeter._generated.models.MarketplaceInstallRequestPayload + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def install( + self, type: Union[str, _models.AppType], _: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def install( + self, type: Union[str, _models.AppType], _: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def install( + self, + type: Union[str, _models.AppType], + _: Union[_models.MarketplaceInstallRequestPayload, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Is one of the following types: MarketplaceInstallRequestPayload, JSON, IO[bytes] + Required. + :type _: ~openmeter._generated.models.MarketplaceInstallRequestPayload or JSON or IO[bytes] + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MarketplaceInstallResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(_, (IOBase, bytes)): + _content = _ + else: + _content = json.dumps(_, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_marketplace_install_request( + type=type, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceInstallResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class AppCustomInvoicingOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`app_custom_invoicing` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def draft_syncronized( + self, + invoice_id: str, + body: _models.CustomInvoicingDraftSynchronizedRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomInvoicingDraftSynchronizedRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def draft_syncronized( + self, invoice_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def draft_syncronized( + self, invoice_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def draft_syncronized( + self, + invoice_id: str, + body: Union[_models.CustomInvoicingDraftSynchronizedRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Is one of the following types: CustomInvoicingDraftSynchronizedRequest, JSON, + IO[bytes] Required. + :type body: ~openmeter._generated.models.CustomInvoicingDraftSynchronizedRequest or JSON or + IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_custom_invoicing_draft_syncronized_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def finalized( + self, + invoice_id: str, + body: _models.CustomInvoicingFinalizedRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomInvoicingFinalizedRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def finalized( + self, invoice_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def finalized( + self, invoice_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def finalized( + self, invoice_id: str, body: Union[_models.CustomInvoicingFinalizedRequest, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Is one of the following types: CustomInvoicingFinalizedRequest, JSON, IO[bytes] + Required. + :type body: ~openmeter._generated.models.CustomInvoicingFinalizedRequest or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_custom_invoicing_finalized_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def payment_status( + self, + invoice_id: str, + body: _models.CustomInvoicingUpdatePaymentStatusRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomInvoicingUpdatePaymentStatusRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def payment_status( + self, invoice_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def payment_status( + self, invoice_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def payment_status( + self, + invoice_id: str, + body: Union[_models.CustomInvoicingUpdatePaymentStatusRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Is one of the following types: CustomInvoicingUpdatePaymentStatusRequest, JSON, + IO[bytes] Required. + :type body: ~openmeter._generated.models.CustomInvoicingUpdatePaymentStatusRequest or JSON or + IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_custom_invoicing_payment_status_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class EventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`events` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + client_id: Optional[str] = None, + ingested_at_from: Optional[datetime.datetime] = None, + ingested_at_to: Optional[datetime.datetime] = None, + id: Optional[str] = None, + subject: Optional[str] = None, + customer_id: Optional[List[str]] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + limit: Optional[int] = None, + **kwargs: Any + ) -> List[_models.IngestedEvent]: + """List ingested events. + + List ingested events within a time range. + + If the from query param is not provided it defaults to last 72 hours. + + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword ingested_at_from: Start date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype ingested_at_from: ~datetime.datetime + :keyword ingested_at_to: End date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype ingested_at_to: ~datetime.datetime + :keyword id: The event ID. + + Accepts partial ID. Default value is None. + :paramtype id: str + :keyword subject: The event subject. + + Accepts partial subject. Default value is None. + :paramtype subject: str + :keyword customer_id: The event customer ID. Default value is None. + :paramtype customer_id: list[str] + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype to: ~datetime.datetime + :keyword limit: Number of events to return. Default value is None. + :paramtype limit: int + :return: list of IngestedEvent + :rtype: list[~openmeter._generated.models.IngestedEvent] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.IngestedEvent]] = kwargs.pop("cls", None) + + _request = build_events_list_request( + client_id=client_id, + ingested_at_from=ingested_at_from, + ingested_at_to=ingested_at_to, + id=id, + subject=subject, + customer_id=customer_id, + from_parameter=from_parameter, + to=to, + limit=limit, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.IngestedEvent], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def ingest_event( + self, body: _models.Event, *, content_type: str = "application/cloudevents+json", **kwargs: Any + ) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Required. + :type body: ~openmeter._generated.models.Event + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def ingest_event( + self, body: JSON, *, content_type: str = "application/cloudevents+json", **kwargs: Any + ) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def ingest_event( + self, body: IO[bytes], *, content_type: str = "application/cloudevents+json", **kwargs: Any + ) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/cloudevents+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def ingest_event(self, body: Union[_models.Event, JSON, IO[bytes]], **kwargs: Any) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Is one of the following types: Event, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.Event or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/cloudevents+json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_events_ingest_event_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def ingest_events( + self, body: List[_models.Event], *, content_type: str = "application/cloudevents-batch+json", **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Required. + :type body: list[~openmeter._generated.models.Event] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents-batch+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def ingest_events( + self, body: List[JSON], *, content_type: str = "application/cloudevents-batch+json", **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Required. + :type body: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents-batch+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def ingest_events( + self, body: IO[bytes], *, content_type: str = "application/cloudevents-batch+json", **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/cloudevents-batch+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def ingest_events(self, body: Union[List[_models.Event], List[JSON], IO[bytes]], **kwargs: Any) -> None: + """ingest_events. + + :param body: Is one of the following types: [Event], [JSON], IO[bytes] Required. + :type body: list[~openmeter._generated.models.Event] or list[JSON] or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/cloudevents-batch+json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_events_ingest_events_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def ingest_events_json( + self, body: _models.Event, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """ingest_events_json. + + :param body: Required. + :type body: ~openmeter._generated.models.Event + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def ingest_events_json( + self, body: List[_models.Event], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """ingest_events_json. + + :param body: Required. + :type body: list[~openmeter._generated.models.Event] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def ingest_events_json(self, body: "_types.IngestEventsBody", **kwargs: Any) -> None: + """ingest_events_json. + + :param body: Is either a Event type or a [Event] type. Required. + :type body: ~openmeter._generated.models.Event or list[~openmeter._generated.models.Event] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, _models.Event): + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + elif isinstance(body, list): + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_events_ingest_events_json_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class EventsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`events_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + limit: Optional[int] = None, + client_id: Optional[str] = None, + filter: Optional[_models.ListRequestFilter] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.IngestedEvent"]: + """List ingested events. + + List ingested events with advanced filtering and cursor pagination. + + :keyword limit: The limit of the pagination. Default value is None. + :paramtype limit: int + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword filter: The filter for the events encoded as JSON string. Default value is None. + :paramtype filter: ~openmeter._generated.models.ListRequestFilter + :return: An iterator like instance of IngestedEvent + :rtype: ~corehttp.paging.AsyncItemPaged[~openmeter._generated.models.IngestedEvent] + :raises ~corehttp.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.IngestedEvent]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(_continuation_token=None): + + _request = build_events_v2_list_request( + cursor=_continuation_token, + limit=limit, + client_id=client_id, + filter=filter, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.IngestedEvent], + deserialized.get("items", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextCursor") or None, AsyncList(list_of_elem) + + async def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class MetersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`meters` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.MeterOrderBy]] = None, + include_deleted: Optional[bool] = None, + **kwargs: Any + ) -> List[_models.Meter]: + """List meters. + + List meters. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "key", "name", "aggregation", + "createdAt", and "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.MeterOrderBy + :keyword include_deleted: Include deleted meters. Default value is None. + :paramtype include_deleted: bool + :return: list of Meter + :rtype: list[~openmeter._generated.models.Meter] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Meter]] = kwargs.pop("cls", None) + + _request = build_meters_list_request( + page=page, + page_size=page_size, + order=order, + order_by=order_by, + include_deleted=include_deleted, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Meter], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, meter_id_or_slug: str, **kwargs: Any) -> _models.Meter: + """Get meter. + + Get a meter by ID or slug. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Meter] = kwargs.pop("cls", None) + + _request = build_meters_get_request( + meter_id_or_slug=meter_id_or_slug, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Meter, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, meter: _models.MeterCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Required. + :type meter: ~openmeter._generated.models.MeterCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create(self, meter: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Required. + :type meter: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create(self, meter: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Required. + :type meter: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, meter: Union[_models.MeterCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Is one of the following types: MeterCreate, JSON, IO[bytes] Required. + :type meter: ~openmeter._generated.models.MeterCreate or JSON or IO[bytes] + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Meter] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(meter, (IOBase, bytes)): + _content = meter + else: + _content = json.dumps(meter, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_meters_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Meter, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + meter_id_or_slug: str, + meter: _models.MeterUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Required. + :type meter: ~openmeter._generated.models.MeterUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, meter_id_or_slug: str, meter: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Required. + :type meter: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, meter_id_or_slug: str, meter: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Required. + :type meter: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, meter_id_or_slug: str, meter: Union[_models.MeterUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Is one of the following types: MeterUpdate, JSON, IO[bytes] Required. + :type meter: ~openmeter._generated.models.MeterUpdate or JSON or IO[bytes] + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Meter] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(meter, (IOBase, bytes)): + _content = meter + else: + _content = json.dumps(meter, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_meters_update_request( + meter_id_or_slug=meter_id_or_slug, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Meter, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, meter_id_or_slug: str, **kwargs: Any) -> None: + """Delete meter. + + Delete a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_meters_delete_request( + meter_id_or_slug=meter_id_or_slug, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def query_json( + self, + meter_id_or_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[List[str]] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + Query meter for usage. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword subject: Filtering by multiple subjects. + + For example: ?subject=subject-1&subject=subject-2. Default value is None. + :paramtype subject: list[str] + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MeterQueryResult] = kwargs.pop("cls", None) + + _request = build_meters_query_json_request( + meter_id_or_slug=meter_id_or_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + subject=subject, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MeterQueryResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + async def query_csv( + self, + meter_id_or_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[List[str]] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> str: + """query_csv. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword subject: Filtering by multiple subjects. + + For example: ?subject=subject-1&subject=subject-2. Default value is None. + :paramtype subject: list[str] + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_meters_query_csv_request( + meter_id_or_slug=meter_id_or_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + subject=subject, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def query( + self, + meter_id_or_slug: str, + request: _models.MeterQueryRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Required. + :type request: ~openmeter._generated.models.MeterQueryRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def query( + self, meter_id_or_slug: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def query( + self, meter_id_or_slug: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def query( + self, meter_id_or_slug: str, request: Union[_models.MeterQueryRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Is one of the following types: MeterQueryRequest, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.MeterQueryRequest or JSON or IO[bytes] + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MeterQueryResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_meters_query_request( + meter_id_or_slug=meter_id_or_slug, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MeterQueryResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + async def query_csv_post(self, meter_id_or_slug: str, **kwargs: Any) -> str: + """query_csv_post. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_meters_query_csv_post_request( + meter_id_or_slug=meter_id_or_slug, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + async def list_subjects( + self, + meter_id_or_slug: str, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> List[str]: + """List meter subjects. + + List subjects for a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. Defaults to the beginning of time. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :return: list of str + :rtype: list[str] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[str]] = kwargs.pop("cls", None) + + _request = build_meters_list_subjects_request( + meter_id_or_slug=meter_id_or_slug, + from_parameter=from_parameter, + to=to, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[str], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list_group_by_values( + self, + meter_id_or_slug: str, + group_by_key: str, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> List[str]: + """List meter group by values. + + List meter group by values. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param group_by_key: Required. + :type group_by_key: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. Defaults to 24 hours ago. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :return: list of str + :rtype: list[str] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[str]] = kwargs.pop("cls", None) + + _request = build_meters_list_group_by_values_request( + meter_id_or_slug=meter_id_or_slug, + group_by_key=group_by_key, + from_parameter=from_parameter, + to=to, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[str], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SubjectsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`subjects` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list(self, **kwargs: Any) -> List[_models.Subject]: + """List subjects. + + List subjects. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Subject]] = kwargs.pop("cls", None) + + _request = build_subjects_list_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Subject], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, subject_id_or_key: str, **kwargs: Any) -> _models.Subject: + """Get subject. + + Get subject by ID or key. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :return: Subject. The Subject is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subject + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Subject] = kwargs.pop("cls", None) + + _request = build_subjects_get_request( + subject_id_or_key=subject_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subject, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def upsert( + self, subject: List[_models.SubjectUpsert], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Required. + :type subject: list[~openmeter._generated.models.SubjectUpsert] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert( + self, subject: List[JSON], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Required. + :type subject: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert( + self, subject: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Required. + :type subject: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def upsert( + self, subject: Union[List[_models.SubjectUpsert], List[JSON], IO[bytes]], **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Is one of the following types: [SubjectUpsert], [JSON], IO[bytes] Required. + :type subject: list[~openmeter._generated.models.SubjectUpsert] or list[JSON] or IO[bytes] + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.Subject]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(subject, (IOBase, bytes)): + _content = subject + else: + _content = json.dumps(subject, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_upsert_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Subject], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, subject_id_or_key: str, **kwargs: Any) -> None: + """Delete subject. + + Delete subject by ID or key. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subjects_delete_request( + subject_id_or_key=subject_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class DebugOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`debug` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def metrics(self, **kwargs: Any) -> str: + """Get event metrics. + + Returns debug metrics (in OpenMetrics format) like the number of ingested events since + mindnight UTC. + + The OpenMetrics Counter(s) reset every day at midnight UTC. + + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_debug_metrics_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class NotificationChannelsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`notification_channels` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + include_deleted: Optional[bool] = None, + include_disabled: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationChannelOrderBy]] = None, + **kwargs: Any + ) -> _models.NotificationChannelPaginatedResponse: + """List notification channels. + + List all notification channels. + + :keyword include_deleted: Include deleted notification channels in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword include_disabled: Include disabled notification channels in response. + + Usage: ``?includeDisabled=false``. Default value is None. + :paramtype include_disabled: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "type", "createdAt", and + "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.NotificationChannelOrderBy + :return: NotificationChannelPaginatedResponse. The NotificationChannelPaginatedResponse is + compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationChannelPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationChannelPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_notification_channels_list_request( + include_deleted=include_deleted, + include_disabled=include_disabled, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationChannelPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, + request: _models.NotificationChannelWebhookCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationChannel": + """Create a notification channel. + + Create a new notification channel. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create( + self, request: "_types.NotificationChannelCreateRequest", **kwargs: Any + ) -> "_types.NotificationChannel": + """Create a notification channel. + + Create a new notification channel. + + :param request: Is one of the following types: NotificationChannelWebhookCreateRequest + Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationChannel"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_channels_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationChannel", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + channel_id: str, + request: _models.NotificationChannelWebhookCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationChannel": + """Update a notification channel. + + Update notification channel. + + :param channel_id: Required. + :type channel_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, channel_id: str, request: "_types.NotificationChannelCreateRequest", **kwargs: Any + ) -> "_types.NotificationChannel": + """Update a notification channel. + + Update notification channel. + + :param channel_id: Required. + :type channel_id: str + :param request: Is one of the following types: NotificationChannelWebhookCreateRequest + Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationChannel"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_channels_update_request( + channel_id=channel_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationChannel", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, channel_id: str, **kwargs: Any) -> "_types.NotificationChannel": + """Get notification channel. + + Get a notification channel by id. + + :param channel_id: Required. + :type channel_id: str + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.NotificationChannel"] = kwargs.pop("cls", None) + + _request = build_notification_channels_get_request( + channel_id=channel_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationChannel", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, channel_id: str, **kwargs: Any) -> None: + """Delete a notification channel. + + Soft delete notification channel by id. + + Once a notification channel is deleted it cannot be undeleted. + + :param channel_id: Required. + :type channel_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_notification_channels_delete_request( + channel_id=channel_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class NotificationRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`notification_rules` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + include_deleted: Optional[bool] = None, + include_disabled: Optional[bool] = None, + feature: Optional[List[str]] = None, + channel: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationRuleOrderBy]] = None, + **kwargs: Any + ) -> _models.NotificationRulePaginatedResponse: + """List notification rules. + + List all notification rules. + + :keyword include_deleted: Include deleted notification rules in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword include_disabled: Include disabled notification rules in response. + + Usage: ``?includeDisabled=false``. Default value is None. + :paramtype include_disabled: bool + :keyword feature: Filtering by multiple feature ids/keys. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword channel: Filtering by multiple notifiaction channel ids. + + Usage: ``?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3``. Default + value is None. + :paramtype channel: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "type", "createdAt", and + "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.NotificationRuleOrderBy + :return: NotificationRulePaginatedResponse. The NotificationRulePaginatedResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.NotificationRulePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationRulePaginatedResponse] = kwargs.pop("cls", None) + + _request = build_notification_rules_list_request( + include_deleted=include_deleted, + include_disabled=include_disabled, + feature=feature, + channel=channel, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationRulePaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, + request: _models.NotificationRuleBalanceThresholdCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + request: _models.NotificationRuleEntitlementResetCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + request: _models.NotificationRuleInvoiceCreatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, + request: _models.NotificationRuleInvoiceUpdatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, request: "_types.NotificationRuleCreateRequest", **kwargs: Any) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Is one of the following types: NotificationRuleBalanceThresholdCreateRequest, + NotificationRuleEntitlementResetCreateRequest, NotificationRuleInvoiceCreatedCreateRequest, + NotificationRuleInvoiceUpdatedCreateRequest Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest or + ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationRule"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_rules_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationRule", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + rule_id: str, + request: _models.NotificationRuleBalanceThresholdCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + rule_id: str, + request: _models.NotificationRuleEntitlementResetCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + rule_id: str, + request: _models.NotificationRuleInvoiceCreatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + rule_id: str, + request: _models.NotificationRuleInvoiceUpdatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, rule_id: str, request: "_types.NotificationRuleCreateRequest", **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Is one of the following types: NotificationRuleBalanceThresholdCreateRequest, + NotificationRuleEntitlementResetCreateRequest, NotificationRuleInvoiceCreatedCreateRequest, + NotificationRuleInvoiceUpdatedCreateRequest Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest or + ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationRule"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_rules_update_request( + rule_id=rule_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationRule", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, rule_id: str, **kwargs: Any) -> "_types.NotificationRule": + """Get notification rule. + + Get a notification rule by id. + + :param rule_id: Required. + :type rule_id: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.NotificationRule"] = kwargs.pop("cls", None) + + _request = build_notification_rules_get_request( + rule_id=rule_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationRule", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, rule_id: str, **kwargs: Any) -> None: + """Delete a notification rule. + + Soft delete notification rule by id. + + Once a notification rule is deleted it cannot be undeleted. + + :param rule_id: Required. + :type rule_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_notification_rules_delete_request( + rule_id=rule_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def test(self, rule_id: str, **kwargs: Any) -> _models.NotificationEvent: + """Test notification rule. + + Test a notification rule by sending a test event with random data. + + :param rule_id: Required. + :type rule_id: str + :return: NotificationEvent. The NotificationEvent is compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationEvent + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationEvent] = kwargs.pop("cls", None) + + _request = build_notification_rules_test_request( + rule_id=rule_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationEvent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class NotificationEventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`notification_events` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + rule: Optional[List[str]] = None, + channel: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationEventOrderBy]] = None, + **kwargs: Any + ) -> _models.NotificationEventPaginatedResponse: + """List notification events. + + List all notification events. + + :keyword from_parameter: Start date-time in RFC 3339 format. + Inclusive. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + Inclusive. Default value is None. + :paramtype to: ~datetime.datetime + :keyword feature: Filtering by multiple feature ids or keys. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword subject: Filtering by multiple subject ids or keys. + + Usage: ``?subject=subject-1&subject=subject-2``. Default value is None. + :paramtype subject: list[str] + :keyword rule: Filtering by multiple rule ids. + + Usage: ``?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5``. Default value is + None. + :paramtype rule: list[str] + :keyword channel: Filtering by multiple channel ids. + + Usage: ``?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J``. Default + value is None. + :paramtype channel: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id" and "createdAt". Default value is + None. + :paramtype order_by: str or ~openmeter.models.NotificationEventOrderBy + :return: NotificationEventPaginatedResponse. The NotificationEventPaginatedResponse is + compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationEventPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationEventPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_notification_events_list_request( + from_parameter=from_parameter, + to=to, + feature=feature, + subject=subject, + rule=rule, + channel=channel, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationEventPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, event_id: str, **kwargs: Any) -> _models.NotificationEvent: + """Get notification event. + + Get a notification event by id. + + :param event_id: Required. + :type event_id: str + :return: NotificationEvent. The NotificationEvent is compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationEvent + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationEvent] = kwargs.pop("cls", None) + + _request = build_notification_events_get_request( + event_id=event_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationEvent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def resend( + self, + event_id: str, + request: _models.NotificationEventResendRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationEventResendRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def resend( + self, event_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def resend( + self, event_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def resend( + self, event_id: str, request: Union[_models.NotificationEventResendRequest, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Is one of the following types: NotificationEventResendRequest, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.NotificationEventResendRequest or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_events_resend_request( + event_id=event_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class EntitlementsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`entitlements_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + feature: Optional[List[str]] = None, + customer_keys: Optional[List[str]] = None, + customer_ids: Optional[List[str]] = None, + entitlement_type: Optional[List[Union[str, _models.EntitlementType]]] = None, + exclude_inactive: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any + ) -> _models.EntitlementV2PaginatedResponse: + """List all entitlements. + + List all entitlements for all the customers and features. This endpoint is intended for + administrative purposes only. To fetch the entitlements of a specific subject please use the + /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword customer_keys: Filtering by multiple customers. + + Usage: ``?customerKeys=customer-1&customerKeys=customer-3``. Default value is None. + :paramtype customer_keys: list[str] + :keyword customer_ids: Filtering by multiple customers. + + Usage: ``?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9``. + Default value is None. + :paramtype customer_ids: list[str] + :keyword entitlement_type: Filtering by multiple entitlement types. + + Usage: ``?entitlementType=metered&entitlementType=boolean``. Default value is None. + :paramtype entitlement_type: list[str or ~openmeter.models.EntitlementType] + :keyword exclude_inactive: Exclude inactive entitlements in the response (those scheduled for + later or earlier). Default value is None. + :paramtype exclude_inactive: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt" and "updatedAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.EntitlementOrderBy + :return: EntitlementV2PaginatedResponse. The EntitlementV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.EntitlementV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_entitlements_v2_list_request( + feature=feature, + customer_keys=customer_keys, + customer_ids=customer_ids, + entitlement_type=entitlement_type, + exclude_inactive=exclude_inactive, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get(self, entitlement_id: str, **kwargs: Any) -> "_types.EntitlementV2": + """Get entitlement by ID. + + Get entitlement by ID. + + :param entitlement_id: Required. + :type entitlement_id: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + _request = build_entitlements_v2_get_request( + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerEntitlementsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_entitlements_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementMeteredV2CreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: "_types.EntitlementV2CreateInputs", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Is one of the following types: EntitlementMeteredV2CreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlements_v2_post_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any + ) -> _models.EntitlementV2PaginatedResponse: + """List customer entitlements. + + List all entitlements for a customer. For checking entitlement access, use the /value endpoint + instead. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt" and "updatedAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.EntitlementOrderBy + :return: EntitlementV2PaginatedResponse. The EntitlementV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.EntitlementV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_entitlements_v2_list_request( + customer_id_or_key=customer_id_or_key, + include_deleted=include_deleted, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get( + self, customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any + ) -> "_types.EntitlementV2": + """Get customer entitlement. + + Get entitlement by feature key. For checking entitlement access, use the /value endpoint + instead. If featureKey is used, the entitlement is resolved for the current timestamp. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + _request = build_customer_entitlements_v2_get_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete( + self, customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any + ) -> None: + """Delete customer entitlement. + + Deleting an entitlement revokes access to the associated feature. As a single customer can only + have one entitlement per featureKey, when "migrating" features you have to delete the old + entitlements as well. As access and status checks can be historical queries, deleting an + entitlement populates the deletedAt timestamp. When queried for a time before that, the + entitlement is still considered active, you cannot have retroactive changes to access, which is + important for, among other things, auditing. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customer_entitlements_v2_delete_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementMeteredV2CreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: "_types.EntitlementV2CreateInputs", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Is one of the following types: EntitlementMeteredV2CreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlements_v2_override_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerEntitlementV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_entitlement_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get_grants( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> _models.GrantV2PaginatedResponse: + """List customer entitlement grants. + + List all grants issued for an entitlement. The entitlement can be defined either by its id or + featureKey. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "createdAt", and "updatedAt". + Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: GrantV2PaginatedResponse. The GrantV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.GrantV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.GrantV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_v2_get_grants_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + include_deleted=include_deleted, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.GrantV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: _models.EntitlementGrantCreateInputV2, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInputV2 + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: Union[_models.EntitlementGrantCreateInputV2, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Is one of the following types: EntitlementGrantCreateInputV2, JSON, IO[bytes] + Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInputV2 or JSON or IO[bytes] + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EntitlementGrantV2] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(grant, (IOBase, bytes)): + _content = grant + else: + _content = json.dumps(grant, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlement_v2_create_customer_entitlement_grant_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementGrantV2, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get_customer_entitlement_value( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> _models.EntitlementValueV2: + """Get customer entitlement value. + + Checks customer access to a given feature (by key). All entitlement types share the hasAccess + property in their value response, but multiple other properties are returned based on the + entitlement type. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword time: Default value is None. + :paramtype time: ~datetime.datetime + :return: EntitlementValueV2. The EntitlementValueV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementValueV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementValueV2] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_v2_get_customer_entitlement_value_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + time=time, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementValueV2, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get_customer_entitlement_history( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any + ) -> _models.WindowedBalanceHistory: + """Get customer entitlement history. + + Returns historical balance and usage data for the entitlement. The queried history can span + accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by + events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information + and the list of grants that were being burnt down in that window. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword window_size: Windowsize. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". + Required. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword from_parameter: Start of time range to query entitlement: date-time in RFC 3339 + format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End of time range to query entitlement: date-time in RFC 3339 format. Defaults to + now. + If not now then gets truncated to the granularity of the underlying meter. Default value is + None. + :paramtype to: ~datetime.datetime + :keyword window_time_zone: The timezone used when calculating the windows. Default value is + None. + :paramtype window_time_zone: str + :return: WindowedBalanceHistory. The WindowedBalanceHistory is compatible with MutableMapping + :rtype: ~openmeter._generated.models.WindowedBalanceHistory + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.WindowedBalanceHistory] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_v2_get_customer_entitlement_history_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + window_size=window_size, + from_parameter=from_parameter, + to=to, + window_time_zone=window_time_zone, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.WindowedBalanceHistory, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: _models.ResetEntitlementUsageInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Required. + :type reset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Required. + :type reset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: Union[_models.ResetEntitlementUsageInput, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Is one of the following types: ResetEntitlementUsageInput, JSON, IO[bytes] + Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(reset, (IOBase, bytes)): + _content = reset + else: + _content = json.dumps(reset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlement_v2_reset_customer_entitlement_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class GrantsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`grants_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + feature: Optional[List[str]] = None, + customer: Optional[List["_types.ULIDOrExternalKey"]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> _models.GrantV2PaginatedResponse: + """List grants. + + List all grants for all the customers and entitlements. This endpoint is intended for + administrative purposes only. To fetch the grants of a specific entitlement please use the + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword customer: Filtering by multiple customers (either by ID or key). + + Usage: ``?customer=customer-1&customer=customer-2``. Default value is None. + :paramtype customer: list[str or str] + :keyword include_deleted: Include deleted. Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "createdAt", and "updatedAt". + Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: GrantV2PaginatedResponse. The GrantV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.GrantV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.GrantV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_grants_v2_list_request( + feature=feature, + customer=customer, + include_deleted=include_deleted, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.GrantV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BillingProfilesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`billing_profiles` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( + self, + *, + include_archived: Optional[bool] = None, + expand: Optional[List[Union[str, _models.BillingProfileExpand]]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.BillingProfileOrderBy]] = None, + **kwargs: Any + ) -> _models.BillingProfilePaginatedResponse: + """List billing profiles. + + List all billing profiles matching the specified filters. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing + profile + will be included in the response. + + :keyword include_archived: Default value is None. + :paramtype include_archived: bool + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileExpand] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt", "updatedAt", "default", + and "name". Default value is None. + :paramtype order_by: str or ~openmeter.models.BillingProfileOrderBy + :return: BillingProfilePaginatedResponse. The BillingProfilePaginatedResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfilePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfilePaginatedResponse] = kwargs.pop("cls", None) + + _request = build_billing_profiles_list_request( + include_archived=include_archived, + expand=expand, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfilePaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create( + self, profile: _models.BillingProfileCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Required. + :type profile: ~openmeter._generated.models.BillingProfileCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, profile: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Required. + :type profile: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, profile: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Required. + :type profile: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create( + self, profile: Union[_models.BillingProfileCreate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Is one of the following types: BillingProfileCreate, JSON, IO[bytes] Required. + :type profile: ~openmeter._generated.models.BillingProfileCreate or JSON or IO[bytes] + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(profile, (IOBase, bytes)): + _content = profile + else: + _content = json.dumps(profile, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_billing_profiles_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfile, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, id: str, **kwargs: Any) -> None: + """Delete a billing profile. + + Delete a billing profile by id. + + Only such billing profiles can be deleted that are: + + * not the default one + * not pinned to any customer using customer overrides + * only have finalized invoices. + + :param id: Required. + :type id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_billing_profiles_delete_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + async def get( + self, id: str, *, expand: Optional[List[Union[str, _models.BillingProfileExpand]]] = None, **kwargs: Any + ) -> _models.BillingProfile: + """Get a billing profile. + + Get a billing profile by id. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing + profile + will be included in the response. + + :param id: Required. + :type id: str + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileExpand] + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None) + + _request = build_billing_profiles_get_request( + id=id, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfile, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + id: str, + profile: _models.BillingProfileReplaceUpdateWithWorkflow, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Required. + :type profile: ~openmeter._generated.models.BillingProfileReplaceUpdateWithWorkflow + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, id: str, profile: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Required. + :type profile: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, id: str, profile: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Required. + :type profile: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update( + self, id: str, profile: Union[_models.BillingProfileReplaceUpdateWithWorkflow, JSON, IO[bytes]], **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Is one of the following types: BillingProfileReplaceUpdateWithWorkflow, JSON, + IO[bytes] Required. + :type profile: ~openmeter._generated.models.BillingProfileReplaceUpdateWithWorkflow or JSON or + IO[bytes] + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(profile, (IOBase, bytes)): + _content = profile + else: + _content = json.dumps(profile, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_billing_profiles_update_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfile, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerOverridesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_overrides` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list( # pylint: disable=too-many-locals + self, + *, + billing_profile: Optional[List[str]] = None, + customers_without_pinned_profile: Optional[bool] = None, + include_all_customers: Optional[bool] = None, + customer_id: Optional[List[str]] = None, + customer_name: Optional[str] = None, + customer_key: Optional[str] = None, + customer_primary_email: Optional[str] = None, + expand: Optional[List[Union[str, _models.BillingProfileCustomerOverrideExpand]]] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.BillingProfileCustomerOverrideOrderBy]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse: + """List customer overrides. + + List customer overrides using the specified filters. + + The response will include the customer override values and the merged billing profile values. + + If the includeAllCustomers is set to true, the list contains all customers. This mode is + useful for getting the current effective billing workflow settings for all users regardless + if they have customer orverrides or not. + + :keyword billing_profile: Filter by billing profile. Default value is None. + :paramtype billing_profile: list[str] + :keyword customers_without_pinned_profile: Only return customers without pinned billing + profiles. This implicitly sets includeAllCustomers to true. Default value is None. + :paramtype customers_without_pinned_profile: bool + :keyword include_all_customers: Include customers without customer overrides. + + If set to false only the customers specifically associated with a billing profile will be + returned. + + If set to true, in case of the default billing profile, all customers will be returned. + Default value is None. + :paramtype include_all_customers: bool + :keyword customer_id: Filter by customer id. Default value is None. + :paramtype customer_id: list[str] + :keyword customer_name: Filter by customer name. Default value is None. + :paramtype customer_name: str + :keyword customer_key: Filter by customer key. Default value is None. + :paramtype customer_key: str + :keyword customer_primary_email: Filter by customer primary email. Default value is None. + :paramtype customer_primary_email: str + :keyword expand: Expand the response with additional details. Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileCustomerOverrideExpand] + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "customerId", "customerName", + "customerKey", "customerPrimaryEmail", and "customerCreatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.BillingProfileCustomerOverrideOrderBy + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: BillingProfileCustomerOverrideWithDetailsPaginatedResponse. The + BillingProfileCustomerOverrideWithDetailsPaginatedResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_overrides_list_request( + billing_profile=billing_profile, + customers_without_pinned_profile=customers_without_pinned_profile, + include_all_customers=include_all_customers, + customer_id=customer_id, + customer_name=customer_name, + customer_key=customer_key, + customer_primary_email=customer_primary_email, + expand=expand, + order=order, + order_by=order_by, + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize( + _models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse, response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def upsert( + self, + customer_id: str, + request: _models.BillingProfileCustomerOverrideCreate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: ~openmeter._generated.models.BillingProfileCustomerOverrideCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert( + self, customer_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def upsert( + self, customer_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def upsert( + self, + customer_id: str, + request: Union[_models.BillingProfileCustomerOverrideCreate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Is one of the following types: BillingProfileCustomerOverrideCreate, JSON, + IO[bytes] Required. + :type request: ~openmeter._generated.models.BillingProfileCustomerOverrideCreate or JSON or + IO[bytes] + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BillingProfileCustomerOverrideWithDetails] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_overrides_upsert_request( + customer_id=customer_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfileCustomerOverrideWithDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def get( + self, + customer_id: str, + *, + expand: Optional[List[Union[str, _models.BillingProfileCustomerOverrideExpand]]] = None, + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Get a customer override. + + Get a customer override by customer id. + + The response will include the customer override values and the merged billing profile values. + + If the customer override is not found, the default billing profile's values are returned. This + behavior + allows for getting a merged profile regardless of the customer override existence. + + :param customer_id: Required. + :type customer_id: str + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileCustomerOverrideExpand] + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfileCustomerOverrideWithDetails] = kwargs.pop("cls", None) + + _request = build_customer_overrides_get_request( + customer_id=customer_id, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfileCustomerOverrideWithDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete(self, customer_id: str, **kwargs: Any) -> None: + """Delete a customer override. + + Delete a customer override by customer id. + + This will remove the customer override and the customer will be subject to the default + billing profile's settings again. + + :param customer_id: Required. + :type customer_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customer_overrides_delete_request( + customer_id=customer_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class InvoicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`invoices` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def invoice_pending_lines_action( + self, request: _models.InvoicePendingLinesActionInput, *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Required. + :type request: ~openmeter._generated.models.InvoicePendingLinesActionInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def invoice_pending_lines_action( + self, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def invoice_pending_lines_action( + self, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def invoice_pending_lines_action( + self, request: Union[_models.InvoicePendingLinesActionInput, JSON, IO[bytes]], **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Is one of the following types: InvoicePendingLinesActionInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.InvoicePendingLinesActionInput or JSON or IO[bytes] + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.Invoice]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_invoices_invoice_pending_lines_action_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Invoice], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list( # pylint: disable=too-many-locals + self, + *, + statuses: Optional[List[Union[str, _models.InvoiceStatus]]] = None, + extended_statuses: Optional[List[str]] = None, + issued_after: Optional[datetime.datetime] = None, + issued_before: Optional[datetime.datetime] = None, + period_start_after: Optional[datetime.datetime] = None, + period_start_before: Optional[datetime.datetime] = None, + created_after: Optional[datetime.datetime] = None, + created_before: Optional[datetime.datetime] = None, + expand: Optional[List[Union[str, _models.InvoiceExpand]]] = None, + customers: Optional[List[str]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.InvoiceOrderBy]] = None, + **kwargs: Any + ) -> _models.InvoicePaginatedResponse: + """List invoices. + + List invoices based on the specified filters. + + The expand option can be used to include additional information (besides the invoice header and + totals) + in the response. For example by adding the expand=lines option the invoice lines will be + included in the response. + + Gathering invoices will always show the current usage calculated on the fly. + + :keyword statuses: Filter by the invoice status. Default value is None. + :paramtype statuses: list[str or ~openmeter.models.InvoiceStatus] + :keyword extended_statuses: Filter by invoice extended statuses. Default value is None. + :paramtype extended_statuses: list[str] + :keyword issued_after: Filter by invoice issued time. + Inclusive. Default value is None. + :paramtype issued_after: ~datetime.datetime + :keyword issued_before: Filter by invoice issued time. + Inclusive. Default value is None. + :paramtype issued_before: ~datetime.datetime + :keyword period_start_after: Filter by period start time. + Inclusive. Default value is None. + :paramtype period_start_after: ~datetime.datetime + :keyword period_start_before: Filter by period start time. + Inclusive. Default value is None. + :paramtype period_start_before: ~datetime.datetime + :keyword created_after: Filter by invoice created time. + Inclusive. Default value is None. + :paramtype created_after: ~datetime.datetime + :keyword created_before: Filter by invoice created time. + Inclusive. Default value is None. + :paramtype created_before: ~datetime.datetime + :keyword expand: What parts of the list output to expand in listings. Default value is None. + :paramtype expand: list[str or ~openmeter.models.InvoiceExpand] + :keyword customers: Filter by customer ID. Default value is None. + :paramtype customers: list[str] + :keyword include_deleted: Include deleted invoices. Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "customer.name", "issuedAt", "status", + "createdAt", "updatedAt", and "periodStart". Default value is None. + :paramtype order_by: str or ~openmeter.models.InvoiceOrderBy + :return: InvoicePaginatedResponse. The InvoicePaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.InvoicePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.InvoicePaginatedResponse] = kwargs.pop("cls", None) + + _request = build_invoices_list_request( + statuses=statuses, + extended_statuses=extended_statuses, + issued_after=issued_after, + issued_before=issued_before, + period_start_after=period_start_after, + period_start_before=period_start_before, + created_after=created_after, + created_before=created_before, + expand=expand, + customers=customers, + include_deleted=include_deleted, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.InvoicePaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class InvoiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`invoice` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get_invoice( + self, + invoice_id: str, + *, + expand: Optional[List[Union[str, _models.InvoiceExpand]]] = None, + include_deleted_lines: Optional[bool] = None, + **kwargs: Any + ) -> _models.Invoice: + """Get an invoice. + + Get an invoice by ID. + + Gathering invoices will always show the current usage calculated on the fly. + + :param invoice_id: Required. + :type invoice_id: str + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.InvoiceExpand] + :keyword include_deleted_lines: Default value is None. + :paramtype include_deleted_lines: bool + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_get_invoice_request( + invoice_id=invoice_id, + expand=expand, + include_deleted_lines=include_deleted_lines, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def delete_invoice(self, invoice_id: str, **kwargs: Any) -> None: + """Delete an invoice. + + Delete an invoice + + Only invoices that are in the draft (or earlier) status can be deleted. + + Invoices that are post finalization can only be voided. + + :param invoice_id: Required. + :type invoice_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_invoice_delete_invoice_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def update_invoice( + self, + invoice_id: str, + request: _models.InvoiceReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: ~openmeter._generated.models.InvoiceReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update_invoice( + self, invoice_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def update_invoice( + self, invoice_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def update_invoice( + self, invoice_id: str, request: Union[_models.InvoiceReplaceUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Is one of the following types: InvoiceReplaceUpdate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.InvoiceReplaceUpdate or JSON or IO[bytes] + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_invoice_update_invoice_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def recalculate_tax_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Recalculate an invoice's tax amounts. + + Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + + Note: charges might apply, depending on the tax provider. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_recalculate_tax_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def approve_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Send the invoice to the customer. + + Approve an invoice and start executing the payment workflow. + + This call instantly sends the invoice to the customer using the configured billing profile app. + + This call is valid in two invoice statuses: + + * `draft`: the invoice will be sent to the customer, the invluce state becomes issued + * `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes + issued. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_approve_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def void_invoice_action( + self, + invoice_id: str, + request: _models.VoidInvoiceActionInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: ~openmeter._generated.models.VoidInvoiceActionInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def void_invoice_action( + self, invoice_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def void_invoice_action( + self, invoice_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def void_invoice_action( + self, invoice_id: str, request: Union[_models.VoidInvoiceActionInput, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Is one of the following types: VoidInvoiceActionInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.VoidInvoiceActionInput or JSON or IO[bytes] + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_invoice_void_invoice_action_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def advance_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Advance the invoice's state to the next status. + + Advance the invoice's state to the next status. + + The call doesn't "approve the invoice", it only advances the invoice to the next status if the + transition would be automatic. + + The action can be called when the invoice's statusDetails' actions field contain the "advance" + action. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_advance_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def retry_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Retry advancing the invoice after a failed attempt. + + Retry advancing the invoice after a failed attempt. + + The action can be called when the invoice's statusDetails' actions field contain the "retry" + action. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_retry_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def snapshot_quantities_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Snapshot quantities for usage based line items. + + Snapshot quantities for usage based line items. + + This call will snapshot the quantities for all usage based line items in the invoice. + + This call is only valid in ``draft.waiting_for_collection`` status, where the collection period + can be skipped using this action. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_snapshot_quantities_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerInvoiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`customer_invoice` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def simulate_invoice( + self, + customer_id: str, + request: _models.InvoiceSimulationInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: ~openmeter._generated.models.InvoiceSimulationInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def simulate_invoice( + self, customer_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def simulate_invoice( + self, customer_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def simulate_invoice( + self, customer_id: str, request: Union[_models.InvoiceSimulationInput, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Is one of the following types: InvoiceSimulationInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.InvoiceSimulationInput or JSON or IO[bytes] + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_invoice_simulate_invoice_request( + customer_id=customer_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_pending_invoice_line( + self, + customer_id: str, + request: _models.InvoicePendingLineCreateInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: ~openmeter._generated.models.InvoicePendingLineCreateInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_pending_invoice_line( + self, customer_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create_pending_invoice_line( + self, customer_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create_pending_invoice_line( + self, customer_id: str, request: Union[_models.InvoicePendingLineCreateInput, JSON, IO[bytes]], **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Is one of the following types: InvoicePendingLineCreateInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.InvoicePendingLineCreateInput or JSON or IO[bytes] + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.InvoicePendingLineCreateResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_invoice_create_pending_invoice_line_request( + customer_id=customer_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.InvoicePendingLineCreateResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ProgressOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`progress` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def get_progress(self, id: str, **kwargs: Any) -> _models.Progress: + """Get progress. + + Get progress. + + :param id: Required. + :type id: str + :return: Progress. The Progress is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Progress + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Progress] = kwargs.pop("cls", None) + + _request = build_progress_get_progress_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Progress, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CurrenciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`currencies` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def list_currencies(self, **kwargs: Any) -> List[_models.Currency]: + """List supported currencies. + + List all supported currencies. + + :return: list of Currency + :rtype: list[~openmeter._generated.models.Currency] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Currency]] = kwargs.pop("cls", None) + + _request = build_currencies_list_currencies_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Currency], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PortalPortalTokensOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`portal_tokens` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + async def create( + self, token: _models.PortalToken, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Required. + :type token: ~openmeter._generated.models.PortalToken + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, token: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Required. + :type token: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, token: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Required. + :type token: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def create(self, token: Union[_models.PortalToken, JSON, IO[bytes]], **kwargs: Any) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Is one of the following types: PortalToken, JSON, IO[bytes] Required. + :type token: ~openmeter._generated.models.PortalToken or JSON or IO[bytes] + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PortalToken] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(token, (IOBase, bytes)): + _content = token + else: + _content = json.dumps(token, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_portal_portal_tokens_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PortalToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def list(self, *, limit: Optional[int] = None, **kwargs: Any) -> List[_models.PortalToken]: + """List consumer portal tokens. + + List tokens. + + :keyword limit: Default value is None. + :paramtype limit: int + :return: list of PortalToken + :rtype: list[~openmeter._generated.models.PortalToken] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PortalToken]] = kwargs.pop("cls", None) + + _request = build_portal_portal_tokens_list_request( + limit=limit, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.PortalToken], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def invalidate( + self, + *, + content_type: str = "application/json", + id: Optional[str] = None, + subject: Optional[str] = None, + **kwargs: Any + ) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword id: Invalidate a portal token by ID. Default value is None. + :paramtype id: str + :keyword subject: Invalidate all portal tokens for a subject. Default value is None. + :paramtype subject: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def invalidate(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + async def invalidate(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + async def invalidate( + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + id: Optional[str] = None, + subject: Optional[str] = None, + **kwargs: Any + ) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword id: Invalidate a portal token by ID. Default value is None. + :paramtype id: str + :keyword subject: Invalidate all portal tokens for a subject. Default value is None. + :paramtype subject: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + if body is _Unset: + body = {"id": id, "subject": subject} + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_portal_portal_tokens_invalidate_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class PortalPortalMetersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.aio.OpenMeterClient`'s + :attr:`portal_meters` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + async def query_json( + self, + meter_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + Query meter for consumer portal. This endpoint is publicly exposable to consumers. + + :param meter_slug: Required. + :type meter_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MeterQueryResult] = kwargs.pop("cls", None) + + _request = build_portal_portal_meters_query_json_request( + meter_slug=meter_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MeterQueryResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + async def query_csv( + self, + meter_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> str: + """Query meter. + + Query meter for consumer portal. This endpoint is publicly exposable to consumers. + + :param meter_slug: Required. + :type meter_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_portal_portal_meters_query_csv_request( + meter_slug=meter_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore diff --git a/api/client/python/openmeter/_generated/aio/operations/_patch.py b/api/client/python/openmeter/_generated/aio/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b208fb11fbc2e1955c43275aa4e1482dec7e5d6f --- /dev/null +++ b/api/client/python/openmeter/_generated/aio/operations/_patch.py @@ -0,0 +1,17 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/api/client/python/openmeter/_generated/models/__init__.py b/api/client/python/openmeter/_generated/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6f038d7f8d3711bbc5029c2d9b277788dabffc --- /dev/null +++ b/api/client/python/openmeter/_generated/models/__init__.py @@ -0,0 +1,758 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + Addon, + AddonCreate, + AddonReplaceUpdate, + Address, + Alignment, + Annotations, + AppCapability, + AppPaginatedResponse, + AppReference, + BadRequestProblemResponse, + BalanceHistoryWindow, + BillingCustomerProfile, + BillingDiscountPercentage, + BillingDiscountUsage, + BillingDiscounts, + BillingInvoiceCustomerExtendedDetails, + BillingParty, + BillingPartyReplaceUpdate, + BillingPartyTaxIdentity, + BillingProfile, + BillingProfileAppReferences, + BillingProfileApps, + BillingProfileAppsCreate, + BillingProfileCreate, + BillingProfileCustomerOverride, + BillingProfileCustomerOverrideCreate, + BillingProfileCustomerOverrideWithDetails, + BillingProfileCustomerOverrideWithDetailsPaginatedResponse, + BillingProfilePaginatedResponse, + BillingProfileReplaceUpdateWithWorkflow, + BillingWorkflow, + BillingWorkflowCollectionAlignmentAnchored, + BillingWorkflowCollectionAlignmentSubscription, + BillingWorkflowCollectionSettings, + BillingWorkflowCreate, + BillingWorkflowInvoicingSettings, + BillingWorkflowPaymentSettings, + BillingWorkflowTaxSettings, + CancelRequest, + CheckoutSessionCustomTextAfterSubmitParams, + CheckoutSessionCustomTextParamsAfterSubmit, + CheckoutSessionCustomTextParamsShippingAddress, + CheckoutSessionCustomTextParamsSubmit, + CheckoutSessionCustomTextParamsTermsOfServiceAcceptance, + ClientAppStartResponse, + ConflictProblemResponse, + CreateCheckoutSessionTaxIdCollection, + CreateStripeCheckoutSessionConsentCollection, + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement, + CreateStripeCheckoutSessionCustomerUpdate, + CreateStripeCheckoutSessionRequest, + CreateStripeCheckoutSessionRequestOptions, + CreateStripeCheckoutSessionResult, + CreateStripeCustomerPortalSessionParams, + CreditNoteOriginalInvoiceRef, + Currency, + CustomInvoicingApp, + CustomInvoicingAppReplaceUpdate, + CustomInvoicingCustomerAppData, + CustomInvoicingDraftSynchronizedRequest, + CustomInvoicingFinalizedInvoicingRequest, + CustomInvoicingFinalizedPaymentRequest, + CustomInvoicingFinalizedRequest, + CustomInvoicingLineDiscountExternalIdMapping, + CustomInvoicingLineExternalIdMapping, + CustomInvoicingSyncResult, + CustomInvoicingTaxConfig, + CustomInvoicingUpdatePaymentStatusRequest, + CustomPlanInput, + CustomSubscriptionChange, + CustomSubscriptionCreate, + Customer, + CustomerAccess, + CustomerAppDataPaginatedResponse, + CustomerCreate, + CustomerId, + CustomerKey, + CustomerPaginatedResponse, + CustomerReplaceUpdate, + CustomerUsageAttribution, + DiscountPercentage, + DiscountReasonMaximumSpend, + DiscountReasonRatecardPercentage, + DiscountReasonRatecardUsage, + DiscountUsage, + Discounts, + DynamicPriceWithCommitments, + EditSubscriptionAddItem, + EditSubscriptionAddPhase, + EditSubscriptionRemoveItem, + EditSubscriptionRemovePhase, + EditSubscriptionStretchPhase, + EditSubscriptionUnscheduleEdit, + EntitlementBoolean, + EntitlementBooleanCreateInputs, + EntitlementBooleanV2, + EntitlementGrant, + EntitlementGrantCreateInput, + EntitlementGrantCreateInputV2, + EntitlementGrantV2, + EntitlementMetered, + EntitlementMeteredCreateInputs, + EntitlementMeteredV2, + EntitlementMeteredV2CreateInputs, + EntitlementPaginatedResponse, + EntitlementStatic, + EntitlementStaticCreateInputs, + EntitlementStaticV2, + EntitlementV2PaginatedResponse, + EntitlementValue, + EntitlementValueV2, + ErrorExtension, + Event, + EventDeliveryAttemptResponse, + ExpirationPeriod, + Feature, + FeatureCreateInputs, + FeatureLLMUnitCost, + FeatureLLMUnitCostPricing, + FeatureManualUnitCost, + FeatureMeta, + FeaturePaginatedResponse, + FilterIDExact, + FilterString, + FilterTime, + FlatPrice, + FlatPriceWithPaymentTerm, + ForbiddenProblemResponse, + GrantBurnDownHistorySegment, + GrantPaginatedResponse, + GrantUsageRecord, + GrantV2PaginatedResponse, + IDResource, + IngestedEvent, + InstallWithApiKeyRequest, + InternalServerErrorProblemResponse, + Invoice, + InvoiceAppExternalIds, + InvoiceAvailableActionDetails, + InvoiceAvailableActionInvoiceDetails, + InvoiceAvailableActions, + InvoiceDetailedLine, + InvoiceDetailedLineRateCard, + InvoiceGenericDocumentRef, + InvoiceLine, + InvoiceLineAmountDiscount, + InvoiceLineAppExternalIds, + InvoiceLineCreditAllocation, + InvoiceLineDiscounts, + InvoiceLineReplaceUpdate, + InvoiceLineSubscriptionReference, + InvoiceLineTaxItem, + InvoiceLineUsageDiscount, + InvoicePaginatedResponse, + InvoicePaymentTerms, + InvoicePendingLineCreate, + InvoicePendingLineCreateInput, + InvoicePendingLineCreateResponse, + InvoicePendingLinesActionFiltersInput, + InvoicePendingLinesActionInput, + InvoiceReference, + InvoiceReplaceUpdate, + InvoiceSimulationInput, + InvoiceSimulationLine, + InvoiceStatusDetails, + InvoiceTotals, + InvoiceUsageBasedRateCard, + InvoiceWorkflowInvoicingSettingsReplaceUpdate, + InvoiceWorkflowReplaceUpdate, + InvoiceWorkflowSettings, + InvoiceWorkflowSettingsReplaceUpdate, + IssueAfterReset, + ListRequestFilter, + MarketplaceInstallRequestPayload, + MarketplaceInstallResponse, + MarketplaceListing, + MarketplaceListingPaginatedResponse, + Metadata, + Meter, + MeterCreate, + MeterQueryRequest, + MeterQueryResult, + MeterQueryRow, + MeterUpdate, + MigrateRequest, + NotFoundProblemResponse, + NotificationChannelMeta, + NotificationChannelPaginatedResponse, + NotificationChannelWebhook, + NotificationChannelWebhookCreateRequest, + NotificationEvent, + NotificationEventBalanceThresholdPayload, + NotificationEventBalanceThresholdPayloadData, + NotificationEventDeliveryAttempt, + NotificationEventDeliveryStatus, + NotificationEventEntitlementValuePayloadBase, + NotificationEventInvoiceCreatedPayload, + NotificationEventInvoiceUpdatedPayload, + NotificationEventPaginatedResponse, + NotificationEventResendRequest, + NotificationEventResetPayload, + NotificationRuleBalanceThreshold, + NotificationRuleBalanceThresholdCreateRequest, + NotificationRuleBalanceThresholdValue, + NotificationRuleEntitlementReset, + NotificationRuleEntitlementResetCreateRequest, + NotificationRuleInvoiceCreated, + NotificationRuleInvoiceCreatedCreateRequest, + NotificationRuleInvoiceUpdated, + NotificationRuleInvoiceUpdatedCreateRequest, + NotificationRulePaginatedResponse, + OmitPropertiesResourceCreateModel, + PackagePriceWithCommitments, + PaymentDueDate, + PaymentTermDueDate, + PaymentTermInstant, + Period, + Plan, + PlanAddon, + PlanAddonCreate, + PlanAddonPaginatedResponse, + PlanAddonReplaceUpdate, + PlanCreate, + PlanPhase, + PlanReference, + PlanReferenceInput, + PlanReplaceUpdate, + PlanSubscriptionChange, + PlanSubscriptionCreate, + PortalToken, + PreconditionFailedProblemResponse, + PriceTier, + ProRatingConfig, + Progress, + RateCardBooleanEntitlement, + RateCardFlatFee, + RateCardMeteredEntitlement, + RateCardStaticEntitlement, + RateCardUsageBased, + RecurringPeriod, + RecurringPeriodCreateInput, + RecurringPeriodV2, + ResetEntitlementUsageInput, + SandboxApp, + SandboxAppReplaceUpdate, + SandboxCustomerAppData, + ServiceUnavailableProblemResponse, + StripeAPIKeyInput, + StripeApp, + StripeAppReplaceUpdate, + StripeCustomerAppData, + StripeCustomerAppDataBase, + StripeCustomerPortalSession, + StripeTaxConfig, + StripeWebhookEvent, + StripeWebhookEventData, + StripeWebhookResponse, + Subject, + SubjectUpsert, + Subscription, + SubscriptionAddon, + SubscriptionAddonAddon, + SubscriptionAddonCreate, + SubscriptionAddonCreateAddon, + SubscriptionAddonRateCard, + SubscriptionAddonTimelineSegment, + SubscriptionAddonUpdate, + SubscriptionAlignment, + SubscriptionBadRequestErrorResponse, + SubscriptionBadRequestErrorResponseExtensions, + SubscriptionChangeResponseBody, + SubscriptionConflictErrorResponse, + SubscriptionEdit, + SubscriptionExpanded, + SubscriptionItem, + SubscriptionItemIncluded, + SubscriptionPaginatedResponse, + SubscriptionPhaseCreate, + SubscriptionPhaseExpanded, + TaxConfig, + TieredPriceWithCommitments, + UnauthorizedProblemResponse, + UnexpectedProblemResponse, + UnitPrice, + UnitPriceWithCommitments, + ValidationError, + ValidationIssue, + VoidInvoiceAction, + VoidInvoiceActionInput, + VoidInvoiceActionLineOverride, + VoidInvoiceLineDiscardAction, + VoidInvoiceLinePendingAction, + WindowedBalanceHistory, +) + +from ._enums import ( # type: ignore + AddonInstanceType, + AddonOrderBy, + AddonStatus, + AppCapabilityType, + AppStatus, + AppType, + BillingCollectionAlignment, + BillingProfileCustomerOverrideExpand, + BillingProfileCustomerOverrideOrderBy, + BillingProfileExpand, + BillingProfileOrderBy, + BillingSettlementMode, + BillingWorkflowInvoicingSubscriptionEndProrationMode, + CheckoutSessionUIMode, + CollectionMethod, + CreateCheckoutSessionTaxIdCollectionRequired, + CreateStripeCheckoutSessionBillingAddressCollection, + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition, + CreateStripeCheckoutSessionConsentCollectionPromotions, + CreateStripeCheckoutSessionConsentCollectionTermsOfService, + CreateStripeCheckoutSessionCustomerUpdateBehavior, + CreateStripeCheckoutSessionRedirectOnCompletion, + CustomInvoicingPaymentTrigger, + CustomerExpand, + CustomerOrderBy, + CustomerSubscriptionOrderBy, + DiscountReasonType, + EditOp, + EntitlementOrderBy, + EntitlementType, + ExpirationDuration, + FeatureOrderBy, + FeatureUnitCostType, + GrantOrderBy, + InstallMethod, + InvoiceDetailedLineCostCategory, + InvoiceDocumentRefType, + InvoiceExpand, + InvoiceLineManagedBy, + InvoiceLineStatus, + InvoiceLineTaxBehavior, + InvoiceLineTypes, + InvoiceOrderBy, + InvoiceStatus, + InvoiceType, + MeasureUsageFromPreset, + MeterAggregation, + MeterOrderBy, + NotificationChannelOrderBy, + NotificationChannelType, + NotificationEventDeliveryStatusState, + NotificationEventOrderBy, + NotificationEventType, + NotificationRuleBalanceThresholdValueType, + NotificationRuleOrderBy, + OAuth2AuthorizationCodeGrantErrorType, + PaymentTermType, + PlanAddonOrderBy, + PlanOrderBy, + PlanStatus, + PricePaymentTerm, + PriceType, + ProRatingMode, + RateCardType, + RecurringPeriodIntervalEnum, + RemovePhaseShifting, + SortOrder, + StripeCheckoutSessionMode, + SubscriptionStatus, + SubscriptionTimingEnum, + TaxBehavior, + TieredPriceMode, + ValidationIssueSeverity, + VoidInvoiceLineActionType, + WindowSize, +) +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Addon", + "AddonCreate", + "AddonReplaceUpdate", + "Address", + "Alignment", + "Annotations", + "AppCapability", + "AppPaginatedResponse", + "AppReference", + "BadRequestProblemResponse", + "BalanceHistoryWindow", + "BillingCustomerProfile", + "BillingDiscountPercentage", + "BillingDiscountUsage", + "BillingDiscounts", + "BillingInvoiceCustomerExtendedDetails", + "BillingParty", + "BillingPartyReplaceUpdate", + "BillingPartyTaxIdentity", + "BillingProfile", + "BillingProfileAppReferences", + "BillingProfileApps", + "BillingProfileAppsCreate", + "BillingProfileCreate", + "BillingProfileCustomerOverride", + "BillingProfileCustomerOverrideCreate", + "BillingProfileCustomerOverrideWithDetails", + "BillingProfileCustomerOverrideWithDetailsPaginatedResponse", + "BillingProfilePaginatedResponse", + "BillingProfileReplaceUpdateWithWorkflow", + "BillingWorkflow", + "BillingWorkflowCollectionAlignmentAnchored", + "BillingWorkflowCollectionAlignmentSubscription", + "BillingWorkflowCollectionSettings", + "BillingWorkflowCreate", + "BillingWorkflowInvoicingSettings", + "BillingWorkflowPaymentSettings", + "BillingWorkflowTaxSettings", + "CancelRequest", + "CheckoutSessionCustomTextAfterSubmitParams", + "CheckoutSessionCustomTextParamsAfterSubmit", + "CheckoutSessionCustomTextParamsShippingAddress", + "CheckoutSessionCustomTextParamsSubmit", + "CheckoutSessionCustomTextParamsTermsOfServiceAcceptance", + "ClientAppStartResponse", + "ConflictProblemResponse", + "CreateCheckoutSessionTaxIdCollection", + "CreateStripeCheckoutSessionConsentCollection", + "CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement", + "CreateStripeCheckoutSessionCustomerUpdate", + "CreateStripeCheckoutSessionRequest", + "CreateStripeCheckoutSessionRequestOptions", + "CreateStripeCheckoutSessionResult", + "CreateStripeCustomerPortalSessionParams", + "CreditNoteOriginalInvoiceRef", + "Currency", + "CustomInvoicingApp", + "CustomInvoicingAppReplaceUpdate", + "CustomInvoicingCustomerAppData", + "CustomInvoicingDraftSynchronizedRequest", + "CustomInvoicingFinalizedInvoicingRequest", + "CustomInvoicingFinalizedPaymentRequest", + "CustomInvoicingFinalizedRequest", + "CustomInvoicingLineDiscountExternalIdMapping", + "CustomInvoicingLineExternalIdMapping", + "CustomInvoicingSyncResult", + "CustomInvoicingTaxConfig", + "CustomInvoicingUpdatePaymentStatusRequest", + "CustomPlanInput", + "CustomSubscriptionChange", + "CustomSubscriptionCreate", + "Customer", + "CustomerAccess", + "CustomerAppDataPaginatedResponse", + "CustomerCreate", + "CustomerId", + "CustomerKey", + "CustomerPaginatedResponse", + "CustomerReplaceUpdate", + "CustomerUsageAttribution", + "DiscountPercentage", + "DiscountReasonMaximumSpend", + "DiscountReasonRatecardPercentage", + "DiscountReasonRatecardUsage", + "DiscountUsage", + "Discounts", + "DynamicPriceWithCommitments", + "EditSubscriptionAddItem", + "EditSubscriptionAddPhase", + "EditSubscriptionRemoveItem", + "EditSubscriptionRemovePhase", + "EditSubscriptionStretchPhase", + "EditSubscriptionUnscheduleEdit", + "EntitlementBoolean", + "EntitlementBooleanCreateInputs", + "EntitlementBooleanV2", + "EntitlementGrant", + "EntitlementGrantCreateInput", + "EntitlementGrantCreateInputV2", + "EntitlementGrantV2", + "EntitlementMetered", + "EntitlementMeteredCreateInputs", + "EntitlementMeteredV2", + "EntitlementMeteredV2CreateInputs", + "EntitlementPaginatedResponse", + "EntitlementStatic", + "EntitlementStaticCreateInputs", + "EntitlementStaticV2", + "EntitlementV2PaginatedResponse", + "EntitlementValue", + "EntitlementValueV2", + "ErrorExtension", + "Event", + "EventDeliveryAttemptResponse", + "ExpirationPeriod", + "Feature", + "FeatureCreateInputs", + "FeatureLLMUnitCost", + "FeatureLLMUnitCostPricing", + "FeatureManualUnitCost", + "FeatureMeta", + "FeaturePaginatedResponse", + "FilterIDExact", + "FilterString", + "FilterTime", + "FlatPrice", + "FlatPriceWithPaymentTerm", + "ForbiddenProblemResponse", + "GrantBurnDownHistorySegment", + "GrantPaginatedResponse", + "GrantUsageRecord", + "GrantV2PaginatedResponse", + "IDResource", + "IngestedEvent", + "InstallWithApiKeyRequest", + "InternalServerErrorProblemResponse", + "Invoice", + "InvoiceAppExternalIds", + "InvoiceAvailableActionDetails", + "InvoiceAvailableActionInvoiceDetails", + "InvoiceAvailableActions", + "InvoiceDetailedLine", + "InvoiceDetailedLineRateCard", + "InvoiceGenericDocumentRef", + "InvoiceLine", + "InvoiceLineAmountDiscount", + "InvoiceLineAppExternalIds", + "InvoiceLineCreditAllocation", + "InvoiceLineDiscounts", + "InvoiceLineReplaceUpdate", + "InvoiceLineSubscriptionReference", + "InvoiceLineTaxItem", + "InvoiceLineUsageDiscount", + "InvoicePaginatedResponse", + "InvoicePaymentTerms", + "InvoicePendingLineCreate", + "InvoicePendingLineCreateInput", + "InvoicePendingLineCreateResponse", + "InvoicePendingLinesActionFiltersInput", + "InvoicePendingLinesActionInput", + "InvoiceReference", + "InvoiceReplaceUpdate", + "InvoiceSimulationInput", + "InvoiceSimulationLine", + "InvoiceStatusDetails", + "InvoiceTotals", + "InvoiceUsageBasedRateCard", + "InvoiceWorkflowInvoicingSettingsReplaceUpdate", + "InvoiceWorkflowReplaceUpdate", + "InvoiceWorkflowSettings", + "InvoiceWorkflowSettingsReplaceUpdate", + "IssueAfterReset", + "ListRequestFilter", + "MarketplaceInstallRequestPayload", + "MarketplaceInstallResponse", + "MarketplaceListing", + "MarketplaceListingPaginatedResponse", + "Metadata", + "Meter", + "MeterCreate", + "MeterQueryRequest", + "MeterQueryResult", + "MeterQueryRow", + "MeterUpdate", + "MigrateRequest", + "NotFoundProblemResponse", + "NotificationChannelMeta", + "NotificationChannelPaginatedResponse", + "NotificationChannelWebhook", + "NotificationChannelWebhookCreateRequest", + "NotificationEvent", + "NotificationEventBalanceThresholdPayload", + "NotificationEventBalanceThresholdPayloadData", + "NotificationEventDeliveryAttempt", + "NotificationEventDeliveryStatus", + "NotificationEventEntitlementValuePayloadBase", + "NotificationEventInvoiceCreatedPayload", + "NotificationEventInvoiceUpdatedPayload", + "NotificationEventPaginatedResponse", + "NotificationEventResendRequest", + "NotificationEventResetPayload", + "NotificationRuleBalanceThreshold", + "NotificationRuleBalanceThresholdCreateRequest", + "NotificationRuleBalanceThresholdValue", + "NotificationRuleEntitlementReset", + "NotificationRuleEntitlementResetCreateRequest", + "NotificationRuleInvoiceCreated", + "NotificationRuleInvoiceCreatedCreateRequest", + "NotificationRuleInvoiceUpdated", + "NotificationRuleInvoiceUpdatedCreateRequest", + "NotificationRulePaginatedResponse", + "OmitPropertiesResourceCreateModel", + "PackagePriceWithCommitments", + "PaymentDueDate", + "PaymentTermDueDate", + "PaymentTermInstant", + "Period", + "Plan", + "PlanAddon", + "PlanAddonCreate", + "PlanAddonPaginatedResponse", + "PlanAddonReplaceUpdate", + "PlanCreate", + "PlanPhase", + "PlanReference", + "PlanReferenceInput", + "PlanReplaceUpdate", + "PlanSubscriptionChange", + "PlanSubscriptionCreate", + "PortalToken", + "PreconditionFailedProblemResponse", + "PriceTier", + "ProRatingConfig", + "Progress", + "RateCardBooleanEntitlement", + "RateCardFlatFee", + "RateCardMeteredEntitlement", + "RateCardStaticEntitlement", + "RateCardUsageBased", + "RecurringPeriod", + "RecurringPeriodCreateInput", + "RecurringPeriodV2", + "ResetEntitlementUsageInput", + "SandboxApp", + "SandboxAppReplaceUpdate", + "SandboxCustomerAppData", + "ServiceUnavailableProblemResponse", + "StripeAPIKeyInput", + "StripeApp", + "StripeAppReplaceUpdate", + "StripeCustomerAppData", + "StripeCustomerAppDataBase", + "StripeCustomerPortalSession", + "StripeTaxConfig", + "StripeWebhookEvent", + "StripeWebhookEventData", + "StripeWebhookResponse", + "Subject", + "SubjectUpsert", + "Subscription", + "SubscriptionAddon", + "SubscriptionAddonAddon", + "SubscriptionAddonCreate", + "SubscriptionAddonCreateAddon", + "SubscriptionAddonRateCard", + "SubscriptionAddonTimelineSegment", + "SubscriptionAddonUpdate", + "SubscriptionAlignment", + "SubscriptionBadRequestErrorResponse", + "SubscriptionBadRequestErrorResponseExtensions", + "SubscriptionChangeResponseBody", + "SubscriptionConflictErrorResponse", + "SubscriptionEdit", + "SubscriptionExpanded", + "SubscriptionItem", + "SubscriptionItemIncluded", + "SubscriptionPaginatedResponse", + "SubscriptionPhaseCreate", + "SubscriptionPhaseExpanded", + "TaxConfig", + "TieredPriceWithCommitments", + "UnauthorizedProblemResponse", + "UnexpectedProblemResponse", + "UnitPrice", + "UnitPriceWithCommitments", + "ValidationError", + "ValidationIssue", + "VoidInvoiceAction", + "VoidInvoiceActionInput", + "VoidInvoiceActionLineOverride", + "VoidInvoiceLineDiscardAction", + "VoidInvoiceLinePendingAction", + "WindowedBalanceHistory", + "AddonInstanceType", + "AddonOrderBy", + "AddonStatus", + "AppCapabilityType", + "AppStatus", + "AppType", + "BillingCollectionAlignment", + "BillingProfileCustomerOverrideExpand", + "BillingProfileCustomerOverrideOrderBy", + "BillingProfileExpand", + "BillingProfileOrderBy", + "BillingSettlementMode", + "BillingWorkflowInvoicingSubscriptionEndProrationMode", + "CheckoutSessionUIMode", + "CollectionMethod", + "CreateCheckoutSessionTaxIdCollectionRequired", + "CreateStripeCheckoutSessionBillingAddressCollection", + "CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition", + "CreateStripeCheckoutSessionConsentCollectionPromotions", + "CreateStripeCheckoutSessionConsentCollectionTermsOfService", + "CreateStripeCheckoutSessionCustomerUpdateBehavior", + "CreateStripeCheckoutSessionRedirectOnCompletion", + "CustomInvoicingPaymentTrigger", + "CustomerExpand", + "CustomerOrderBy", + "CustomerSubscriptionOrderBy", + "DiscountReasonType", + "EditOp", + "EntitlementOrderBy", + "EntitlementType", + "ExpirationDuration", + "FeatureOrderBy", + "FeatureUnitCostType", + "GrantOrderBy", + "InstallMethod", + "InvoiceDetailedLineCostCategory", + "InvoiceDocumentRefType", + "InvoiceExpand", + "InvoiceLineManagedBy", + "InvoiceLineStatus", + "InvoiceLineTaxBehavior", + "InvoiceLineTypes", + "InvoiceOrderBy", + "InvoiceStatus", + "InvoiceType", + "MeasureUsageFromPreset", + "MeterAggregation", + "MeterOrderBy", + "NotificationChannelOrderBy", + "NotificationChannelType", + "NotificationEventDeliveryStatusState", + "NotificationEventOrderBy", + "NotificationEventType", + "NotificationRuleBalanceThresholdValueType", + "NotificationRuleOrderBy", + "OAuth2AuthorizationCodeGrantErrorType", + "PaymentTermType", + "PlanAddonOrderBy", + "PlanOrderBy", + "PlanStatus", + "PricePaymentTerm", + "PriceType", + "ProRatingMode", + "RateCardType", + "RecurringPeriodIntervalEnum", + "RemovePhaseShifting", + "SortOrder", + "StripeCheckoutSessionMode", + "SubscriptionStatus", + "SubscriptionTimingEnum", + "TaxBehavior", + "TieredPriceMode", + "ValidationIssueSeverity", + "VoidInvoiceLineActionType", + "WindowSize", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/api/client/python/openmeter/_generated/models/_enums.py b/api/client/python/openmeter/_generated/models/_enums.py new file mode 100644 index 0000000000000000000000000000000000000000..7035201dd8aa12475161bccd334e5dc09cc73cca --- /dev/null +++ b/api/client/python/openmeter/_generated/models/_enums.py @@ -0,0 +1,920 @@ +# coding=utf-8 + +from enum import Enum +from corehttp.utils import CaseInsensitiveEnumMeta + + +class AddonInstanceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The instanceType of the add-on. Single instance add-ons can be added to subscription only once + while add-ons with multiple type can be added more then once. + """ + + SINGLE = "single" + """SINGLE.""" + MULTIPLE = "multiple" + """MULTIPLE.""" + + +class AddonOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for add-ons.""" + + ID = "id" + """ID.""" + KEY = "key" + """KEY.""" + VERSION = "version" + """VERSION.""" + CREATED_AT = "created_at" + """CREATED_AT.""" + UPDATED_AT = "updated_at" + """UPDATED_AT.""" + + +class AddonStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the add-on defined by the effectiveFrom and effectiveTo properties.""" + + DRAFT = "draft" + """DRAFT.""" + ACTIVE = "active" + """ACTIVE.""" + ARCHIVED = "archived" + """ARCHIVED.""" + + +class AppCapabilityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """App capability type.""" + + REPORT_USAGE = "reportUsage" + """The app can report aggregated usage.""" + REPORT_EVENTS = "reportEvents" + """The app can report raw events.""" + CALCULATE_TAX = "calculateTax" + """The app can calculate tax.""" + INVOICE_CUSTOMERS = "invoiceCustomers" + """The app can invoice customers.""" + COLLECT_PAYMENTS = "collectPayments" + """The app can collect payments.""" + + +class AppStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """App installed status.""" + + READY = "ready" + """The app is ready to be used.""" + UNAUTHORIZED = "unauthorized" + """The app is unauthorized. This usually happens when the app's credentials are revoked or + expired. To resolve this, the user must re-authorize the app.""" + + +class AppType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the app.""" + + STRIPE = "stripe" + """STRIPE.""" + SANDBOX = "sandbox" + """SANDBOX.""" + CUSTOM_INVOICING = "custom_invoicing" + """CUSTOM_INVOICING.""" + + +class BillingCollectionAlignment(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Collection alignment.""" + + SUBSCRIPTION = "subscription" + """Align the collection to the start of the subscription period.""" + ANCHORED = "anchored" + """Align the collection to the anchor time and cadence.""" + + +class BillingProfileCustomerOverrideExpand(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """CustomerOverrideExpand specifies the parts of the profile to expand.""" + + APPS = "apps" + """APPS.""" + CUSTOMER = "customer" + """CUSTOMER.""" + + +class BillingProfileCustomerOverrideOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for customers.""" + + CUSTOMER_ID = "customerId" + """CUSTOMER_ID.""" + CUSTOMER_NAME = "customerName" + """CUSTOMER_NAME.""" + CUSTOMER_KEY = "customerKey" + """CUSTOMER_KEY.""" + CUSTOMER_PRIMARY_EMAIL = "customerPrimaryEmail" + """CUSTOMER_PRIMARY_EMAIL.""" + CUSTOMER_CREATED_AT = "customerCreatedAt" + """CUSTOMER_CREATED_AT.""" + + +class BillingProfileExpand(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """BillingProfileExpand details what profile fields to expand.""" + + APPS = "apps" + """APPS.""" + + +class BillingProfileOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """BillingProfileOrderBy specifies the ordering options for profiles.""" + + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + DEFAULT = "default" + """DEFAULT.""" + NAME = "name" + """NAME.""" + + +class BillingSettlementMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The settlement mode of a plan. + It determines how the billing system generates invoices and credits for the subscriptions using + this plan. + + * credit_then_invoice: credits from the previous billing period are applied first, then the + remaining balance is invoiced. This is the default and most common settlement mode. + * credit_only: only credits from the previous billing period are generated and applied. No + invoices are generated for the subscription. + """ + + CREDIT_THEN_INVOICE = "credit_then_invoice" + """CREDIT_THEN_INVOICE.""" + CREDIT_ONLY = "credit_only" + """CREDIT_ONLY.""" + + +class BillingWorkflowInvoicingSubscriptionEndProrationMode( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Billing workflow subscription end proration mode.""" + + BILL_FULL_PERIOD = "bill_full_period" + """Bill the full billing period amount for terminal lines even when the actual service period is + shorter.""" + BILL_ACTUAL_PERIOD = "bill_actual_period" + """Bill the amount for the actual terminal service period.""" + + +class CheckoutSessionUIMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Stripe CheckoutSession.ui_mode.""" + + EMBEDDED = "embedded" + """EMBEDDED.""" + HOSTED = "hosted" + """HOSTED.""" + + +class CollectionMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Collection method.""" + + CHARGE_AUTOMATICALLY = "charge_automatically" + """CHARGE_AUTOMATICALLY.""" + SEND_INVOICE = "send_invoice" + """SEND_INVOICE.""" + + +class CreateCheckoutSessionTaxIdCollectionRequired( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Create Stripe checkout session tax ID collection required.""" + + IF_SUPPORTED = "if_supported" + """A tax ID will be required if collection is supported for the selected billing address country. + See: `https://docs.stripe.com/tax/checkout/tax-ids#supported-types + `_.""" + NEVER = "never" + """Tax ID collection is never required.""" + + +class CreateStripeCheckoutSessionBillingAddressCollection( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Specify whether Checkout should collect the customer’s billing address.""" + + AUTO = "auto" + """Checkout will only collect the billing address when necessary. When using automatic_tax, + Checkout will collect the minimum number of fields required for tax calculation.""" + REQUIRED = "required" + """Checkout will always collect the customer’s billing address.""" + + +class CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Create Stripe checkout session consent collection agreement position.""" + + AUTO = "auto" + """Uses Stripe defaults to determine the visibility and position of the payment method reuse + agreement.""" + HIDDEN = "hidden" + """Hides the payment method reuse agreement.""" + + +class CreateStripeCheckoutSessionConsentCollectionPromotions( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Create Stripe checkout session consent collection promotions.""" + + AUTO = "auto" + """Enable the collection of customer consent for promotional communications. The Checkout Session + will determine whether to display an option to opt into promotional communication from the + merchant depending on if a customer is provided, and if that customer has consented to + receiving promotional communications from the merchant in the past.""" + NONE = "none" + """Checkout will not collect customer consent for promotional communications.""" + + +class CreateStripeCheckoutSessionConsentCollectionTermsOfService( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Create Stripe checkout session consent collection terms of service.""" + + NONE = "none" + """Does not display checkbox for the terms of service agreement.""" + REQUIRED = "required" + """Displays a checkbox for the terms of service agreement which requires customer to check before + being able to pay.""" + + +class CreateStripeCheckoutSessionCustomerUpdateBehavior( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Create Stripe checkout session customer update behavior.""" + + AUTO = "auto" + """Checkout will automatically determine whether to update the provided Customer object using + details from the session.""" + NEVER = "never" + """Checkout will never update the provided Customer object.""" + + +class CreateStripeCheckoutSessionRedirectOnCompletion( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Create Stripe checkout session redirect on completion.""" + + ALWAYS = "always" + """The Session will always redirect to the return_url after successful confirmation.""" + IF_REQUIRED = "if_required" + """The Session will only redirect to the return_url after a redirect-based payment method is used.""" + NEVER = "never" + """The Session will never redirect to the return_url, and redirect-based payment methods will be + disabled.""" + + +class CustomerExpand(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """CustomerExpand specifies the parts of the customer to expand in the list output.""" + + SUBSCRIPTIONS = "subscriptions" + """SUBSCRIPTIONS.""" + + +class CustomerOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for customers.""" + + ID = "id" + """ID.""" + NAME = "name" + """NAME.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + + +class CustomerSubscriptionOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for customer subscriptions.""" + + ACTIVE_FROM = "activeFrom" + """ACTIVE_FROM.""" + ACTIVE_TO = "activeTo" + """ACTIVE_TO.""" + + +class CustomInvoicingPaymentTrigger(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Payment trigger to execute on a finalized invoice.""" + + PAID = "paid" + """PAID.""" + PAYMENT_FAILED = "payment_failed" + """PAYMENT_FAILED.""" + PAYMENT_UNCOLLECTIBLE = "payment_uncollectible" + """PAYMENT_UNCOLLECTIBLE.""" + PAYMENT_OVERDUE = "payment_overdue" + """PAYMENT_OVERDUE.""" + ACTION_REQUIRED = "action_required" + """ACTION_REQUIRED.""" + VOID = "void" + """VOID.""" + + +class DiscountReasonType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the discount reason.""" + + MAXIMUM_SPEND = "maximum_spend" + """MAXIMUM_SPEND.""" + RATECARD_PERCENTAGE = "ratecard_percentage" + """RATECARD_PERCENTAGE.""" + RATECARD_USAGE = "ratecard_usage" + """RATECARD_USAGE.""" + + +class EditOp(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum listing the different operation types.""" + + ADD_ITEM = "add_item" + """ADD_ITEM.""" + REMOVE_ITEM = "remove_item" + """REMOVE_ITEM.""" + UNSCHEDULE_EDIT = "unschedule_edit" + """UNSCHEDULE_EDIT.""" + ADD_PHASE = "add_phase" + """ADD_PHASE.""" + REMOVE_PHASE = "remove_phase" + """REMOVE_PHASE.""" + STRETCH_PHASE = "stretch_phase" + """STRETCH_PHASE.""" + + +class EntitlementOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for entitlements.""" + + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + + +class EntitlementType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the entitlement.""" + + METERED = "metered" + """METERED.""" + BOOLEAN = "boolean" + """BOOLEAN.""" + STATIC = "static" + """STATIC.""" + + +class ExpirationDuration(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The expiration duration enum.""" + + HOUR = "HOUR" + """HOUR.""" + DAY = "DAY" + """DAY.""" + WEEK = "WEEK" + """WEEK.""" + MONTH = "MONTH" + """MONTH.""" + YEAR = "YEAR" + """YEAR.""" + + +class FeatureOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for features.""" + + ID = "id" + """ID.""" + KEY = "key" + """KEY.""" + NAME = "name" + """NAME.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + + +class FeatureUnitCostType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of unit cost.""" + + LLM = "llm" + """LLM.""" + MANUAL = "manual" + """MANUAL.""" + + +class GrantOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for grants.""" + + ID = "id" + """ID.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + + +class InstallMethod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Install method of the application.""" + + WITH_O_AUTH2 = "with_oauth2" + """WITH_O_AUTH2.""" + WITH_API_KEY = "with_api_key" + """WITH_API_KEY.""" + NO_CREDENTIALS_REQUIRED = "no_credentials_required" + """NO_CREDENTIALS_REQUIRED.""" + + +class InvoiceDetailedLineCostCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a + commitment. + """ + + REGULAR = "regular" + """The fee is a regular fee due to usage.""" + COMMITMENT = "commitment" + """The fee is a fee due to a commitment (e.g. minimum spend).""" + + +class InvoiceDocumentRefType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceDocumentRefType defines the type of document that is being referenced.""" + + CREDIT_NOTE_ORIGINAL_INVOICE = "credit_note_original_invoice" + """CREDIT_NOTE_ORIGINAL_INVOICE.""" + + +class InvoiceExpand(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceExpand specifies the parts of the invoice to expand in the list output.""" + + LINES = "lines" + """LINES.""" + PRECEDING = "preceding" + """PRECEDING.""" + WORKFLOW_APPS = "workflow.apps" + """WORKFLOW_APPS.""" + + +class InvoiceLineManagedBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceLineManagedBy specifies who manages the line.""" + + SUBSCRIPTION = "subscription" + """The line is managed by the susbcription engine of + + If there are any changes to the subscription the line will be updated accordingly.""" + SYSTEM = "system" + """The line is managed by the billing system of the + + The line is immutable.""" + MANUAL = "manual" + """The line is managed via our API. + + If the line is coming from a subscription we will not update the line if the subscription + changes. + + The only exception is that the period and invoiceAt fields will be updated in case of + progressively billed + usage-based lines to maintain the coherence of the line structure. Any other fields edited will + be kept as is.""" + + +class InvoiceLineStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Line status specifies the status of the line.""" + + VALID = "valid" + """The line is valid and can be used in the invoice.""" + DETAILED = "detailed" + """The line is a detail line which is used to detail the individual charges and discounts of a + valid line.""" + SPLIT = "split" + """The line has been split into multiple valid lines due to progressive billing.""" + + +class InvoiceLineTaxBehavior(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceLineTaxBehavior details how the tax item is applied to the base amount. + + Inclusive means the tax is included in the base amount. + Exclusive means the tax is added to the base amount. + """ + + INCLUSIVE = "inclusive" + """Tax is included in the base amount.""" + EXCLUSIVE = "exclusive" + """Tax is added to the base amount.""" + + +class InvoiceLineTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """LineTypes represents the different types of lines that can be used in an invoice.""" + + FLAT_FEE = "flat_fee" + """FLAT_FEE.""" + USAGE_BASED = "usage_based" + """USAGE_BASED.""" + + +class InvoiceOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceOrderBy specifies the ordering options for invoice listing.""" + + CUSTOMER_NAME = "customer.name" + """CUSTOMER_NAME.""" + ISSUED_AT = "issuedAt" + """ISSUED_AT.""" + STATUS = "status" + """STATUS.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + PERIOD_START = "periodStart" + """PERIOD_START.""" + + +class InvoiceStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceStatus describes the status of an invoice.""" + + GATHERING = "gathering" + """The list of line items for the next invoice is being gathered.""" + DRAFT = "draft" + """The invoice is in draft status.""" + ISSUING = "issuing" + """The invoice is in the process of being issued.""" + ISSUED = "issued" + """The invoice has been issued to the customer.""" + PAYMENT_PROCESSING = "payment_processing" + """The payment for the invoice is being processed.""" + OVERDUE = "overdue" + """The invoice's payment is overdue.""" + PAID = "paid" + """The invoice has been paid.""" + UNCOLLECTIBLE = "uncollectible" + """The invoice has been marked uncollectible.""" + VOIDED = "voided" + """The invoice has been voided.""" + + +class InvoiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """InvoiceType represents the type of invoice. + + The type of invoice determines the purpose of the invoice and how it should be handled. + """ + + STANDARD = "standard" + """A regular commercial invoice document between a supplier and customer.""" + CREDIT_NOTE = "credit_note" + """Reflects a refund either partial or complete of the preceding document. A credit note + effectively *extends* the previous document.""" + + +class MeasureUsageFromPreset(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Start of measurement options.""" + + CURRENT_PERIOD_START = "CURRENT_PERIOD_START" + """CURRENT_PERIOD_START.""" + NOW = "NOW" + """NOW.""" + + +class MeterAggregation(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The aggregation type to use for the meter.""" + + SUM = "SUM" + """SUM.""" + COUNT = "COUNT" + """COUNT.""" + UNIQUE_COUNT = "UNIQUE_COUNT" + """UNIQUE_COUNT.""" + AVG = "AVG" + """AVG.""" + MIN = "MIN" + """MIN.""" + MAX = "MAX" + """MAX.""" + LATEST = "LATEST" + """LATEST.""" + + +class MeterOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for meters.""" + + KEY = "key" + """KEY.""" + NAME = "name" + """NAME.""" + AGGREGATION = "aggregation" + """AGGREGATION.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + + +class NotificationChannelOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for notification channels.""" + + ID = "id" + """ID.""" + TYPE = "type" + """TYPE.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + + +class NotificationChannelType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the notification channel.""" + + WEBHOOK = "WEBHOOK" + """WEBHOOK.""" + + +class NotificationEventDeliveryStatusState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Delivery State.""" + + SUCCESS = "SUCCESS" + """SUCCESS.""" + FAILED = "FAILED" + """FAILED.""" + SENDING = "SENDING" + """SENDING.""" + PENDING = "PENDING" + """PENDING.""" + RESENDING = "RESENDING" + """RESENDING.""" + + +class NotificationEventOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for notification channels.""" + + ID = "id" + """ID.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + + +class NotificationEventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of the notification event.""" + + ENTITLEMENTS_BALANCE_THRESHOLD = "entitlements.balance.threshold" + """ENTITLEMENTS_BALANCE_THRESHOLD.""" + ENTITLEMENTS_RESET = "entitlements.reset" + """ENTITLEMENTS_RESET.""" + INVOICE_CREATED = "invoice.created" + """INVOICE_CREATED.""" + INVOICE_UPDATED = "invoice.updated" + """INVOICE_UPDATED.""" + + +class NotificationRuleBalanceThresholdValueType( # pylint: disable=name-too-long + str, Enum, metaclass=CaseInsensitiveEnumMeta +): + """Notification balance threshold type.""" + + PERCENT = "PERCENT" + """PERCENT.""" + NUMBER = "NUMBER" + """NUMBER.""" + BALANCE_VALUE = "balance_value" + """BALANCE_VALUE.""" + USAGE_PERCENTAGE = "usage_percentage" + """USAGE_PERCENTAGE.""" + USAGE_VALUE = "usage_value" + """USAGE_VALUE.""" + + +class NotificationRuleOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for notification channels.""" + + ID = "id" + """ID.""" + TYPE = "type" + """TYPE.""" + CREATED_AT = "createdAt" + """CREATED_AT.""" + UPDATED_AT = "updatedAt" + """UPDATED_AT.""" + + +class OAuth2AuthorizationCodeGrantErrorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """OAuth2 authorization code grant error types.""" + + INVALID_REQUEST = "invalid_request" + """The request is missing a required parameter, includes an invalid parameter value, includes a + parameter more than once, or is otherwise malformed.""" + UNAUTHORIZED_CLIENT = "unauthorized_client" + """The client is not authorized to request an authorization code using this method.""" + ACCESS_DENIED = "access_denied" + """The resource owner or authorization server denied the request.""" + UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type" + """The authorization server does not support obtaining an authorization code using this method.""" + INVALID_SCOPE = "invalid_scope" + """The requested scope is invalid, unknown, or malformed.""" + SERVER_ERROR = "server_error" + """The authorization server encountered an unexpected condition that prevented it from fulfilling + the request.""" + TEMPORARILY_UNAVAILABLE = "temporarily_unavailable" + """The authorization server is currently unable to handle the request due to a temporary + overloading or maintenance of the server.""" + + +class PaymentTermType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """PaymentTermType defines the type of terms to be applied.""" + + DUE_DATE = "due_date" + """Due on a specific date.""" + INSTANT = "instant" + """On receipt of invoice.""" + + +class PlanAddonOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for plan add-on assignments.""" + + ID = "id" + """ID.""" + KEY = "key" + """KEY.""" + VERSION = "version" + """VERSION.""" + CREATED_AT = "created_at" + """CREATED_AT.""" + UPDATED_AT = "updated_at" + """UPDATED_AT.""" + + +class PlanOrderBy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Order by options for plans.""" + + ID = "id" + """ID.""" + KEY = "key" + """KEY.""" + VERSION = "version" + """VERSION.""" + CREATED_AT = "created_at" + """CREATED_AT.""" + UPDATED_AT = "updated_at" + """UPDATED_AT.""" + + +class PlanStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of a plan.""" + + DRAFT = "draft" + """DRAFT.""" + ACTIVE = "active" + """ACTIVE.""" + ARCHIVED = "archived" + """ARCHIVED.""" + SCHEDULED = "scheduled" + """SCHEDULED.""" + + +class PricePaymentTerm(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The payment term of a flat price. One of: in_advance or in_arrears.""" + + IN_ADVANCE = "in_advance" + """If in_advance, the rate card will be invoiced in the previous billing cycle.""" + IN_ARREARS = "in_arrears" + """If in_arrears, the rate card will be invoiced in the current billing cycle.""" + + +class PriceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the price.""" + + FLAT = "flat" + """FLAT.""" + UNIT = "unit" + """UNIT.""" + TIERED = "tiered" + """TIERED.""" + DYNAMIC = "dynamic" + """DYNAMIC.""" + PACKAGE = "package" + """PACKAGE.""" + + +class ProRatingMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Pro-rating mode options for handling billing period changes.""" + + PRORATE_PRICES = "prorate_prices" + """Calculate pro-rated charges based on time remaining in billing period.""" + + +class RateCardType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of the rate card.""" + + FLAT_FEE = "flat_fee" + """FLAT_FEE.""" + USAGE_BASED = "usage_based" + """USAGE_BASED.""" + + +class RecurringPeriodIntervalEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The unit of time for the interval. One of: ``day``, ``week``, ``month``, or ``year``.""" + + DAY = "DAY" + """DAY.""" + WEEK = "WEEK" + """WEEK.""" + MONTH = "MONTH" + """MONTH.""" + YEAR = "YEAR" + """YEAR.""" + + +class RemovePhaseShifting(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The direction of the phase shift when a phase is removed.""" + + NEXT = "next" + """Shifts all subsequent phases to start sooner by the deleted phase's length.""" + PREV = "prev" + """Extends the previous phase to end later by the deleted phase's length.""" + + +class SortOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The order direction.""" + + ASC = "ASC" + """ASC.""" + DESC = "DESC" + """DESC.""" + + +class StripeCheckoutSessionMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Stripe CheckoutSession.mode.""" + + SETUP = "setup" + """SETUP.""" + + +class SubscriptionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Subscription status.""" + + ACTIVE = "active" + """ACTIVE.""" + INACTIVE = "inactive" + """INACTIVE.""" + CANCELED = "canceled" + """CANCELED.""" + SCHEDULED = "scheduled" + """SCHEDULED.""" + + +class SubscriptionTimingEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Subscription edit timing. When immediate, the requested changes take effect immediately. When + nextBillingCycle, the requested changes take effect at the next billing cycle. + """ + + IMMEDIATE = "immediate" + """IMMEDIATE.""" + NEXT_BILLING_CYCLE = "next_billing_cycle" + """NEXT_BILLING_CYCLE.""" + + +class TaxBehavior(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Tax behavior. + + This enum is used to specify whether tax is included in the price or excluded from the price. + """ + + INCLUSIVE = "inclusive" + """Tax is included in the price.""" + EXCLUSIVE = "exclusive" + """Tax is excluded from the price.""" + + +class TieredPriceMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The mode of the tiered price.""" + + VOLUME = "volume" + """VOLUME.""" + GRADUATED = "graduated" + """GRADUATED.""" + + +class ValidationIssueSeverity(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """ValidationIssueSeverity describes the severity of a validation issue. + + Issues with severity "critical" will prevent the invoice from being issued. + """ + + CRITICAL = "critical" + """CRITICAL.""" + WARNING = "warning" + """WARNING.""" + + +class VoidInvoiceLineActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """VoidInvoiceLineActionType describes how to handle the voidied line item in the invoice.""" + + DISCARD = "discard" + """The line items will never be charged for again.""" + PENDING = "pending" + """Queue the line items into the pending state, they will be included in the next invoice. (We + want to generate an invoice right now).""" + + +class WindowSize(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Aggregation window size.""" + + MINUTE = "MINUTE" + """MINUTE.""" + HOUR = "HOUR" + """HOUR.""" + DAY = "DAY" + """DAY.""" + MONTH = "MONTH" + """MONTH.""" diff --git a/api/client/python/openmeter/_generated/models/_models.py b/api/client/python/openmeter/_generated/models/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..69b864826f3415178588733299cc3bdbad38ef90 --- /dev/null +++ b/api/client/python/openmeter/_generated/models/_models.py @@ -0,0 +1,15703 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_field +from ._enums import ( + AppType, + BillingCollectionAlignment, + DiscountReasonType, + EditOp, + EntitlementType, + FeatureUnitCostType, + InvoiceDocumentRefType, + InvoiceLineTypes, + NotificationChannelType, + NotificationEventType, + PaymentTermType, + PriceType, + RateCardType, + VoidInvoiceLineActionType, +) + +if TYPE_CHECKING: + from .. import _types, models as _models + + +class Addon(_Model): + """Add-on allows extending subscriptions with compatible plans with additional ratecards. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar key: Key. Required. + :vartype key: str + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar version: Version. Required. + :vartype version: int + :ivar instance_type: InstanceType. Required. Known values are: "single" and "multiple". + :vartype instance_type: str or ~openmeter.models.AddonInstanceType + :ivar currency: Currency. Required. + :vartype currency: str + :ivar effective_from: Effective start date. + :vartype effective_from: ~datetime.datetime + :ivar effective_to: Effective end date. + :vartype effective_to: ~datetime.datetime + :ivar status: Status. Required. Known values are: "draft", "active", and "archived". + :vartype status: str or ~openmeter.models.AddonStatus + :ivar rate_cards: Rate cards. Required. + :vartype rate_cards: list[~openmeter._generated.models.RateCardFlatFee or + ~openmeter._generated.models.RateCardUsageBased] + :ivar validation_errors: Validation errors. Required. + :vartype validation_errors: list[~openmeter._generated.models.ValidationError] + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + key: str = rest_field(visibility=["read", "create"]) + """Key. Required.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + version: int = rest_field(visibility=["read"]) + """Version. Required.""" + instance_type: Union[str, "_models.AddonInstanceType"] = rest_field( + name="instanceType", visibility=["read", "create", "update"] + ) + """InstanceType. Required. Known values are: \"single\" and \"multiple\".""" + currency: str = rest_field(visibility=["read", "create"]) + """Currency. Required.""" + effective_from: Optional[datetime.datetime] = rest_field( + name="effectiveFrom", visibility=["read"], format="rfc3339" + ) + """Effective start date.""" + effective_to: Optional[datetime.datetime] = rest_field(name="effectiveTo", visibility=["read"], format="rfc3339") + """Effective end date.""" + status: Union[str, "_models.AddonStatus"] = rest_field(visibility=["read"]) + """Status. Required. Known values are: \"draft\", \"active\", and \"archived\".""" + rate_cards: list["_types.RateCard"] = rest_field(name="rateCards", visibility=["read", "create", "update"]) + """Rate cards. Required.""" + validation_errors: list["_models.ValidationError"] = rest_field(name="validationErrors", visibility=["read"]) + """Validation errors. Required.""" + + @overload + def __init__( + self, + *, + name: str, + key: str, + instance_type: Union[str, "_models.AddonInstanceType"], + currency: str, + rate_cards: list["_types.RateCard"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AddonCreate(_Model): + """Resource create operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar key: Key. Required. + :vartype key: str + :ivar instance_type: InstanceType. Required. Known values are: "single" and "multiple". + :vartype instance_type: str or ~openmeter.models.AddonInstanceType + :ivar currency: Currency. Required. + :vartype currency: str + :ivar rate_cards: Rate cards. Required. + :vartype rate_cards: list[~openmeter._generated.models.RateCardFlatFee or + ~openmeter._generated.models.RateCardUsageBased] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key. Required.""" + instance_type: Union[str, "_models.AddonInstanceType"] = rest_field( + name="instanceType", visibility=["read", "create", "update", "delete", "query"] + ) + """InstanceType. Required. Known values are: \"single\" and \"multiple\".""" + currency: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency. Required.""" + rate_cards: list["_types.RateCard"] = rest_field( + name="rateCards", visibility=["read", "create", "update", "delete", "query"] + ) + """Rate cards. Required.""" + + @overload + def __init__( + self, + *, + name: str, + key: str, + instance_type: Union[str, "_models.AddonInstanceType"], + currency: str, + rate_cards: list["_types.RateCard"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AddonReplaceUpdate(_Model): + """Resource update operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar instance_type: InstanceType. Required. Known values are: "single" and "multiple". + :vartype instance_type: str or ~openmeter.models.AddonInstanceType + :ivar rate_cards: Rate cards. Required. + :vartype rate_cards: list[~openmeter._generated.models.RateCardFlatFee or + ~openmeter._generated.models.RateCardUsageBased] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + instance_type: Union[str, "_models.AddonInstanceType"] = rest_field( + name="instanceType", visibility=["read", "create", "update"] + ) + """InstanceType. Required. Known values are: \"single\" and \"multiple\".""" + rate_cards: list["_types.RateCard"] = rest_field(name="rateCards", visibility=["read", "create", "update"]) + """Rate cards. Required.""" + + @overload + def __init__( + self, + *, + name: str, + instance_type: Union[str, "_models.AddonInstanceType"], + rate_cards: list["_types.RateCard"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Address(_Model): + """Address. + + :ivar country: Country code in `ISO 3166-1 `_ + alpha-2 format. + :vartype country: str + :ivar postal_code: Postal code. + :vartype postal_code: str + :ivar state: State or province. + :vartype state: str + :ivar city: City. + :vartype city: str + :ivar line1: First line of the address. + :vartype line1: str + :ivar line2: Second line of the address. + :vartype line2: str + :ivar phone_number: Phone number. + :vartype phone_number: str + """ + + country: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Country code in `ISO 3166-1 `_ alpha-2 format.""" + postal_code: Optional[str] = rest_field( + name="postalCode", visibility=["read", "create", "update", "delete", "query"] + ) + """Postal code.""" + state: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """State or province.""" + city: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """City.""" + line1: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """First line of the address.""" + line2: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Second line of the address.""" + phone_number: Optional[str] = rest_field( + name="phoneNumber", visibility=["read", "create", "update", "delete", "query"] + ) + """Phone number.""" + + @overload + def __init__( + self, + *, + country: Optional[str] = None, + postal_code: Optional[str] = None, + state: Optional[str] = None, + city: Optional[str] = None, + line1: Optional[str] = None, + line2: Optional[str] = None, + phone_number: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Alignment(_Model): + """Alignment configuration for a plan or subscription. + + :ivar billables_must_align: Whether all Billable items and RateCards must align. Alignment + means the Price's BillingCadence must align for both duration and anchor time. + :vartype billables_must_align: bool + """ + + billables_must_align: Optional[bool] = rest_field( + name="billablesMustAlign", visibility=["read", "create", "update"] + ) + """Whether all Billable items and RateCards must align. Alignment means the Price's BillingCadence + must align for both duration and anchor time.""" + + @overload + def __init__( + self, + *, + billables_must_align: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Annotations(_Model): + """Set of key-value pairs managed by the system. Cannot be modified by user.""" + + +class AppCapability(_Model): + """App capability. + + Capabilities only exist in config so they don't extend the Resource model. + + :ivar type: The capability type. Required. Known values are: "reportUsage", "reportEvents", + "calculateTax", "invoiceCustomers", and "collectPayments". + :vartype type: str or ~openmeter.models.AppCapabilityType + :ivar key: Key. Required. + :vartype key: str + :ivar name: The capability name. Required. + :vartype name: str + :ivar description: The capability description. Required. + :vartype description: str + """ + + type: Union[str, "_models.AppCapabilityType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The capability type. Required. Known values are: \"reportUsage\", \"reportEvents\", + \"calculateTax\", \"invoiceCustomers\", and \"collectPayments\".""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The capability name. Required.""" + description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The capability description. Required.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.AppCapabilityType"], + key: str, + name: str, + description: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AppPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.StripeApp or + ~openmeter._generated.models.SandboxApp or ~openmeter._generated.models.CustomInvoicingApp] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_types.App"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_types.App"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class AppReference(_Model): + """App reference + + Can be used as a short reference to an app if the full app object is not needed. + + :ivar id: The ID of the app. Required. + :vartype id: str + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the app. Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UnexpectedProblemResponse(_Model): + """A Problem Details object (RFC 7807). Additional properties specific to the problem type may be + present. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type contains a URI that identifies the problem type. Required.""" + title: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A a short, human-readable summary of the problem type. Required.""" + status: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The HTTP status code generated by the origin server for this occurrence of the problem.""" + detail: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A human-readable explanation specific to this occurrence of the problem. Required.""" + instance: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A URI reference that identifies the specific occurrence of the problem. Required.""" + extensions: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional properties specific to the problem type may be present.""" + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BadRequestProblemResponse(UnexpectedProblemResponse): + """The server cannot or will not process the request due to something that is perceived to be a + client error (e.g., malformed request syntax, invalid request message framing, or deceptive + request routing). + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BalanceHistoryWindow(_Model): + """The balance history window. + + :ivar period: Required. + :vartype period: ~openmeter._generated.models.Period + :ivar usage: The total usage of the feature in the period. Required. + :vartype usage: float + :ivar balance_at_start: The entitlement balance at the start of the period. Required. + :vartype balance_at_start: float + """ + + period: "_models.Period" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + usage: float = rest_field(visibility=["read"]) + """The total usage of the feature in the period. Required.""" + balance_at_start: float = rest_field(name="balanceAtStart", visibility=["read"]) + """The entitlement balance at the start of the period. Required.""" + + @overload + def __init__( + self, + *, + period: "_models.Period", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingCustomerProfile(_Model): + """Customer specific merged profile. + + This profile is calculated from the customer override and the billing profile it references or + the default. + + Thus this does not have any kind of resource fields, only the calculated values. + + :ivar supplier: The name and contact information for the supplier this billing profile + represents. Required. + :vartype supplier: ~openmeter._generated.models.BillingParty + :ivar workflow: The billing workflow settings for this profile. Required. + :vartype workflow: ~openmeter._generated.models.BillingWorkflow + :ivar apps: The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + Required. Is either a BillingProfileApps type or a BillingProfileAppReferences type. + :vartype apps: ~openmeter._generated.models.BillingProfileApps or + ~openmeter._generated.models.BillingProfileAppReferences + """ + + supplier: "_models.BillingParty" = rest_field(visibility=["read"]) + """The name and contact information for the supplier this billing profile represents. Required.""" + workflow: "_models.BillingWorkflow" = rest_field(visibility=["read"]) + """The billing workflow settings for this profile. Required.""" + apps: "_types.BillingProfileAppsOrReference" = rest_field(visibility=["read"]) + """The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + Required. Is either a BillingProfileApps type or a BillingProfileAppReferences type.""" + + +class BillingDiscountPercentage(_Model): + """A percentage discount. + + :ivar percentage: Percentage. Required. + :vartype percentage: float + :ivar correlation_id: Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + :vartype correlation_id: str + """ + + percentage: float = rest_field(visibility=["read", "create", "update"]) + """Percentage. Required.""" + correlation_id: Optional[str] = rest_field( + name="correlationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect.""" + + @overload + def __init__( + self, + *, + percentage: float, + correlation_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingDiscounts(_Model): + """A discount by type. + + :ivar percentage: The percentage discount. + :vartype percentage: ~openmeter._generated.models.BillingDiscountPercentage + :ivar usage: The usage discount. + :vartype usage: ~openmeter._generated.models.BillingDiscountUsage + """ + + percentage: Optional["_models.BillingDiscountPercentage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The percentage discount.""" + usage: Optional["_models.BillingDiscountUsage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The usage discount.""" + + @overload + def __init__( + self, + *, + percentage: Optional["_models.BillingDiscountPercentage"] = None, + usage: Optional["_models.BillingDiscountUsage"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingDiscountUsage(_Model): + """A usage discount. + + :ivar quantity: Usage. Required. + :vartype quantity: str + :ivar correlation_id: Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + :vartype correlation_id: str + """ + + quantity: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Usage. Required.""" + correlation_id: Optional[str] = rest_field( + name="correlationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect.""" + + @overload + def __init__( + self, + *, + quantity: str, + correlation_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingInvoiceCustomerExtendedDetails(_Model): + """BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the + billing party details for invoices. + + These fields contain the OpenMeter specific details for the customer, that are not strictly + required for the invoice itself. + + :ivar id: Unique identifier for the party (if available). + :vartype id: str + :ivar key: Key. + :vartype key: str + :ivar name: Legal name or representation of the organization. + :vartype name: str + :ivar tax_id: The entity's legal ID code used for tax purposes. They may have other numbers, + but we're only interested in those valid for tax purposes. + :vartype tax_id: ~openmeter._generated.models.BillingPartyTaxIdentity + :ivar addresses: Regular post addresses for where information should be sent if needed. + :vartype addresses: list[~openmeter._generated.models.Address] + :ivar usage_attribution: Usage Attribution. Required. + :vartype usage_attribution: ~openmeter._generated.models.CustomerUsageAttribution + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Unique identifier for the party (if available).""" + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Legal name or representation of the organization.""" + tax_id: Optional["_models.BillingPartyTaxIdentity"] = rest_field( + name="taxId", visibility=["read", "create", "update"] + ) + """The entity's legal ID code used for tax purposes. They may have other numbers, but we're only + interested in those valid for tax purposes.""" + addresses: Optional[list["_models.Address"]] = rest_field(visibility=["read", "create", "update"]) + """Regular post addresses for where information should be sent if needed.""" + usage_attribution: "_models.CustomerUsageAttribution" = rest_field( + name="usageAttribution", visibility=["read", "create", "update", "delete", "query"] + ) + """Usage Attribution. Required.""" + + @overload + def __init__( + self, + *, + usage_attribution: "_models.CustomerUsageAttribution", + key: Optional[str] = None, + name: Optional[str] = None, + tax_id: Optional["_models.BillingPartyTaxIdentity"] = None, + addresses: Optional[list["_models.Address"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingParty(_Model): + """Party represents a person or business entity. + + :ivar id: Unique identifier for the party (if available). + :vartype id: str + :ivar key: Key. + :vartype key: str + :ivar name: Legal name or representation of the organization. + :vartype name: str + :ivar tax_id: The entity's legal ID code used for tax purposes. They may have other numbers, + but we're only interested in those valid for tax purposes. + :vartype tax_id: ~openmeter._generated.models.BillingPartyTaxIdentity + :ivar addresses: Regular post addresses for where information should be sent if needed. + :vartype addresses: list[~openmeter._generated.models.Address] + """ + + id: Optional[str] = rest_field(visibility=["read"]) + """Unique identifier for the party (if available).""" + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Legal name or representation of the organization.""" + tax_id: Optional["_models.BillingPartyTaxIdentity"] = rest_field( + name="taxId", visibility=["read", "create", "update"] + ) + """The entity's legal ID code used for tax purposes. They may have other numbers, but we're only + interested in those valid for tax purposes.""" + addresses: Optional[list["_models.Address"]] = rest_field(visibility=["read", "create", "update"]) + """Regular post addresses for where information should be sent if needed.""" + + @overload + def __init__( + self, + *, + key: Optional[str] = None, + name: Optional[str] = None, + tax_id: Optional["_models.BillingPartyTaxIdentity"] = None, + addresses: Optional[list["_models.Address"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingPartyReplaceUpdate(_Model): + """Resource update operation model. + + :ivar key: Key. + :vartype key: str + :ivar name: Legal name or representation of the organization. + :vartype name: str + :ivar tax_id: The entity's legal ID code used for tax purposes. They may have other numbers, + but we're only interested in those valid for tax purposes. + :vartype tax_id: ~openmeter._generated.models.BillingPartyTaxIdentity + :ivar addresses: Regular post addresses for where information should be sent if needed. + :vartype addresses: list[~openmeter._generated.models.Address] + """ + + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Legal name or representation of the organization.""" + tax_id: Optional["_models.BillingPartyTaxIdentity"] = rest_field( + name="taxId", visibility=["read", "create", "update"] + ) + """The entity's legal ID code used for tax purposes. They may have other numbers, but we're only + interested in those valid for tax purposes.""" + addresses: Optional[list["_models.Address"]] = rest_field(visibility=["read", "create", "update"]) + """Regular post addresses for where information should be sent if needed.""" + + @overload + def __init__( + self, + *, + key: Optional[str] = None, + name: Optional[str] = None, + tax_id: Optional["_models.BillingPartyTaxIdentity"] = None, + addresses: Optional[list["_models.Address"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingPartyTaxIdentity(_Model): + """Identity stores the details required to identify an entity for tax purposes in a specific + country. + + :ivar code: Normalized tax code shown on the original identity document. + :vartype code: str + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Normalized tax code shown on the original identity document.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfile(_Model): + """BillingProfile represents a billing profile. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar supplier: The name and contact information for the supplier this billing profile + represents. Required. + :vartype supplier: ~openmeter._generated.models.BillingParty + :ivar workflow: The billing workflow settings for this profile. Required. + :vartype workflow: ~openmeter._generated.models.BillingWorkflow + :ivar apps: The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + Required. Is either a BillingProfileApps type or a BillingProfileAppReferences type. + :vartype apps: ~openmeter._generated.models.BillingProfileApps or + ~openmeter._generated.models.BillingProfileAppReferences + :ivar default: Is this the default profile?. Required. + :vartype default: bool + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + supplier: "_models.BillingParty" = rest_field(visibility=["read", "create", "update"]) + """The name and contact information for the supplier this billing profile represents. Required.""" + workflow: "_models.BillingWorkflow" = rest_field(visibility=["read"]) + """The billing workflow settings for this profile. Required.""" + apps: "_types.BillingProfileAppsOrReference" = rest_field(visibility=["read"]) + """The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + Required. Is either a BillingProfileApps type or a BillingProfileAppReferences type.""" + default: bool = rest_field(visibility=["read", "create", "update"]) + """Is this the default profile?. Required.""" + + @overload + def __init__( + self, + *, + name: str, + supplier: "_models.BillingParty", + default: bool, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileAppReferences(_Model): + """BillingProfileAppReferences represents the references (id, type) to the apps used by a billing + profile. + + :ivar tax: The tax app used for this workflow. Required. + :vartype tax: ~openmeter._generated.models.AppReference + :ivar invoicing: The invoicing app used for this workflow. Required. + :vartype invoicing: ~openmeter._generated.models.AppReference + :ivar payment: The payment app used for this workflow. Required. + :vartype payment: ~openmeter._generated.models.AppReference + """ + + tax: "_models.AppReference" = rest_field(visibility=["read"]) + """The tax app used for this workflow. Required.""" + invoicing: "_models.AppReference" = rest_field(visibility=["read"]) + """The invoicing app used for this workflow. Required.""" + payment: "_models.AppReference" = rest_field(visibility=["read"]) + """The payment app used for this workflow. Required.""" + + +class BillingProfileApps(_Model): + """BillingProfileApps represents the applications used by a billing profile. + + :ivar tax: The tax app used for this workflow. Required. Is one of the following types: + StripeApp, SandboxApp, CustomInvoicingApp + :vartype tax: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp + or ~openmeter._generated.models.CustomInvoicingApp + :ivar invoicing: The invoicing app used for this workflow. Required. Is one of the following + types: StripeApp, SandboxApp, CustomInvoicingApp + :vartype invoicing: ~openmeter._generated.models.StripeApp or + ~openmeter._generated.models.SandboxApp or ~openmeter._generated.models.CustomInvoicingApp + :ivar payment: The payment app used for this workflow. Required. Is one of the following types: + StripeApp, SandboxApp, CustomInvoicingApp + :vartype payment: ~openmeter._generated.models.StripeApp or + ~openmeter._generated.models.SandboxApp or ~openmeter._generated.models.CustomInvoicingApp + """ + + tax: "_types.App" = rest_field(visibility=["read"]) + """The tax app used for this workflow. Required. Is one of the following types: StripeApp, + SandboxApp, CustomInvoicingApp""" + invoicing: "_types.App" = rest_field(visibility=["read"]) + """The invoicing app used for this workflow. Required. Is one of the following types: StripeApp, + SandboxApp, CustomInvoicingApp""" + payment: "_types.App" = rest_field(visibility=["read"]) + """The payment app used for this workflow. Required. Is one of the following types: StripeApp, + SandboxApp, CustomInvoicingApp""" + + +class BillingProfileAppsCreate(_Model): + """BillingProfileAppsCreate represents the input for creating a billing profile's apps. + + :ivar tax: The tax app used for this workflow. Required. + :vartype tax: str + :ivar invoicing: The invoicing app used for this workflow. Required. + :vartype invoicing: str + :ivar payment: The payment app used for this workflow. Required. + :vartype payment: str + """ + + tax: str = rest_field(visibility=["create"]) + """The tax app used for this workflow. Required.""" + invoicing: str = rest_field(visibility=["create"]) + """The invoicing app used for this workflow. Required.""" + payment: str = rest_field(visibility=["create"]) + """The payment app used for this workflow. Required.""" + + @overload + def __init__( + self, + *, + tax: str, + invoicing: str, + payment: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileCreate(_Model): + """BillingProfileCreate represents the input for creating a billing profile. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar supplier: The name and contact information for the supplier this billing profile + represents. Required. + :vartype supplier: ~openmeter._generated.models.BillingParty + :ivar default: Is this the default profile?. Required. + :vartype default: bool + :ivar workflow: The billing workflow settings for this profile. Required. + :vartype workflow: ~openmeter._generated.models.BillingWorkflowCreate + :ivar apps: The apps used by this billing profile. Required. + :vartype apps: ~openmeter._generated.models.BillingProfileAppsCreate + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + supplier: "_models.BillingParty" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name and contact information for the supplier this billing profile represents. Required.""" + default: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Is this the default profile?. Required.""" + workflow: "_models.BillingWorkflowCreate" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The billing workflow settings for this profile. Required.""" + apps: "_models.BillingProfileAppsCreate" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The apps used by this billing profile. Required.""" + + @overload + def __init__( + self, + *, + name: str, + supplier: "_models.BillingParty", + default: bool, + workflow: "_models.BillingWorkflowCreate", + apps: "_models.BillingProfileAppsCreate", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileCustomerOverride(_Model): + """Customer override values. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar billing_profile_id: The billing profile this override is associated with. + + If empty the default profile is looked up dynamically. + :vartype billing_profile_id: str + :ivar customer_id: The customer id this override is associated with. Required. + :vartype customer_id: str + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + billing_profile_id: Optional[str] = rest_field( + name="billingProfileId", visibility=["read", "create", "update", "delete", "query"] + ) + """The billing profile this override is associated with. + + If empty the default profile is looked up dynamically.""" + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The customer id this override is associated with. Required.""" + + @overload + def __init__( + self, + *, + customer_id: str, + billing_profile_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileCustomerOverrideCreate(_Model): + """Payload for creating a new or updating an existing customer override. + + :ivar billing_profile_id: The billing profile this override is associated with. + + If not provided, the default billing profile is chosen if available. + :vartype billing_profile_id: str + """ + + billing_profile_id: Optional[str] = rest_field( + name="billingProfileId", visibility=["read", "create", "update", "delete", "query"] + ) + """The billing profile this override is associated with. + + If not provided, the default billing profile is chosen if available.""" + + @overload + def __init__( + self, + *, + billing_profile_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileCustomerOverrideWithDetails(_Model): # pylint: disable=name-too-long + """Customer specific workflow overrides. + + :ivar customer_override: The customer override values. + + If empty the merged values are calculated based on the default profile. + :vartype customer_override: ~openmeter._generated.models.BillingProfileCustomerOverride + :ivar base_billing_profile_id: The billing profile the customerProfile is associated with at + the time of query. + + customerOverride contains the explicit mapping set in the customer override object. If that is + empty, then the baseBillingProfileId is the default profile. Required. + :vartype base_billing_profile_id: str + :ivar customer_profile: Merged billing profile with the customer specific overrides. + :vartype customer_profile: ~openmeter._generated.models.BillingCustomerProfile + :ivar customer: The customer this override belongs to. + :vartype customer: ~openmeter._generated.models.Customer + """ + + customer_override: Optional["_models.BillingProfileCustomerOverride"] = rest_field( + name="customerOverride", visibility=["read", "create", "update", "delete", "query"] + ) + """The customer override values. + + If empty the merged values are calculated based on the default profile.""" + base_billing_profile_id: str = rest_field( + name="baseBillingProfileId", visibility=["read", "create", "update", "delete", "query"] + ) + """The billing profile the customerProfile is associated with at the time of query. + + customerOverride contains the explicit mapping set in the customer override object. If that is + empty, then the baseBillingProfileId is the default profile. Required.""" + customer_profile: Optional["_models.BillingCustomerProfile"] = rest_field( + name="customerProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """Merged billing profile with the customer specific overrides.""" + customer: Optional["_models.Customer"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The customer this override belongs to.""" + + @overload + def __init__( + self, + *, + base_billing_profile_id: str, + customer_override: Optional["_models.BillingProfileCustomerOverride"] = None, + customer_profile: Optional["_models.BillingCustomerProfile"] = None, + customer: Optional["_models.Customer"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileCustomerOverrideWithDetailsPaginatedResponse(_Model): # pylint: disable=name-too-long + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: + list[~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.BillingProfileCustomerOverrideWithDetails"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.BillingProfileCustomerOverrideWithDetails"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfilePaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.BillingProfile] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.BillingProfile"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.BillingProfile"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingProfileReplaceUpdateWithWorkflow(_Model): + """BillingProfileReplaceUpdate represents the input for updating a billing profile + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar supplier: The name and contact information for the supplier this billing profile + represents. Required. + :vartype supplier: ~openmeter._generated.models.BillingParty + :ivar default: Is this the default profile?. Required. + :vartype default: bool + :ivar workflow: The billing workflow settings for this profile. Required. + :vartype workflow: ~openmeter._generated.models.BillingWorkflow + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + supplier: "_models.BillingParty" = rest_field(visibility=["read", "create", "update"]) + """The name and contact information for the supplier this billing profile represents. Required.""" + default: bool = rest_field(visibility=["read", "create", "update"]) + """Is this the default profile?. Required.""" + workflow: "_models.BillingWorkflow" = rest_field(visibility=["update"]) + """The billing workflow settings for this profile. Required.""" + + @overload + def __init__( + self, + *, + name: str, + supplier: "_models.BillingParty", + default: bool, + workflow: "_models.BillingWorkflow", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflow(_Model): + """BillingWorkflow represents the settings for a billing workflow. + + :ivar collection: The collection settings for this workflow. + :vartype collection: ~openmeter._generated.models.BillingWorkflowCollectionSettings + :ivar invoicing: The invoicing settings for this workflow. + :vartype invoicing: ~openmeter._generated.models.BillingWorkflowInvoicingSettings + :ivar payment: The payment settings for this workflow. + :vartype payment: ~openmeter._generated.models.BillingWorkflowPaymentSettings + :ivar tax: The tax settings for this workflow. + :vartype tax: ~openmeter._generated.models.BillingWorkflowTaxSettings + """ + + collection: Optional["_models.BillingWorkflowCollectionSettings"] = rest_field( + visibility=["read", "create", "update"] + ) + """The collection settings for this workflow.""" + invoicing: Optional["_models.BillingWorkflowInvoicingSettings"] = rest_field( + visibility=["read", "create", "update"] + ) + """The invoicing settings for this workflow.""" + payment: Optional["_models.BillingWorkflowPaymentSettings"] = rest_field(visibility=["read", "create", "update"]) + """The payment settings for this workflow.""" + tax: Optional["_models.BillingWorkflowTaxSettings"] = rest_field(visibility=["read", "create", "update"]) + """The tax settings for this workflow.""" + + @overload + def __init__( + self, + *, + collection: Optional["_models.BillingWorkflowCollectionSettings"] = None, + invoicing: Optional["_models.BillingWorkflowInvoicingSettings"] = None, + payment: Optional["_models.BillingWorkflowPaymentSettings"] = None, + tax: Optional["_models.BillingWorkflowTaxSettings"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowCollectionAlignmentAnchored(_Model): # pylint: disable=name-too-long + """BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending + line items into an invoice. + + :ivar type: The type of alignment. Required. Align the collection to the anchor time and + cadence. + :vartype type: str or ~openmeter._generated.models.ANCHORED + :ivar recurring_period: The recurring period for the alignment. Required. + :vartype recurring_period: ~openmeter._generated.models.RecurringPeriodV2 + """ + + type: Literal[BillingCollectionAlignment.ANCHORED] = rest_field(visibility=["read", "create", "update"]) + """The type of alignment. Required. Align the collection to the anchor time and cadence.""" + recurring_period: "_models.RecurringPeriodV2" = rest_field( + name="recurringPeriod", visibility=["read", "create", "update"] + ) + """The recurring period for the alignment. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[BillingCollectionAlignment.ANCHORED], + recurring_period: "_models.RecurringPeriodV2", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowCollectionAlignmentSubscription(_Model): # pylint: disable=name-too-long + """BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the + pending line items into an invoice. + + :ivar type: The type of alignment. Required. Align the collection to the start of the + subscription period. + :vartype type: str or ~openmeter._generated.models.SUBSCRIPTION + """ + + type: Literal[BillingCollectionAlignment.SUBSCRIPTION] = rest_field(visibility=["read", "create", "update"]) + """The type of alignment. Required. Align the collection to the start of the subscription period.""" + + @overload + def __init__( + self, + *, + type: Literal[BillingCollectionAlignment.SUBSCRIPTION], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowCollectionSettings(_Model): + """Workflow collection specifies how to collect the pending line items for an invoice. + + :ivar alignment: The alignment for collecting the pending line items into an invoice. Is either + a BillingWorkflowCollectionAlignmentSubscription type or a + BillingWorkflowCollectionAlignmentAnchored type. + :vartype alignment: ~openmeter._generated.models.BillingWorkflowCollectionAlignmentSubscription + or ~openmeter._generated.models.BillingWorkflowCollectionAlignmentAnchored + :ivar interval: This grace period can be used to delay the collection of the pending line items + specified in + alignment. + + This is useful, in case of multiple subscriptions having slightly different billing periods. + :vartype interval: str + """ + + alignment: Optional["_types.BillingWorkflowCollectionAlignment"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The alignment for collecting the pending line items into an invoice. Is either a + BillingWorkflowCollectionAlignmentSubscription type or a + BillingWorkflowCollectionAlignmentAnchored type.""" + interval: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """This grace period can be used to delay the collection of the pending line items specified in + alignment. + + This is useful, in case of multiple subscriptions having slightly different billing periods.""" + + @overload + def __init__( + self, + *, + alignment: Optional["_types.BillingWorkflowCollectionAlignment"] = None, + interval: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowCreate(_Model): + """Resource create operation model. + + :ivar collection: The collection settings for this workflow. + :vartype collection: ~openmeter._generated.models.BillingWorkflowCollectionSettings + :ivar invoicing: The invoicing settings for this workflow. + :vartype invoicing: ~openmeter._generated.models.BillingWorkflowInvoicingSettings + :ivar payment: The payment settings for this workflow. + :vartype payment: ~openmeter._generated.models.BillingWorkflowPaymentSettings + :ivar tax: The tax settings for this workflow. + :vartype tax: ~openmeter._generated.models.BillingWorkflowTaxSettings + """ + + collection: Optional["_models.BillingWorkflowCollectionSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The collection settings for this workflow.""" + invoicing: Optional["_models.BillingWorkflowInvoicingSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The invoicing settings for this workflow.""" + payment: Optional["_models.BillingWorkflowPaymentSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The payment settings for this workflow.""" + tax: Optional["_models.BillingWorkflowTaxSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The tax settings for this workflow.""" + + @overload + def __init__( + self, + *, + collection: Optional["_models.BillingWorkflowCollectionSettings"] = None, + invoicing: Optional["_models.BillingWorkflowInvoicingSettings"] = None, + payment: Optional["_models.BillingWorkflowPaymentSettings"] = None, + tax: Optional["_models.BillingWorkflowTaxSettings"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowInvoicingSettings(_Model): + """Workflow invoice settings. + + :ivar auto_advance: Whether to automatically issue the invoice after the draftPeriod has + passed. + :vartype auto_advance: bool + :ivar draft_period: The period for the invoice to be kept in draft status for manual reviews. + :vartype draft_period: str + :ivar due_after: The period after which the invoice is due. With some payment solutions it's + only applicable for manual collection method. + :vartype due_after: str + :ivar progressive_billing: Should progressive billing be allowed for this workflow?. + :vartype progressive_billing: bool + :ivar subscription_end_proration_mode: Controls how subscription-ending shortened service + periods are billed. Known values are: "bill_full_period" and "bill_actual_period". + :vartype subscription_end_proration_mode: str or + ~openmeter.models.BillingWorkflowInvoicingSubscriptionEndProrationMode + :ivar default_tax_config: Default tax configuration to apply to the invoices. + + Setting a tax code (``stripe.code`` / ``taxCodeId``) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and ``behavior`` remains + fully supported. + :vartype default_tax_config: ~openmeter._generated.models.TaxConfig + """ + + auto_advance: Optional[bool] = rest_field(name="autoAdvance", visibility=["read", "create", "update"]) + """Whether to automatically issue the invoice after the draftPeriod has passed.""" + draft_period: Optional[str] = rest_field(name="draftPeriod", visibility=["read", "create", "update"]) + """The period for the invoice to be kept in draft status for manual reviews.""" + due_after: Optional[str] = rest_field(name="dueAfter", visibility=["read", "create", "update"]) + """The period after which the invoice is due. With some payment solutions it's only applicable for + manual collection method.""" + progressive_billing: Optional[bool] = rest_field(name="progressiveBilling", visibility=["read", "create", "update"]) + """Should progressive billing be allowed for this workflow?.""" + subscription_end_proration_mode: Optional[ + Union[str, "_models.BillingWorkflowInvoicingSubscriptionEndProrationMode"] + ] = rest_field(name="subscriptionEndProrationMode", visibility=["read", "create", "update"]) + """Controls how subscription-ending shortened service periods are billed. Known values are: + \"bill_full_period\" and \"bill_actual_period\".""" + default_tax_config: Optional["_models.TaxConfig"] = rest_field( + name="defaultTaxConfig", visibility=["read", "create", "update"] + ) + """Default tax configuration to apply to the invoices. + + Setting a tax code (``stripe.code`` / ``taxCodeId``) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and ``behavior`` remains + fully supported.""" + + @overload + def __init__( + self, + *, + auto_advance: Optional[bool] = None, + draft_period: Optional[str] = None, + due_after: Optional[str] = None, + progressive_billing: Optional[bool] = None, + subscription_end_proration_mode: Optional[ + Union[str, "_models.BillingWorkflowInvoicingSubscriptionEndProrationMode"] + ] = None, + default_tax_config: Optional["_models.TaxConfig"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowPaymentSettings(_Model): + """Workflow payment settings. + + :ivar collection_method: The payment method for the invoice. Known values are: + "charge_automatically" and "send_invoice". + :vartype collection_method: str or ~openmeter.models.CollectionMethod + """ + + collection_method: Optional[Union[str, "_models.CollectionMethod"]] = rest_field( + name="collectionMethod", visibility=["read", "create", "update"] + ) + """The payment method for the invoice. Known values are: \"charge_automatically\" and + \"send_invoice\".""" + + @overload + def __init__( + self, + *, + collection_method: Optional[Union[str, "_models.CollectionMethod"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class BillingWorkflowTaxSettings(_Model): + """Workflow tax settings. + + :ivar enabled: Enable automatic tax calculation when tax is supported by the app. For example, + with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + :vartype enabled: bool + :ivar enforced: Enforce tax calculation when tax is supported by the app. When enabled, + OpenMeter will not allow to create an invoice without tax calculation. Enforcement is different + per apps, for example, Stripe app requires customer to have a tax location when starting a paid + subscription. + :vartype enforced: bool + """ + + enabled: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Enable automatic tax calculation when tax is supported by the app. For example, with Stripe + Invoicing when enabled, tax is calculated via Stripe Tax.""" + enforced: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Enforce tax calculation when tax is supported by the app. When enabled, OpenMeter will not + allow to create an invoice without tax calculation. Enforcement is different per apps, for + example, Stripe app requires customer to have a tax location when starting a paid subscription.""" + + @overload + def __init__( + self, + *, + enabled: Optional[bool] = None, + enforced: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CancelRequest(_Model): + """CancelRequest. + + :ivar timing: If not provided the subscription is canceled immediately. Is either a Union[str, + "_models.SubscriptionTimingEnum"] type or a datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + """ + + timing: Optional["_types.SubscriptionTiming"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """If not provided the subscription is canceled immediately. Is either a Union[str, + \"_models.SubscriptionTimingEnum\"] type or a datetime.datetime type.""" + + @overload + def __init__( + self, + *, + timing: Optional["_types.SubscriptionTiming"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CheckoutSessionCustomTextAfterSubmitParams(_Model): # pylint: disable=name-too-long + """Stripe CheckoutSession.custom_text. + + :ivar after_submit: Custom text that should be displayed after the payment confirmation button. + :vartype after_submit: ~openmeter._generated.models.CheckoutSessionCustomTextParamsAfterSubmit + :ivar shipping_address: Custom text that should be displayed alongside shipping address + collection. + :vartype shipping_address: + ~openmeter._generated.models.CheckoutSessionCustomTextParamsShippingAddress + :ivar submit: Custom text that should be displayed alongside the payment confirmation button. + :vartype submit: ~openmeter._generated.models.CheckoutSessionCustomTextParamsSubmit + :ivar terms_of_service_acceptance: Custom text that should be displayed in place of the default + terms of service agreement text. + :vartype terms_of_service_acceptance: + ~openmeter._generated.models.CheckoutSessionCustomTextParamsTermsOfServiceAcceptance + """ + + after_submit: Optional["_models.CheckoutSessionCustomTextParamsAfterSubmit"] = rest_field( + name="afterSubmit", visibility=["read", "create", "update", "delete", "query"] + ) + """Custom text that should be displayed after the payment confirmation button.""" + shipping_address: Optional["_models.CheckoutSessionCustomTextParamsShippingAddress"] = rest_field( + name="shippingAddress", visibility=["read", "create", "update", "delete", "query"] + ) + """Custom text that should be displayed alongside shipping address collection.""" + submit: Optional["_models.CheckoutSessionCustomTextParamsSubmit"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Custom text that should be displayed alongside the payment confirmation button.""" + terms_of_service_acceptance: Optional["_models.CheckoutSessionCustomTextParamsTermsOfServiceAcceptance"] = ( + rest_field(name="termsOfServiceAcceptance", visibility=["read", "create", "update", "delete", "query"]) + ) + """Custom text that should be displayed in place of the default terms of service agreement text.""" + + @overload + def __init__( + self, + *, + after_submit: Optional["_models.CheckoutSessionCustomTextParamsAfterSubmit"] = None, + shipping_address: Optional["_models.CheckoutSessionCustomTextParamsShippingAddress"] = None, + submit: Optional["_models.CheckoutSessionCustomTextParamsSubmit"] = None, + terms_of_service_acceptance: Optional["_models.CheckoutSessionCustomTextParamsTermsOfServiceAcceptance"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CheckoutSessionCustomTextParamsAfterSubmit(_Model): # pylint: disable=name-too-long + """CheckoutSessionCustomTextParamsAfterSubmit. + + :ivar message: + :vartype message: str + """ + + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CheckoutSessionCustomTextParamsShippingAddress(_Model): # pylint: disable=name-too-long + """CheckoutSessionCustomTextParamsShippingAddress. + + :ivar message: + :vartype message: str + """ + + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CheckoutSessionCustomTextParamsSubmit(_Model): + """CheckoutSessionCustomTextParamsSubmit. + + :ivar message: + :vartype message: str + """ + + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CheckoutSessionCustomTextParamsTermsOfServiceAcceptance(_Model): # pylint: disable=name-too-long + """CheckoutSessionCustomTextParamsTermsOfServiceAcceptance. + + :ivar message: + :vartype message: str + """ + + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ClientAppStartResponse(_Model): + """Response from the client app (OpenMeter backend) to start the OAuth2 flow. + + :ivar url: The URL to start the OAuth2 authorization code grant flow. Required. + :vartype url: str + """ + + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URL to start the OAuth2 authorization code grant flow. Required.""" + + @overload + def __init__( + self, + *, + url: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ConflictProblemResponse(UnexpectedProblemResponse): + """The request could not be completed due to a conflict with the current state of the target + resource. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateCheckoutSessionTaxIdCollection(_Model): + """Create Stripe checkout session tax ID collection. + + :ivar enabled: Enable tax ID collection during checkout. Defaults to false. Required. + :vartype enabled: bool + :ivar required: Describes whether a tax ID is required during checkout. Defaults to never. + Known values are: "if_supported" and "never". + :vartype required: str or ~openmeter.models.CreateCheckoutSessionTaxIdCollectionRequired + """ + + enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Enable tax ID collection during checkout. Defaults to false. Required.""" + required: Optional[Union[str, "_models.CreateCheckoutSessionTaxIdCollectionRequired"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Describes whether a tax ID is required during checkout. Defaults to never. Known values are: + \"if_supported\" and \"never\".""" + + @overload + def __init__( + self, + *, + enabled: bool, + required: Optional[Union[str, "_models.CreateCheckoutSessionTaxIdCollectionRequired"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCheckoutSessionConsentCollection(_Model): # pylint: disable=name-too-long + """Configure fields for the Checkout Session to gather active consent from customers. + + :ivar payment_method_reuse_agreement: Determines the position and visibility of the payment + method reuse agreement in the UI. When set to auto, Stripe’s defaults will be used. When set to + hidden, the payment method reuse agreement text will always be hidden in the UI. + :vartype payment_method_reuse_agreement: + ~openmeter._generated.models.CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement + :ivar promotions: If set to auto, enables the collection of customer consent for promotional + communications. The Checkout Session will determine whether to display an option to opt into + promotional communication from the merchant depending on the customer’s locale. Only available + to US merchants. Known values are: "auto" and "none". + :vartype promotions: str or + ~openmeter.models.CreateStripeCheckoutSessionConsentCollectionPromotions + :ivar terms_of_service: If set to required, it requires customers to check a terms of service + checkbox before being able to pay. There must be a valid terms of service URL set in your + Stripe Dashboard settings. `https://dashboard.stripe.com/settings/public + `_. Known values are: "none" and "required". + :vartype terms_of_service: str or + ~openmeter.models.CreateStripeCheckoutSessionConsentCollectionTermsOfService + """ + + payment_method_reuse_agreement: Optional[ + "_models.CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement" + ] = rest_field(name="paymentMethodReuseAgreement", visibility=["read", "create", "update", "delete", "query"]) + """Determines the position and visibility of the payment method reuse agreement in the UI. When + set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse + agreement text will always be hidden in the UI.""" + promotions: Optional[Union[str, "_models.CreateStripeCheckoutSessionConsentCollectionPromotions"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """If set to auto, enables the collection of customer consent for promotional communications. The + Checkout Session will determine whether to display an option to opt into promotional + communication from the merchant depending on the customer’s locale. Only available to US + merchants. Known values are: \"auto\" and \"none\".""" + terms_of_service: Optional[Union[str, "_models.CreateStripeCheckoutSessionConsentCollectionTermsOfService"]] = ( + rest_field(name="termsOfService", visibility=["read", "create", "update", "delete", "query"]) + ) + """If set to required, it requires customers to check a terms of service checkbox before being + able to pay. There must be a valid terms of service URL set in your Stripe Dashboard settings. + `https://dashboard.stripe.com/settings/public `_. + Known values are: \"none\" and \"required\".""" + + @overload + def __init__( + self, + *, + payment_method_reuse_agreement: Optional[ + "_models.CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement" + ] = None, + promotions: Optional[Union[str, "_models.CreateStripeCheckoutSessionConsentCollectionPromotions"]] = None, + terms_of_service: Optional[ + Union[str, "_models.CreateStripeCheckoutSessionConsentCollectionTermsOfService"] + ] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement(_Model): # pylint: disable=name-too-long + """Create Stripe checkout session payment method reuse agreement. + + :ivar position: Known values are: "auto" and "hidden". + :vartype position: str or + ~openmeter.models.CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition + """ + + position: Optional[ + Union[str, "_models.CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition"] + ] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Known values are: \"auto\" and \"hidden\".""" + + @overload + def __init__( + self, + *, + position: Optional[ + Union[str, "_models.CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition"] + ] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCheckoutSessionCustomerUpdate(_Model): # pylint: disable=name-too-long + """Controls what fields on Customer can be updated by the Checkout Session. + + :ivar address: Describes whether Checkout saves the billing address onto customer.address. To + always collect a full billing address, use billing_address_collection. Defaults to never. Known + values are: "auto" and "never". + :vartype address: str or ~openmeter.models.CreateStripeCheckoutSessionCustomerUpdateBehavior + :ivar name: Describes whether Checkout saves the name onto customer.name. Defaults to never. + Known values are: "auto" and "never". + :vartype name: str or ~openmeter.models.CreateStripeCheckoutSessionCustomerUpdateBehavior + :ivar shipping: Describes whether Checkout saves shipping information onto customer.shipping. + To collect shipping information, use shipping_address_collection. Defaults to never. Known + values are: "auto" and "never". + :vartype shipping: str or ~openmeter.models.CreateStripeCheckoutSessionCustomerUpdateBehavior + """ + + address: Optional[Union[str, "_models.CreateStripeCheckoutSessionCustomerUpdateBehavior"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Describes whether Checkout saves the billing address onto customer.address. To always collect a + full billing address, use billing_address_collection. Defaults to never. Known values are: + \"auto\" and \"never\".""" + name: Optional[Union[str, "_models.CreateStripeCheckoutSessionCustomerUpdateBehavior"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Describes whether Checkout saves the name onto customer.name. Defaults to never. Known values + are: \"auto\" and \"never\".""" + shipping: Optional[Union[str, "_models.CreateStripeCheckoutSessionCustomerUpdateBehavior"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Describes whether Checkout saves shipping information onto customer.shipping. To collect + shipping information, use shipping_address_collection. Defaults to never. Known values are: + \"auto\" and \"never\".""" + + @overload + def __init__( + self, + *, + address: Optional[Union[str, "_models.CreateStripeCheckoutSessionCustomerUpdateBehavior"]] = None, + name: Optional[Union[str, "_models.CreateStripeCheckoutSessionCustomerUpdateBehavior"]] = None, + shipping: Optional[Union[str, "_models.CreateStripeCheckoutSessionCustomerUpdateBehavior"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCheckoutSessionRequest(_Model): + """Create Stripe checkout session request. + + :ivar app_id: If not provided, the default Stripe app is used if any. + :vartype app_id: str + :ivar customer: Provide a customer ID or key to use an existing OpenMeter customer. or provide + a customer object to create a new customer. Required. Is one of the following types: + CustomerId, CustomerKey, CustomerCreate + :vartype customer: ~openmeter._generated.models.CustomerId or + ~openmeter._generated.models.CustomerKey or ~openmeter._generated.models.CustomerCreate + :ivar stripe_customer_id: Stripe customer ID. If not provided OpenMeter creates a new Stripe + customer or uses the OpenMeter customer's default Stripe customer ID. + :vartype stripe_customer_id: str + :ivar options: Options passed to Stripe when creating the checkout session. Required. + :vartype options: ~openmeter._generated.models.CreateStripeCheckoutSessionRequestOptions + """ + + app_id: Optional[str] = rest_field(name="appId", visibility=["read", "create", "update", "delete", "query"]) + """If not provided, the default Stripe app is used if any.""" + customer: Union["_models.CustomerId", "_models.CustomerKey", "_models.CustomerCreate"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Provide a customer ID or key to use an existing OpenMeter customer. or provide a customer + object to create a new customer. Required. Is one of the following types: CustomerId, + CustomerKey, CustomerCreate""" + stripe_customer_id: Optional[str] = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """Stripe customer ID. If not provided OpenMeter creates a new Stripe customer or uses the + OpenMeter customer's default Stripe customer ID.""" + options: "_models.CreateStripeCheckoutSessionRequestOptions" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Options passed to Stripe when creating the checkout session. Required.""" + + @overload + def __init__( + self, + *, + customer: Union["_models.CustomerId", "_models.CustomerKey", "_models.CustomerCreate"], + options: "_models.CreateStripeCheckoutSessionRequestOptions", + app_id: Optional[str] = None, + stripe_customer_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCheckoutSessionRequestOptions(_Model): # pylint: disable=name-too-long + """Create Stripe checkout session options See + `https://docs.stripe.com/api/checkout/sessions/create + `_. + + :ivar billing_address_collection: Specify whether Checkout should collect the customer’s + billing address. Defaults to auto. Known values are: "auto" and "required". + :vartype billing_address_collection: str or + ~openmeter.models.CreateStripeCheckoutSessionBillingAddressCollection + :ivar cancel_url: If set, Checkout displays a back button and customers will be directed to + this URL if they decide to cancel payment and return to your website. This parameter is not + allowed if ui_mode is embedded. + :vartype cancel_url: str + :ivar client_reference_id: A unique string to reference the Checkout Session. This can be a + customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal + systems. + :vartype client_reference_id: str + :ivar customer_update: Controls what fields on Customer can be updated by the Checkout Session. + :vartype customer_update: + ~openmeter._generated.models.CreateStripeCheckoutSessionCustomerUpdate + :ivar consent_collection: Configure fields for the Checkout Session to gather active consent + from customers. + :vartype consent_collection: + ~openmeter._generated.models.CreateStripeCheckoutSessionConsentCollection + :ivar currency: Three-letter ISO currency code, in lowercase. + :vartype currency: str + :ivar custom_text: Display additional text for your customers using custom text. + :vartype custom_text: ~openmeter._generated.models.CheckoutSessionCustomTextAfterSubmitParams + :ivar expires_at: The Epoch time in seconds at which the Checkout Session will expire. It can + be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value + is 24 hours from creation. + :vartype expires_at: int + :ivar locale: + :vartype locale: str + :ivar metadata: Set of key-value pairs that you can attach to an object. This can be useful for + storing additional information about the object in a structured format. Individual keys can be + unset by posting an empty value to them. All keys can be unset by posting an empty value to + metadata. + :vartype metadata: dict[str, str] + :ivar return_url: The URL to redirect your customer back to after they authenticate or cancel + their payment on the payment method’s app or site. This parameter is required if ui_mode is + embedded and redirect-based payment methods are enabled on the session. + :vartype return_url: str + :ivar success_url: The URL to which Stripe should send customers when payment or setup is + complete. This parameter is not allowed if ui_mode is embedded. If you’d like to use + information from the successful Checkout Session on your page, read the guide on customizing + your success page: `https://docs.stripe.com/payments/checkout/custom-success-page + `_. + :vartype success_url: str + :ivar ui_mode: The UI mode of the Session. Defaults to hosted. Known values are: "embedded" and + "hosted". + :vartype ui_mode: str or ~openmeter.models.CheckoutSessionUIMode + :ivar payment_method_types: A list of the types of payment methods (e.g., card) this Checkout + Session can accept. + :vartype payment_method_types: list[str] + :ivar redirect_on_completion: This parameter applies to ui_mode: embedded. Defaults to always. + Learn more about the redirect behavior of embedded sessions at + `https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + `_. + Known values are: "always", "if_required", and "never". + :vartype redirect_on_completion: str or + ~openmeter.models.CreateStripeCheckoutSessionRedirectOnCompletion + :ivar tax_id_collection: Controls tax ID collection during checkout. + :vartype tax_id_collection: ~openmeter._generated.models.CreateCheckoutSessionTaxIdCollection + """ + + billing_address_collection: Optional[Union[str, "_models.CreateStripeCheckoutSessionBillingAddressCollection"]] = ( + rest_field(name="billingAddressCollection", visibility=["read", "create", "update", "delete", "query"]) + ) + """Specify whether Checkout should collect the customer’s billing address. Defaults to auto. Known + values are: \"auto\" and \"required\".""" + cancel_url: Optional[str] = rest_field(name="cancelURL", visibility=["read", "create", "update", "delete", "query"]) + """If set, Checkout displays a back button and customers will be directed to this URL if they + decide to cancel payment and return to your website. This parameter is not allowed if ui_mode + is embedded.""" + client_reference_id: Optional[str] = rest_field( + name="clientReferenceID", visibility=["read", "create", "update", "delete", "query"] + ) + """A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or + similar, and can be used to reconcile the session with your internal systems.""" + customer_update: Optional["_models.CreateStripeCheckoutSessionCustomerUpdate"] = rest_field( + name="customerUpdate", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls what fields on Customer can be updated by the Checkout Session.""" + consent_collection: Optional["_models.CreateStripeCheckoutSessionConsentCollection"] = rest_field( + name="consentCollection", visibility=["read", "create", "update", "delete", "query"] + ) + """Configure fields for the Checkout Session to gather active consent from customers.""" + currency: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Three-letter ISO currency code, in lowercase.""" + custom_text: Optional["_models.CheckoutSessionCustomTextAfterSubmitParams"] = rest_field( + name="customText", visibility=["read", "create", "update", "delete", "query"] + ) + """Display additional text for your customers using custom text.""" + expires_at: Optional[int] = rest_field(name="expiresAt", visibility=["read", "create", "update", "delete", "query"]) + """The Epoch time in seconds at which the Checkout Session will expire. It can be anywhere from 30 + minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from + creation.""" + locale: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + metadata: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Set of key-value pairs that you can attach to an object. This can be useful for storing + additional information about the object in a structured format. Individual keys can be unset by + posting an empty value to them. All keys can be unset by posting an empty value to metadata.""" + return_url: Optional[str] = rest_field(name="returnURL", visibility=["read", "create", "update", "delete", "query"]) + """The URL to redirect your customer back to after they authenticate or cancel their payment on + the payment method’s app or site. This parameter is required if ui_mode is embedded and + redirect-based payment methods are enabled on the session.""" + success_url: Optional[str] = rest_field( + name="successURL", visibility=["read", "create", "update", "delete", "query"] + ) + """The URL to which Stripe should send customers when payment or setup is complete. This parameter + is not allowed if ui_mode is embedded. If you’d like to use information from the successful + Checkout Session on your page, read the guide on customizing your success page: + `https://docs.stripe.com/payments/checkout/custom-success-page + `_.""" + ui_mode: Optional[Union[str, "_models.CheckoutSessionUIMode"]] = rest_field( + name="uiMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The UI mode of the Session. Defaults to hosted. Known values are: \"embedded\" and \"hosted\".""" + payment_method_types: Optional[list[str]] = rest_field( + name="paymentMethodTypes", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of the types of payment methods (e.g., card) this Checkout Session can accept.""" + redirect_on_completion: Optional[Union[str, "_models.CreateStripeCheckoutSessionRedirectOnCompletion"]] = ( + rest_field(name="redirectOnCompletion", visibility=["read", "create", "update", "delete", "query"]) + ) + """This parameter applies to ui_mode: embedded. Defaults to always. Learn more about the redirect + behavior of embedded sessions at + `https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + `_. + Known values are: \"always\", \"if_required\", and \"never\".""" + tax_id_collection: Optional["_models.CreateCheckoutSessionTaxIdCollection"] = rest_field( + name="taxIdCollection", visibility=["read", "create", "update", "delete", "query"] + ) + """Controls tax ID collection during checkout.""" + + @overload + def __init__( + self, + *, + billing_address_collection: Optional[ + Union[str, "_models.CreateStripeCheckoutSessionBillingAddressCollection"] + ] = None, + cancel_url: Optional[str] = None, + client_reference_id: Optional[str] = None, + customer_update: Optional["_models.CreateStripeCheckoutSessionCustomerUpdate"] = None, + consent_collection: Optional["_models.CreateStripeCheckoutSessionConsentCollection"] = None, + currency: Optional[str] = None, + custom_text: Optional["_models.CheckoutSessionCustomTextAfterSubmitParams"] = None, + expires_at: Optional[int] = None, + locale: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + return_url: Optional[str] = None, + success_url: Optional[str] = None, + ui_mode: Optional[Union[str, "_models.CheckoutSessionUIMode"]] = None, + payment_method_types: Optional[list[str]] = None, + redirect_on_completion: Optional[Union[str, "_models.CreateStripeCheckoutSessionRedirectOnCompletion"]] = None, + tax_id_collection: Optional["_models.CreateCheckoutSessionTaxIdCollection"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCheckoutSessionResult(_Model): + """Create Stripe Checkout Session response. + + :ivar customer_id: The OpenMeter customer ID. Required. + :vartype customer_id: str + :ivar stripe_customer_id: The Stripe customer ID. Required. + :vartype stripe_customer_id: str + :ivar session_id: The checkout session ID. Required. + :vartype session_id: str + :ivar setup_intent_id: The checkout session setup intent ID. Required. + :vartype setup_intent_id: str + :ivar client_secret: The client secret of the checkout session. This can be used to initialize + Stripe.js for your client-side implementation. + :vartype client_secret: str + :ivar client_reference_id: A unique string to reference the Checkout Session. This can be a + customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal + systems. + :vartype client_reference_id: str + :ivar customer_email: Customer's email address provided to Stripe. + :vartype customer_email: str + :ivar currency: Three-letter ISO currency code, in lowercase. + :vartype currency: str + :ivar created_at: Timestamp at which the checkout session was created. Required. + :vartype created_at: ~datetime.datetime + :ivar expires_at: Timestamp at which the checkout session will expire. + :vartype expires_at: ~datetime.datetime + :ivar metadata: Set of key-value pairs attached to the checkout session. + :vartype metadata: dict[str, str] + :ivar status: The status of the checkout session. + :vartype status: str + :ivar url: URL to show the checkout session. + :vartype url: str + :ivar mode: Mode Always ``setup`` for now. Required. "setup" + :vartype mode: str or ~openmeter.models.StripeCheckoutSessionMode + :ivar cancel_url: Cancel URL. + :vartype cancel_url: str + :ivar success_url: Success URL. + :vartype success_url: str + :ivar return_url: Return URL. + :vartype return_url: str + """ + + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The OpenMeter customer ID. Required.""" + stripe_customer_id: str = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe customer ID. Required.""" + session_id: str = rest_field(name="sessionId", visibility=["read", "create", "update", "delete", "query"]) + """The checkout session ID. Required.""" + setup_intent_id: str = rest_field(name="setupIntentId", visibility=["read", "create", "update", "delete", "query"]) + """The checkout session setup intent ID. Required.""" + client_secret: Optional[str] = rest_field( + name="clientSecret", visibility=["read", "create", "update", "delete", "query"] + ) + """The client secret of the checkout session. This can be used to initialize Stripe.js for your + client-side implementation.""" + client_reference_id: Optional[str] = rest_field( + name="clientReferenceId", visibility=["read", "create", "update", "delete", "query"] + ) + """A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or + similar, and can be used to reconcile the session with your internal systems.""" + customer_email: Optional[str] = rest_field( + name="customerEmail", visibility=["read", "create", "update", "delete", "query"] + ) + """Customer's email address provided to Stripe.""" + currency: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Three-letter ISO currency code, in lowercase.""" + created_at: datetime.datetime = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Timestamp at which the checkout session was created. Required.""" + expires_at: Optional[datetime.datetime] = rest_field( + name="expiresAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Timestamp at which the checkout session will expire.""" + metadata: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Set of key-value pairs attached to the checkout session.""" + status: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The status of the checkout session.""" + url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """URL to show the checkout session.""" + mode: Union[str, "_models.StripeCheckoutSessionMode"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Mode Always ``setup`` for now. Required. \"setup\"""" + cancel_url: Optional[str] = rest_field(name="cancelURL", visibility=["read", "create", "update", "delete", "query"]) + """Cancel URL.""" + success_url: Optional[str] = rest_field( + name="successURL", visibility=["read", "create", "update", "delete", "query"] + ) + """Success URL.""" + return_url: Optional[str] = rest_field(name="returnURL", visibility=["read", "create", "update", "delete", "query"]) + """Return URL.""" + + @overload + def __init__( + self, + *, + customer_id: str, + stripe_customer_id: str, + session_id: str, + setup_intent_id: str, + created_at: datetime.datetime, + mode: Union[str, "_models.StripeCheckoutSessionMode"], + client_secret: Optional[str] = None, + client_reference_id: Optional[str] = None, + customer_email: Optional[str] = None, + currency: Optional[str] = None, + expires_at: Optional[datetime.datetime] = None, + metadata: Optional[dict[str, str]] = None, + status: Optional[str] = None, + url: Optional[str] = None, + cancel_url: Optional[str] = None, + success_url: Optional[str] = None, + return_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CreateStripeCustomerPortalSessionParams(_Model): + """Stripe customer portal request params. + + :ivar configuration_id: Configuration. + :vartype configuration_id: str + :ivar locale: Locale. + :vartype locale: str + :ivar return_url: ReturnUrl. + :vartype return_url: str + """ + + configuration_id: Optional[str] = rest_field( + name="configurationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Configuration.""" + locale: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Locale.""" + return_url: Optional[str] = rest_field(name="returnUrl", visibility=["read", "create", "update", "delete", "query"]) + """ReturnUrl.""" + + @overload + def __init__( + self, + *, + configuration_id: Optional[str] = None, + locale: Optional[str] = None, + return_url: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceGenericDocumentRef(_Model): + """InvoiceGenericDocumentRef is used to describe an existing document or a specific part of it's + contents. + + :ivar type: Type of the document referenced. Required. "credit_note_original_invoice" + :vartype type: str or ~openmeter.models.InvoiceDocumentRefType + :ivar reason: Human readable description on why this reference is here or needs to be used. + :vartype reason: str + :ivar description: Additional details about the document. + :vartype description: str + """ + + type: Union[str, "_models.InvoiceDocumentRefType"] = rest_field(visibility=["read"]) + """Type of the document referenced. Required. \"credit_note_original_invoice\"""" + reason: Optional[str] = rest_field(visibility=["read"]) + """Human readable description on why this reference is here or needs to be used.""" + description: Optional[str] = rest_field(visibility=["read"]) + """Additional details about the document.""" + + +class CreditNoteOriginalInvoiceRef(InvoiceGenericDocumentRef): + """CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is + based on. + + :ivar reason: Human readable description on why this reference is here or needs to be used. + :vartype reason: str + :ivar description: Additional details about the document. + :vartype description: str + :ivar type: Type of the invoice. Required. CREDIT_NOTE_ORIGINAL_INVOICE. + :vartype type: str or ~openmeter._generated.models.CREDIT_NOTE_ORIGINAL_INVOICE + :ivar issued_at: IssueAt reflects the time the document was issued. + :vartype issued_at: ~datetime.datetime + :ivar number: (Serial) Number of the referenced document. + :vartype number: str + :ivar url: Link to the source document. Required. + :vartype url: str + """ + + type: Literal[InvoiceDocumentRefType.CREDIT_NOTE_ORIGINAL_INVOICE] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Type of the invoice. Required. CREDIT_NOTE_ORIGINAL_INVOICE.""" + issued_at: Optional[datetime.datetime] = rest_field(name="issuedAt", visibility=["read"], format="rfc3339") + """IssueAt reflects the time the document was issued.""" + number: Optional[str] = rest_field(visibility=["read"]) + """(Serial) Number of the referenced document.""" + url: str = rest_field(visibility=["read"]) + """Link to the source document. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[InvoiceDocumentRefType.CREDIT_NOTE_ORIGINAL_INVOICE], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Currency(_Model): + """Currency describes a currency supported by OpenMeter. + + :ivar code: The currency ISO code. Required. + :vartype code: str + :ivar name: The currency name. Required. + :vartype name: str + :ivar symbol: The currency symbol. Required. + :vartype symbol: str + :ivar subunits: Subunit of the currency. Required. + :vartype subunits: int + """ + + code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The currency ISO code. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The currency name. Required.""" + symbol: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The currency symbol. Required.""" + subunits: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Subunit of the currency. Required.""" + + @overload + def __init__( + self, + *, + code: str, + name: str, + symbol: str, + subunits: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Customer(_Model): + """A customer object. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar key: Key. + :vartype key: str + :ivar usage_attribution: Usage Attribution. + :vartype usage_attribution: ~openmeter._generated.models.CustomerUsageAttribution + :ivar primary_email: Primary Email. + :vartype primary_email: str + :ivar currency: Currency. + :vartype currency: str + :ivar billing_address: Billing Address. + :vartype billing_address: ~openmeter._generated.models.Address + :ivar current_subscription_id: Current Subscription ID. + :vartype current_subscription_id: str + :ivar subscriptions: Subscriptions. + :vartype subscriptions: list[~openmeter._generated.models.Subscription] + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key.""" + usage_attribution: Optional["_models.CustomerUsageAttribution"] = rest_field( + name="usageAttribution", visibility=["read", "create", "update", "delete", "query"] + ) + """Usage Attribution.""" + primary_email: Optional[str] = rest_field( + name="primaryEmail", visibility=["read", "create", "update", "delete", "query"] + ) + """Primary Email.""" + currency: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency.""" + billing_address: Optional["_models.Address"] = rest_field( + name="billingAddress", visibility=["read", "create", "update", "delete", "query"] + ) + """Billing Address.""" + current_subscription_id: Optional[str] = rest_field(name="currentSubscriptionId", visibility=["read"]) + """Current Subscription ID.""" + subscriptions: Optional[list["_models.Subscription"]] = rest_field(visibility=["read"]) + """Subscriptions.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + key: Optional[str] = None, + usage_attribution: Optional["_models.CustomerUsageAttribution"] = None, + primary_email: Optional[str] = None, + currency: Optional[str] = None, + billing_address: Optional["_models.Address"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerAccess(_Model): + """CustomerAccess describes what features the customer has access to. + + :ivar entitlements: Map of entitlements the customer has access to. The key is the feature key, + the value is the entitlement value + the entitlement ID. Required. + :vartype entitlements: dict[str, ~openmeter._generated.models.EntitlementValue] + """ + + entitlements: dict[str, "_models.EntitlementValue"] = rest_field(visibility=["read"]) + """Map of entitlements the customer has access to. The key is the feature key, the value is the + entitlement value + the entitlement ID. Required.""" + + +class CustomerAppDataPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_types.CustomerAppData"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_types.CustomerAppData"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerCreate(_Model): + """Resource create operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar key: Key. + :vartype key: str + :ivar usage_attribution: Usage Attribution. + :vartype usage_attribution: ~openmeter._generated.models.CustomerUsageAttribution + :ivar primary_email: Primary Email. + :vartype primary_email: str + :ivar currency: Currency. + :vartype currency: str + :ivar billing_address: Billing Address. + :vartype billing_address: ~openmeter._generated.models.Address + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key.""" + usage_attribution: Optional["_models.CustomerUsageAttribution"] = rest_field( + name="usageAttribution", visibility=["read", "create", "update", "delete", "query"] + ) + """Usage Attribution.""" + primary_email: Optional[str] = rest_field( + name="primaryEmail", visibility=["read", "create", "update", "delete", "query"] + ) + """Primary Email.""" + currency: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency.""" + billing_address: Optional["_models.Address"] = rest_field( + name="billingAddress", visibility=["read", "create", "update", "delete", "query"] + ) + """Billing Address.""" + + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + key: Optional[str] = None, + usage_attribution: Optional["_models.CustomerUsageAttribution"] = None, + primary_email: Optional[str] = None, + currency: Optional[str] = None, + billing_address: Optional["_models.Address"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerId(_Model): + """Create Stripe checkout session with customer ID. + + :ivar id: Required. + :vartype id: str + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerKey(_Model): + """Create Stripe checkout session with customer key. + + :ivar key: Required. + :vartype key: str + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + key: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.Customer] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.Customer"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.Customer"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerReplaceUpdate(_Model): + """Resource update operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar key: Key. + :vartype key: str + :ivar usage_attribution: Usage Attribution. + :vartype usage_attribution: ~openmeter._generated.models.CustomerUsageAttribution + :ivar primary_email: Primary Email. + :vartype primary_email: str + :ivar currency: Currency. + :vartype currency: str + :ivar billing_address: Billing Address. + :vartype billing_address: ~openmeter._generated.models.Address + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key.""" + usage_attribution: Optional["_models.CustomerUsageAttribution"] = rest_field( + name="usageAttribution", visibility=["read", "create", "update", "delete", "query"] + ) + """Usage Attribution.""" + primary_email: Optional[str] = rest_field( + name="primaryEmail", visibility=["read", "create", "update", "delete", "query"] + ) + """Primary Email.""" + currency: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency.""" + billing_address: Optional["_models.Address"] = rest_field( + name="billingAddress", visibility=["read", "create", "update", "delete", "query"] + ) + """Billing Address.""" + + @overload + def __init__( + self, + *, + name: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + key: Optional[str] = None, + usage_attribution: Optional["_models.CustomerUsageAttribution"] = None, + primary_email: Optional[str] = None, + currency: Optional[str] = None, + billing_address: Optional["_models.Address"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomerUsageAttribution(_Model): + """Mapping to attribute metered usage to the customer. One customer can have zero or more + subjects, but one subject can only belong to one customer. + + :ivar subject_keys: SubjectKeys. Required. + :vartype subject_keys: list[str] + """ + + subject_keys: list[str] = rest_field(name="subjectKeys", visibility=["read", "create", "update", "delete", "query"]) + """SubjectKeys. Required.""" + + @overload + def __init__( + self, + *, + subject_keys: list[str], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingApp(_Model): + """Custom Invoicing app can be used for interface with any invoicing or payment system. + + This app provides ways to manipulate invoices and payments, however the integration + must rely on Notifications API to get notified about invoice changes. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar listing: The marketplace listing that this installed app is based on. Required. + :vartype listing: ~openmeter._generated.models.MarketplaceListing + :ivar status: Status of the app connection. Required. Known values are: "ready" and + "unauthorized". + :vartype status: str or ~openmeter.models.AppStatus + :ivar type: The app's type is CustomInvoicing. Required. CUSTOM_INVOICING. + :vartype type: str or ~openmeter._generated.models.CUSTOM_INVOICING + :ivar enable_draft_sync_hook: Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required. + :vartype enable_draft_sync_hook: bool + :ivar enable_issuing_sync_hook: Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required. + :vartype enable_issuing_sync_hook: bool + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + listing: "_models.MarketplaceListing" = rest_field(visibility=["read"]) + """The marketplace listing that this installed app is based on. Required.""" + status: Union[str, "_models.AppStatus"] = rest_field(visibility=["read"]) + """Status of the app connection. Required. Known values are: \"ready\" and \"unauthorized\".""" + type: Literal[AppType.CUSTOM_INVOICING] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type is CustomInvoicing. Required. CUSTOM_INVOICING.""" + enable_draft_sync_hook: bool = rest_field( + name="enableDraftSyncHook", visibility=["read", "create", "update", "delete", "query"] + ) + """Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required.""" + enable_issuing_sync_hook: bool = rest_field( + name="enableIssuingSyncHook", visibility=["read", "create", "update", "delete", "query"] + ) + """Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required.""" + + @overload + def __init__( + self, + *, + name: str, + type: Literal[AppType.CUSTOM_INVOICING], + enable_draft_sync_hook: bool, + enable_issuing_sync_hook: bool, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingAppReplaceUpdate(_Model): + """Resource update operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: The app's type is CustomInvoicing. Required. CUSTOM_INVOICING. + :vartype type: str or ~openmeter._generated.models.CUSTOM_INVOICING + :ivar enable_draft_sync_hook: Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required. + :vartype enable_draft_sync_hook: bool + :ivar enable_issuing_sync_hook: Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required. + :vartype enable_issuing_sync_hook: bool + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + type: Literal[AppType.CUSTOM_INVOICING] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type is CustomInvoicing. Required. CUSTOM_INVOICING.""" + enable_draft_sync_hook: bool = rest_field( + name="enableDraftSyncHook", visibility=["read", "create", "update", "delete", "query"] + ) + """Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required.""" + enable_issuing_sync_hook: bool = rest_field( + name="enableIssuingSyncHook", visibility=["read", "create", "update", "delete", "query"] + ) + """Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + Required.""" + + @overload + def __init__( + self, + *, + name: str, + type: Literal[AppType.CUSTOM_INVOICING], + enable_draft_sync_hook: bool, + enable_issuing_sync_hook: bool, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingCustomerAppData(_Model): + """Custom Invoicing Customer App Data. + + :ivar app: The installed custom invoicing app this data belongs to. + :vartype app: ~openmeter._generated.models.CustomInvoicingApp + :ivar id: App ID. + :vartype id: str + :ivar type: App Type. Required. CUSTOM_INVOICING. + :vartype type: str or ~openmeter._generated.models.CUSTOM_INVOICING + :ivar metadata: Metadata to be used by the custom invoicing provider. + :vartype metadata: ~openmeter._generated.models.Metadata + """ + + app: Optional["_models.CustomInvoicingApp"] = rest_field(visibility=["read"]) + """The installed custom invoicing app this data belongs to.""" + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """App ID.""" + type: Literal[AppType.CUSTOM_INVOICING] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """App Type. Required. CUSTOM_INVOICING.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata to be used by the custom invoicing provider.""" + + @overload + def __init__( + self, + *, + type: Literal[AppType.CUSTOM_INVOICING], + id: Optional[str] = None, # pylint: disable=redefined-builtin + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingDraftSynchronizedRequest(_Model): + """Information to finalize the draft details of an invoice. + + :ivar invoicing: The result of the synchronization. + :vartype invoicing: ~openmeter._generated.models.CustomInvoicingSyncResult + """ + + invoicing: Optional["_models.CustomInvoicingSyncResult"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The result of the synchronization.""" + + @overload + def __init__( + self, + *, + invoicing: Optional["_models.CustomInvoicingSyncResult"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingFinalizedInvoicingRequest(_Model): + """Information to finalize the invoicing details of an invoice. + + :ivar invoice_number: If set the invoice's number will be set to this value. + :vartype invoice_number: str + :ivar sent_to_customer_at: If set the invoice's sent to customer at will be set to this value. + :vartype sent_to_customer_at: ~datetime.datetime + """ + + invoice_number: Optional[str] = rest_field( + name="invoiceNumber", visibility=["read", "create", "update", "delete", "query"] + ) + """If set the invoice's number will be set to this value.""" + sent_to_customer_at: Optional[datetime.datetime] = rest_field( + name="sentToCustomerAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """If set the invoice's sent to customer at will be set to this value.""" + + @overload + def __init__( + self, + *, + invoice_number: Optional[str] = None, + sent_to_customer_at: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingFinalizedPaymentRequest(_Model): + """Information to finalize the payment details of an invoice. + + :ivar external_id: If set the invoice's payment external ID will be set to this value. + :vartype external_id: str + """ + + external_id: Optional[str] = rest_field( + name="externalId", visibility=["read", "create", "update", "delete", "query"] + ) + """If set the invoice's payment external ID will be set to this value.""" + + @overload + def __init__( + self, + *, + external_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingFinalizedRequest(_Model): + """Information to finalize the invoice. + + If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- + prefix). + + :ivar invoicing: The result of the synchronization. + :vartype invoicing: ~openmeter._generated.models.CustomInvoicingFinalizedInvoicingRequest + :ivar payment: The result of the payment synchronization. + :vartype payment: ~openmeter._generated.models.CustomInvoicingFinalizedPaymentRequest + """ + + invoicing: Optional["_models.CustomInvoicingFinalizedInvoicingRequest"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The result of the synchronization.""" + payment: Optional["_models.CustomInvoicingFinalizedPaymentRequest"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The result of the payment synchronization.""" + + @overload + def __init__( + self, + *, + invoicing: Optional["_models.CustomInvoicingFinalizedInvoicingRequest"] = None, + payment: Optional["_models.CustomInvoicingFinalizedPaymentRequest"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingLineDiscountExternalIdMapping(_Model): # pylint: disable=name-too-long + """Mapping between line discounts and external IDs. + + :ivar line_discount_id: The line discount ID. Required. + :vartype line_discount_id: str + :ivar external_id: The external ID (e.g. custom invoicing system's ID). Required. + :vartype external_id: str + """ + + line_discount_id: str = rest_field( + name="lineDiscountId", visibility=["read", "create", "update", "delete", "query"] + ) + """The line discount ID. Required.""" + external_id: str = rest_field(name="externalId", visibility=["read", "create", "update", "delete", "query"]) + """The external ID (e.g. custom invoicing system's ID). Required.""" + + @overload + def __init__( + self, + *, + line_discount_id: str, + external_id: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingLineExternalIdMapping(_Model): + """Mapping between lines and external IDs. + + :ivar line_id: The line ID. Required. + :vartype line_id: str + :ivar external_id: The external ID (e.g. custom invoicing system's ID). Required. + :vartype external_id: str + """ + + line_id: str = rest_field(name="lineId", visibility=["read", "create", "update", "delete", "query"]) + """The line ID. Required.""" + external_id: str = rest_field(name="externalId", visibility=["read", "create", "update", "delete", "query"]) + """The external ID (e.g. custom invoicing system's ID). Required.""" + + @overload + def __init__( + self, + *, + line_id: str, + external_id: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingSyncResult(_Model): + """Information to synchronize the invoice. + + Can be used to store external app's IDs on the invoice or lines. + + :ivar invoice_number: If set the invoice's number will be set to this value. + :vartype invoice_number: str + :ivar external_id: If set the invoice's invoicing external ID will be set to this value. + :vartype external_id: str + :ivar line_external_ids: If set the invoice's line external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice. + :vartype line_external_ids: + list[~openmeter._generated.models.CustomInvoicingLineExternalIdMapping] + :ivar line_discount_external_ids: If set the invoice's line discount external IDs will be set + to this value. + + This can be used to reference the external system's entities in the + invoice. + :vartype line_discount_external_ids: + list[~openmeter._generated.models.CustomInvoicingLineDiscountExternalIdMapping] + """ + + invoice_number: Optional[str] = rest_field( + name="invoiceNumber", visibility=["read", "create", "update", "delete", "query"] + ) + """If set the invoice's number will be set to this value.""" + external_id: Optional[str] = rest_field( + name="externalId", visibility=["read", "create", "update", "delete", "query"] + ) + """If set the invoice's invoicing external ID will be set to this value.""" + line_external_ids: Optional[list["_models.CustomInvoicingLineExternalIdMapping"]] = rest_field( + name="lineExternalIds", visibility=["read", "create", "update", "delete", "query"] + ) + """If set the invoice's line external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice.""" + line_discount_external_ids: Optional[list["_models.CustomInvoicingLineDiscountExternalIdMapping"]] = rest_field( + name="lineDiscountExternalIds", visibility=["read", "create", "update", "delete", "query"] + ) + """If set the invoice's line discount external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice.""" + + @overload + def __init__( + self, + *, + invoice_number: Optional[str] = None, + external_id: Optional[str] = None, + line_external_ids: Optional[list["_models.CustomInvoicingLineExternalIdMapping"]] = None, + line_discount_external_ids: Optional[list["_models.CustomInvoicingLineDiscountExternalIdMapping"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingTaxConfig(_Model): + """Custom invoicing tax config. + + :ivar code: Tax code. Required. + :vartype code: str + """ + + code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tax code. Required.""" + + @overload + def __init__( + self, + *, + code: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomInvoicingUpdatePaymentStatusRequest(_Model): # pylint: disable=name-too-long + """Update payment status request. + + Can be used to manipulate invoice's payment status (when custominvoicing app is being used). + + :ivar trigger: The trigger to be executed on the invoice. Required. Known values are: "paid", + "payment_failed", "payment_uncollectible", "payment_overdue", "action_required", and "void". + :vartype trigger: str or ~openmeter.models.CustomInvoicingPaymentTrigger + """ + + trigger: Union[str, "_models.CustomInvoicingPaymentTrigger"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The trigger to be executed on the invoice. Required. Known values are: \"paid\", + \"payment_failed\", \"payment_uncollectible\", \"payment_overdue\", \"action_required\", and + \"void\".""" + + @overload + def __init__( + self, + *, + trigger: Union[str, "_models.CustomInvoicingPaymentTrigger"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OmitPropertiesResourceCreateModel(_Model): + """The template for omitting properties. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar alignment: Alignment configuration for the plan. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar currency: Currency. Required. + :vartype currency: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar settlement_mode: Settlement mode. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar phases: Plan phases. Required. + :vartype phases: list[~openmeter._generated.models.PlanPhase] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Alignment configuration for the plan.""" + currency: str = rest_field(visibility=["read", "create"]) + """Currency. Required.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read", "create", "update"]) + """Billing cadence. Required.""" + pro_rating_config: Optional["_models.ProRatingConfig"] = rest_field( + name="proRatingConfig", visibility=["read", "create", "update"] + ) + """Pro-rating configuration.""" + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = rest_field( + name="settlementMode", visibility=["read", "create", "update"] + ) + """Settlement mode. Known values are: \"credit_then_invoice\" and \"credit_only\".""" + phases: list["_models.PlanPhase"] = rest_field(visibility=["read", "create", "update"]) + """Plan phases. Required.""" + + @overload + def __init__( + self, + *, + name: str, + currency: str, + billing_cadence: datetime.timedelta, + phases: list["_models.PlanPhase"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + alignment: Optional["_models.Alignment"] = None, + pro_rating_config: Optional["_models.ProRatingConfig"] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomPlanInput(OmitPropertiesResourceCreateModel): + """Plan input for custom subscription creation (without key and version). + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar alignment: Alignment configuration for the plan. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar currency: Currency. Required. + :vartype currency: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar settlement_mode: Settlement mode. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar phases: Plan phases. Required. + :vartype phases: list[~openmeter._generated.models.PlanPhase] + """ + + @overload + def __init__( + self, + *, + name: str, + currency: str, + billing_cadence: datetime.timedelta, + phases: list["_models.PlanPhase"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + alignment: Optional["_models.Alignment"] = None, + pro_rating_config: Optional["_models.ProRatingConfig"] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomSubscriptionChange(_Model): + """Change a custom subscription. + + :ivar timing: Timing configuration for the change, when the change should take effect. For + changing a subscription, the accepted values depend on the subscription configuration. + Required. Is either a Union[str, "_models.SubscriptionTimingEnum"] type or a datetime.datetime + type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar billing_anchor: The billing anchor of the subscription. The provided date will be + normalized according to the billing cadence to the nearest recurrence before start time. If not + provided, the previous subscription billing anchor will be used. + :vartype billing_anchor: ~datetime.datetime + :ivar custom_plan: The custom plan description which defines the Subscription. Required. + :vartype custom_plan: ~openmeter._generated.models.CustomPlanInput + """ + + timing: "_types.SubscriptionTiming" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Timing configuration for the change, when the change should take effect. For changing a + subscription, the accepted values depend on the subscription configuration. Required. Is either + a Union[str, \"_models.SubscriptionTimingEnum\"] type or a datetime.datetime type.""" + billing_anchor: Optional[datetime.datetime] = rest_field( + name="billingAnchor", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The billing anchor of the subscription. The provided date will be normalized according to the + billing cadence to the nearest recurrence before start time. If not provided, the previous + subscription billing anchor will be used.""" + custom_plan: "_models.CustomPlanInput" = rest_field( + name="customPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """The custom plan description which defines the Subscription. Required.""" + + @overload + def __init__( + self, + *, + timing: "_types.SubscriptionTiming", + custom_plan: "_models.CustomPlanInput", + billing_anchor: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CustomSubscriptionCreate(_Model): + """Create custom. + + :ivar custom_plan: The custom plan description which defines the Subscription. Required. + :vartype custom_plan: ~openmeter._generated.models.CustomPlanInput + :ivar timing: Timing configuration for the change, when the change should take effect. The + default is immediate. Is either a Union[str, "_models.SubscriptionTimingEnum"] type or a + datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar customer_id: The ID of the customer. Provide either the key or ID. Has presedence over + the key. + :vartype customer_id: str + :ivar customer_key: The key of the customer. Provide either the key or ID. + :vartype customer_key: str + :ivar billing_anchor: The billing anchor of the subscription. The provided date will be + normalized according to the billing cadence to the nearest recurrence before start time. If not + provided, the subscription start time will be used. + :vartype billing_anchor: ~datetime.datetime + """ + + custom_plan: "_models.CustomPlanInput" = rest_field( + name="customPlan", visibility=["read", "create", "update", "delete", "query"] + ) + """The custom plan description which defines the Subscription. Required.""" + timing: Optional["_types.SubscriptionTiming"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Timing configuration for the change, when the change should take effect. The default is + immediate. Is either a Union[str, \"_models.SubscriptionTimingEnum\"] type or a + datetime.datetime type.""" + customer_id: Optional[str] = rest_field( + name="customerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The ID of the customer. Provide either the key or ID. Has presedence over the key.""" + customer_key: Optional[str] = rest_field( + name="customerKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The key of the customer. Provide either the key or ID.""" + billing_anchor: Optional[datetime.datetime] = rest_field( + name="billingAnchor", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The billing anchor of the subscription. The provided date will be normalized according to the + billing cadence to the nearest recurrence before start time. If not provided, the subscription + start time will be used.""" + + @overload + def __init__( + self, + *, + custom_plan: "_models.CustomPlanInput", + timing: Optional["_types.SubscriptionTiming"] = None, + customer_id: Optional[str] = None, + customer_key: Optional[str] = None, + billing_anchor: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DiscountPercentage(_Model): + """Percentage discount. + + :ivar percentage: Percentage. Required. + :vartype percentage: float + """ + + percentage: float = rest_field(visibility=["read", "create", "update"]) + """Percentage. Required.""" + + @overload + def __init__( + self, + *, + percentage: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DiscountReasonMaximumSpend(_Model): + """The reason for the discount is a maximum spend. + + :ivar type: Required. MAXIMUM_SPEND. + :vartype type: str or ~openmeter._generated.models.MAXIMUM_SPEND + """ + + type: Literal[DiscountReasonType.MAXIMUM_SPEND] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required. MAXIMUM_SPEND.""" + + @overload + def __init__( + self, + *, + type: Literal[DiscountReasonType.MAXIMUM_SPEND], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DiscountReasonRatecardPercentage(_Model): + """The reason for the discount is a ratecard percentage. + + :ivar type: Required. RATECARD_PERCENTAGE. + :vartype type: str or ~openmeter._generated.models.RATECARD_PERCENTAGE + :ivar percentage: Percentage. Required. + :vartype percentage: float + :ivar correlation_id: Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + :vartype correlation_id: str + """ + + type: Literal[DiscountReasonType.RATECARD_PERCENTAGE] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required. RATECARD_PERCENTAGE.""" + percentage: float = rest_field(visibility=["read", "create", "update"]) + """Percentage. Required.""" + correlation_id: Optional[str] = rest_field( + name="correlationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect.""" + + @overload + def __init__( + self, + *, + type: Literal[DiscountReasonType.RATECARD_PERCENTAGE], + percentage: float, + correlation_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DiscountReasonRatecardUsage(_Model): + """The reason for the discount is a ratecard usage. + + :ivar type: Required. RATECARD_USAGE. + :vartype type: str or ~openmeter._generated.models.RATECARD_USAGE + :ivar quantity: Usage. Required. + :vartype quantity: str + :ivar correlation_id: Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + :vartype correlation_id: str + """ + + type: Literal[DiscountReasonType.RATECARD_USAGE] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required. RATECARD_USAGE.""" + quantity: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Usage. Required.""" + correlation_id: Optional[str] = rest_field( + name="correlationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect.""" + + @overload + def __init__( + self, + *, + type: Literal[DiscountReasonType.RATECARD_USAGE], + quantity: str, + correlation_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Discounts(_Model): + """Discount by type on a price. + + :ivar percentage: The percentage discount. + :vartype percentage: ~openmeter._generated.models.DiscountPercentage + :ivar usage: The usage discount. + :vartype usage: ~openmeter._generated.models.DiscountUsage + """ + + percentage: Optional["_models.DiscountPercentage"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The percentage discount.""" + usage: Optional["_models.DiscountUsage"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The usage discount.""" + + @overload + def __init__( + self, + *, + percentage: Optional["_models.DiscountPercentage"] = None, + usage: Optional["_models.DiscountUsage"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DiscountUsage(_Model): + """Usage discount. + + Usage discount means that the first N items are free. From billing perspective + this means that any usage on a specific feature is considered 0 until this discount + is exhausted. + + :ivar quantity: Usage. Required. + :vartype quantity: str + """ + + quantity: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Usage. Required.""" + + @overload + def __init__( + self, + *, + quantity: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DynamicPriceWithCommitments(_Model): + """Dynamic price with spend commitments. + + :ivar type: The type of the price. Required. DYNAMIC. + :vartype type: str or ~openmeter._generated.models.DYNAMIC + :ivar multiplier: The multiplier to apply to the base price to get the dynamic price. + :vartype multiplier: str + :ivar minimum_amount: Minimum amount. + :vartype minimum_amount: str + :ivar maximum_amount: Maximum amount. + :vartype maximum_amount: str + """ + + type: Literal[PriceType.DYNAMIC] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. Required. DYNAMIC.""" + multiplier: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """The multiplier to apply to the base price to get the dynamic price.""" + minimum_amount: Optional[str] = rest_field(name="minimumAmount", visibility=["read", "create", "update"]) + """Minimum amount.""" + maximum_amount: Optional[str] = rest_field(name="maximumAmount", visibility=["read", "create", "update"]) + """Maximum amount.""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.DYNAMIC], + multiplier: Optional[str] = None, + minimum_amount: Optional[str] = None, + maximum_amount: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EditSubscriptionAddItem(_Model): + """Add a new item to a phase. + + :ivar op: Required. ADD_ITEM. + :vartype op: str or ~openmeter._generated.models.ADD_ITEM + :ivar phase_key: Required. + :vartype phase_key: str + :ivar rate_card: Required. Is either a RateCardFlatFee type or a RateCardUsageBased type. + :vartype rate_card: ~openmeter._generated.models.RateCardFlatFee or + ~openmeter._generated.models.RateCardUsageBased + """ + + op: Literal[EditOp.ADD_ITEM] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. ADD_ITEM.""" + phase_key: str = rest_field(name="phaseKey", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + rate_card: "_types.RateCard" = rest_field( + name="rateCard", visibility=["read", "create", "update", "delete", "query"] + ) + """Required. Is either a RateCardFlatFee type or a RateCardUsageBased type.""" + + @overload + def __init__( + self, + *, + op: Literal[EditOp.ADD_ITEM], + phase_key: str, + rate_card: "_types.RateCard", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EditSubscriptionAddPhase(_Model): + """Add a new phase. + + :ivar op: Required. ADD_PHASE. + :vartype op: str or ~openmeter._generated.models.ADD_PHASE + :ivar phase: Required. + :vartype phase: ~openmeter._generated.models.SubscriptionPhaseCreate + """ + + op: Literal[EditOp.ADD_PHASE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. ADD_PHASE.""" + phase: "_models.SubscriptionPhaseCreate" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + op: Literal[EditOp.ADD_PHASE], + phase: "_models.SubscriptionPhaseCreate", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EditSubscriptionRemoveItem(_Model): + """Remove an item from a phase. + + :ivar op: Required. REMOVE_ITEM. + :vartype op: str or ~openmeter._generated.models.REMOVE_ITEM + :ivar phase_key: Required. + :vartype phase_key: str + :ivar item_key: Required. + :vartype item_key: str + """ + + op: Literal[EditOp.REMOVE_ITEM] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. REMOVE_ITEM.""" + phase_key: str = rest_field(name="phaseKey", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + item_key: str = rest_field(name="itemKey", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + op: Literal[EditOp.REMOVE_ITEM], + phase_key: str, + item_key: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EditSubscriptionRemovePhase(_Model): + """Remove a phase. + + :ivar op: Required. REMOVE_PHASE. + :vartype op: str or ~openmeter._generated.models.REMOVE_PHASE + :ivar phase_key: Required. + :vartype phase_key: str + :ivar shift: Required. Known values are: "next" and "prev". + :vartype shift: str or ~openmeter.models.RemovePhaseShifting + """ + + op: Literal[EditOp.REMOVE_PHASE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. REMOVE_PHASE.""" + phase_key: str = rest_field(name="phaseKey", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + shift: Union[str, "_models.RemovePhaseShifting"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Required. Known values are: \"next\" and \"prev\".""" + + @overload + def __init__( + self, + *, + op: Literal[EditOp.REMOVE_PHASE], + phase_key: str, + shift: Union[str, "_models.RemovePhaseShifting"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EditSubscriptionStretchPhase(_Model): + """Stretch a phase. + + :ivar op: Required. STRETCH_PHASE. + :vartype op: str or ~openmeter._generated.models.STRETCH_PHASE + :ivar phase_key: Required. + :vartype phase_key: str + :ivar extend_by: Required. + :vartype extend_by: ~datetime.timedelta + """ + + op: Literal[EditOp.STRETCH_PHASE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. STRETCH_PHASE.""" + phase_key: str = rest_field(name="phaseKey", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + extend_by: datetime.timedelta = rest_field( + name="extendBy", visibility=["read", "create", "update", "delete", "query"] + ) + """Required.""" + + @overload + def __init__( + self, + *, + op: Literal[EditOp.STRETCH_PHASE], + phase_key: str, + extend_by: datetime.timedelta, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EditSubscriptionUnscheduleEdit(_Model): + """Unschedules any edits from the current phase. + + :ivar op: Required. UNSCHEDULE_EDIT. + :vartype op: str or ~openmeter._generated.models.UNSCHEDULE_EDIT + """ + + op: Literal[EditOp.UNSCHEDULE_EDIT] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. UNSCHEDULE_EDIT.""" + + @overload + def __init__( + self, + *, + op: Literal[EditOp.UNSCHEDULE_EDIT], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementBoolean(_Model): + """Entitlement template of a boolean entitlement. + + :ivar type: Required. BOOLEAN. + :vartype type: str or ~openmeter._generated.models.BOOLEAN + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: The annotations of the entitlement. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar subject_key: The identifier key unique to the subject. NOTE: Subjects are being + deprecated, please use the new customer APIs. Required. + :vartype subject_key: str + :ivar feature_key: The feature the subject is entitled to use. Required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Required. + :vartype feature_id: str + :ivar current_usage_period: The current usage period. + :vartype current_usage_period: ~openmeter._generated.models.Period + :ivar usage_period: The defined usage period of the entitlement. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriod + """ + + type: Literal[EntitlementType.BOOLEAN] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. BOOLEAN.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """The annotations of the entitlement.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + subject_key: str = rest_field(name="subjectKey", visibility=["read", "create", "update", "delete", "query"]) + """The identifier key unique to the subject. NOTE: Subjects are being deprecated, please use the + new customer APIs. Required.""" + feature_key: str = rest_field(name="featureKey", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + feature_id: str = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + current_usage_period: Optional["_models.Period"] = rest_field( + name="currentUsagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The current usage period.""" + usage_period: Optional["_models.RecurringPeriod"] = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The defined usage period of the entitlement.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.BOOLEAN], + active_from: datetime.datetime, + subject_key: str, + feature_key: str, + feature_id: str, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + current_usage_period: Optional["_models.Period"] = None, + usage_period: Optional["_models.RecurringPeriod"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementBooleanCreateInputs(_Model): + """Create inputs for boolean entitlement. + + :ivar feature_key: The feature the subject is entitled to use. Either featureKey or featureId + is required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Either featureKey or featureId is + required. + :vartype feature_id: str + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar usage_period: The usage period associated with the entitlement. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriodCreateInput + :ivar type: Required. BOOLEAN. + :vartype type: str or ~openmeter._generated.models.BOOLEAN + """ + + feature_key: Optional[str] = rest_field( + name="featureKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + feature_id: Optional[str] = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + usage_period: Optional["_models.RecurringPeriodCreateInput"] = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The usage period associated with the entitlement.""" + type: Literal[EntitlementType.BOOLEAN] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. BOOLEAN.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.BOOLEAN], + feature_key: Optional[str] = None, + feature_id: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + usage_period: Optional["_models.RecurringPeriodCreateInput"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementBooleanV2(_Model): + """Entitlement template of a boolean entitlement. + + :ivar type: Required. BOOLEAN. + :vartype type: str or ~openmeter._generated.models.BOOLEAN + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: The annotations of the entitlement. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar feature_key: The feature the subject is entitled to use. Required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Required. + :vartype feature_id: str + :ivar current_usage_period: The current usage period. + :vartype current_usage_period: ~openmeter._generated.models.Period + :ivar usage_period: The defined usage period of the entitlement. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriod + :ivar customer_key: The identifier key unique to the customer. + :vartype customer_key: str + :ivar customer_id: The identifier unique to the customer. Required. + :vartype customer_id: str + """ + + type: Literal[EntitlementType.BOOLEAN] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. BOOLEAN.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """The annotations of the entitlement.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + feature_key: str = rest_field(name="featureKey", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + feature_id: str = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + current_usage_period: Optional["_models.Period"] = rest_field( + name="currentUsagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The current usage period.""" + usage_period: Optional["_models.RecurringPeriod"] = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The defined usage period of the entitlement.""" + customer_key: Optional[str] = rest_field( + name="customerKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The identifier key unique to the customer.""" + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The identifier unique to the customer. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.BOOLEAN], + active_from: datetime.datetime, + feature_key: str, + feature_id: str, + customer_id: str, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + current_usage_period: Optional["_models.Period"] = None, + usage_period: Optional["_models.RecurringPeriod"] = None, + customer_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementGrant(_Model): + """The grant. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar amount: The amount to grant. Should be a positive number. Required. + :vartype amount: float + :ivar priority: The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. For + example, a priority of 1 is more urgent than a priority of 2. When there are several grants + available for the same subject, the system selects the grant with the highest priority. In + cases where grants share the same priority level, the grant closest to its expiration will be + used first. In the case of two grants have identical priorities and expiration dates, the + system will use the grant that was created first. + :vartype priority: int + :ivar effective_at: Effective date for grants and anchor for recurring grants. Provided value + will be ceiled to metering windowSize (minute). Required. + :vartype effective_at: ~datetime.datetime + :ivar expiration: The grant expiration definition. Required. + :vartype expiration: ~openmeter._generated.models.ExpirationPeriod + :ivar max_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)). + :vartype max_rollover_amount: float + :ivar min_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)). + :vartype min_rollover_amount: float + :ivar metadata: The grant metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar entitlement_id: The unique entitlement ULID that the grant is associated with. Required. + :vartype entitlement_id: str + :ivar next_recurrence: The next time the grant will recurr. + :vartype next_recurrence: ~datetime.datetime + :ivar expires_at: The time the grant expires. + :vartype expires_at: ~datetime.datetime + :ivar voided_at: The time the grant was voided. + :vartype voided_at: ~datetime.datetime + :ivar recurrence: The recurrence period of the grant. + :vartype recurrence: ~openmeter._generated.models.RecurringPeriod + :ivar annotations: Grant annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + amount: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The amount to grant. Should be a positive number. Required.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The priority of the grant. Grants with higher priority are applied first. Priority is a + positive decimal numbers. With lower numbers indicating higher importance. For example, a + priority of 1 is more urgent than a priority of 2. When there are several grants available for + the same subject, the system selects the grant with the highest priority. In cases where grants + share the same priority level, the grant closest to its expiration will be used first. In the + case of two grants have identical priorities and expiration dates, the system will use the + grant that was created first.""" + effective_at: datetime.datetime = rest_field( + name="effectiveAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Effective date for grants and anchor for recurring grants. Provided value will be ceiled to + metering windowSize (minute). Required.""" + expiration: "_models.ExpirationPeriod" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grant expiration definition. Required.""" + max_rollover_amount: Optional[float] = rest_field( + name="maxRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. Balance after the reset is calculated as: Balance_After_Reset = + MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)).""" + min_rollover_amount: Optional[float] = rest_field( + name="minRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. Balance after the reset is calculated as: Balance_After_Reset = + MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)).""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grant metadata.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + entitlement_id: str = rest_field(name="entitlementId", visibility=["read"]) + """The unique entitlement ULID that the grant is associated with. Required.""" + next_recurrence: Optional[datetime.datetime] = rest_field( + name="nextRecurrence", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The next time the grant will recurr.""" + expires_at: Optional[datetime.datetime] = rest_field(name="expiresAt", visibility=["read"], format="rfc3339") + """The time the grant expires.""" + voided_at: Optional[datetime.datetime] = rest_field( + name="voidedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time the grant was voided.""" + recurrence: Optional["_models.RecurringPeriod"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The recurrence period of the grant.""" + annotations: Optional["_models.Annotations"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Grant annotations.""" + + @overload + def __init__( + self, + *, + amount: float, + effective_at: datetime.datetime, + expiration: "_models.ExpirationPeriod", + priority: Optional[int] = None, + max_rollover_amount: Optional[float] = None, + min_rollover_amount: Optional[float] = None, + metadata: Optional["_models.Metadata"] = None, + next_recurrence: Optional[datetime.datetime] = None, + voided_at: Optional[datetime.datetime] = None, + recurrence: Optional["_models.RecurringPeriod"] = None, + annotations: Optional["_models.Annotations"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementGrantCreateInput(_Model): + """The grant creation input. + + :ivar amount: The amount to grant. Should be a positive number. Required. + :vartype amount: float + :ivar priority: The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. For + example, a priority of 1 is more urgent than a priority of 2. When there are several grants + available for the same subject, the system selects the grant with the highest priority. In + cases where grants share the same priority level, the grant closest to its expiration will be + used first. In the case of two grants have identical priorities and expiration dates, the + system will use the grant that was created first. + :vartype priority: int + :ivar effective_at: Effective date for grants and anchor for recurring grants. Provided value + will be ceiled to metering windowSize (minute). Required. + :vartype effective_at: ~datetime.datetime + :ivar expiration: The grant expiration definition. Required. + :vartype expiration: ~openmeter._generated.models.ExpirationPeriod + :ivar max_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)). + :vartype max_rollover_amount: float + :ivar min_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)). + :vartype min_rollover_amount: float + :ivar metadata: The grant metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar recurrence: The subject of the grant. + :vartype recurrence: ~openmeter._generated.models.RecurringPeriodCreateInput + """ + + amount: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The amount to grant. Should be a positive number. Required.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The priority of the grant. Grants with higher priority are applied first. Priority is a + positive decimal numbers. With lower numbers indicating higher importance. For example, a + priority of 1 is more urgent than a priority of 2. When there are several grants available for + the same subject, the system selects the grant with the highest priority. In cases where grants + share the same priority level, the grant closest to its expiration will be used first. In the + case of two grants have identical priorities and expiration dates, the system will use the + grant that was created first.""" + effective_at: datetime.datetime = rest_field( + name="effectiveAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Effective date for grants and anchor for recurring grants. Provided value will be ceiled to + metering windowSize (minute). Required.""" + expiration: "_models.ExpirationPeriod" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grant expiration definition. Required.""" + max_rollover_amount: Optional[float] = rest_field( + name="maxRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. Balance after the reset is calculated as: Balance_After_Reset = + MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)).""" + min_rollover_amount: Optional[float] = rest_field( + name="minRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. Balance after the reset is calculated as: Balance_After_Reset = + MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)).""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grant metadata.""" + recurrence: Optional["_models.RecurringPeriodCreateInput"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The subject of the grant.""" + + @overload + def __init__( + self, + *, + amount: float, + effective_at: datetime.datetime, + expiration: "_models.ExpirationPeriod", + priority: Optional[int] = None, + max_rollover_amount: Optional[float] = None, + min_rollover_amount: Optional[float] = None, + metadata: Optional["_models.Metadata"] = None, + recurrence: Optional["_models.RecurringPeriodCreateInput"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementGrantCreateInputV2(_Model): + """The grant creation input. + + :ivar amount: The amount to grant. Should be a positive number. Required. + :vartype amount: float + :ivar priority: The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. For + example, a priority of 1 is more urgent than a priority of 2. When there are several grants + available for the same subject, the system selects the grant with the highest priority. In + cases where grants share the same priority level, the grant closest to its expiration will be + used first. In the case of two grants have identical priorities and expiration dates, the + system will use the grant that was created first. + :vartype priority: int + :ivar effective_at: Effective date for grants and anchor for recurring grants. Provided value + will be ceiled to metering windowSize (minute). Required. + :vartype effective_at: ~datetime.datetime + :ivar min_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)). + :vartype min_rollover_amount: float + :ivar metadata: The grant metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar recurrence: The subject of the grant. + :vartype recurrence: ~openmeter._generated.models.RecurringPeriodCreateInput + :ivar max_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. The default value equals grant + amount. Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, + MAX(Balance_Before_Reset, MinRolloverAmount)). + :vartype max_rollover_amount: float + :ivar expiration: The grant expiration definition. If no expiration is provided, the grant can + be active indefinitely. + :vartype expiration: ~openmeter._generated.models.ExpirationPeriod + :ivar annotations: Grant annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + """ + + amount: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The amount to grant. Should be a positive number. Required.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The priority of the grant. Grants with higher priority are applied first. Priority is a + positive decimal numbers. With lower numbers indicating higher importance. For example, a + priority of 1 is more urgent than a priority of 2. When there are several grants available for + the same subject, the system selects the grant with the highest priority. In cases where grants + share the same priority level, the grant closest to its expiration will be used first. In the + case of two grants have identical priorities and expiration dates, the system will use the + grant that was created first.""" + effective_at: datetime.datetime = rest_field( + name="effectiveAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Effective date for grants and anchor for recurring grants. Provided value will be ceiled to + metering windowSize (minute). Required.""" + min_rollover_amount: Optional[float] = rest_field( + name="minRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. Balance after the reset is calculated as: Balance_After_Reset = + MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)).""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grant metadata.""" + recurrence: Optional["_models.RecurringPeriodCreateInput"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The subject of the grant.""" + max_rollover_amount: Optional[float] = rest_field( + name="maxRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. The default value equals grant amount. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)).""" + expiration: Optional["_models.ExpirationPeriod"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The grant expiration definition. If no expiration is provided, the grant can be active + indefinitely.""" + annotations: Optional["_models.Annotations"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Grant annotations.""" + + @overload + def __init__( + self, + *, + amount: float, + effective_at: datetime.datetime, + priority: Optional[int] = None, + min_rollover_amount: Optional[float] = None, + metadata: Optional["_models.Metadata"] = None, + recurrence: Optional["_models.RecurringPeriodCreateInput"] = None, + max_rollover_amount: Optional[float] = None, + expiration: Optional["_models.ExpirationPeriod"] = None, + annotations: Optional["_models.Annotations"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementGrantV2(_Model): + """The grant. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar amount: The amount to grant. Should be a positive number. Required. + :vartype amount: float + :ivar priority: The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. For + example, a priority of 1 is more urgent than a priority of 2. When there are several grants + available for the same subject, the system selects the grant with the highest priority. In + cases where grants share the same priority level, the grant closest to its expiration will be + used first. In the case of two grants have identical priorities and expiration dates, the + system will use the grant that was created first. + :vartype priority: int + :ivar effective_at: Effective date for grants and anchor for recurring grants. Provided value + will be ceiled to metering windowSize (minute). Required. + :vartype effective_at: ~datetime.datetime + :ivar min_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)). + :vartype min_rollover_amount: float + :ivar metadata: The grant metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar max_rollover_amount: Grants are rolled over at reset, after which they can have a + different balance compared to what they had before the reset. The default value equals grant + amount. Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, + MAX(Balance_Before_Reset, MinRolloverAmount)). + :vartype max_rollover_amount: float + :ivar expiration: The grant expiration definition. If no expiration is provided, the grant can + be active indefinitely. + :vartype expiration: ~openmeter._generated.models.ExpirationPeriod + :ivar annotations: Grant annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar entitlement_id: The unique entitlement ULID that the grant is associated with. Required. + :vartype entitlement_id: str + :ivar next_recurrence: The next time the grant will recurr. + :vartype next_recurrence: ~datetime.datetime + :ivar expires_at: The time the grant expires. + :vartype expires_at: ~datetime.datetime + :ivar voided_at: The time the grant was voided. + :vartype voided_at: ~datetime.datetime + :ivar recurrence: The recurrence period of the grant. + :vartype recurrence: ~openmeter._generated.models.RecurringPeriod + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + amount: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The amount to grant. Should be a positive number. Required.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The priority of the grant. Grants with higher priority are applied first. Priority is a + positive decimal numbers. With lower numbers indicating higher importance. For example, a + priority of 1 is more urgent than a priority of 2. When there are several grants available for + the same subject, the system selects the grant with the highest priority. In cases where grants + share the same priority level, the grant closest to its expiration will be used first. In the + case of two grants have identical priorities and expiration dates, the system will use the + grant that was created first.""" + effective_at: datetime.datetime = rest_field( + name="effectiveAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Effective date for grants and anchor for recurring grants. Provided value will be ceiled to + metering windowSize (minute). Required.""" + min_rollover_amount: Optional[float] = rest_field( + name="minRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. Balance after the reset is calculated as: Balance_After_Reset = + MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)).""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grant metadata.""" + max_rollover_amount: Optional[float] = rest_field( + name="maxRolloverAmount", visibility=["read", "create", "update", "delete", "query"] + ) + """Grants are rolled over at reset, after which they can have a different balance compared to what + they had before the reset. The default value equals grant amount. Balance after the reset is + calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, + MinRolloverAmount)).""" + expiration: Optional["_models.ExpirationPeriod"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The grant expiration definition. If no expiration is provided, the grant can be active + indefinitely.""" + annotations: Optional["_models.Annotations"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Grant annotations.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + entitlement_id: str = rest_field(name="entitlementId", visibility=["read"]) + """The unique entitlement ULID that the grant is associated with. Required.""" + next_recurrence: Optional[datetime.datetime] = rest_field( + name="nextRecurrence", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The next time the grant will recurr.""" + expires_at: Optional[datetime.datetime] = rest_field(name="expiresAt", visibility=["read"], format="rfc3339") + """The time the grant expires.""" + voided_at: Optional[datetime.datetime] = rest_field( + name="voidedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time the grant was voided.""" + recurrence: Optional["_models.RecurringPeriod"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The recurrence period of the grant.""" + + @overload + def __init__( + self, + *, + amount: float, + effective_at: datetime.datetime, + priority: Optional[int] = None, + min_rollover_amount: Optional[float] = None, + metadata: Optional["_models.Metadata"] = None, + max_rollover_amount: Optional[float] = None, + expiration: Optional["_models.ExpirationPeriod"] = None, + annotations: Optional["_models.Annotations"] = None, + next_recurrence: Optional[datetime.datetime] = None, + voided_at: Optional[datetime.datetime] = None, + recurrence: Optional["_models.RecurringPeriod"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementMetered(_Model): + """Metered entitlements are useful for many different use cases, from setting up usage based + access to implementing complex credit systems. Access is determined based on feature usage + using a balance calculation (the "usage allowance" provided by the issued grants is "burnt + down" by the usage). + + :ivar type: Required. METERED. + :vartype type: str or ~openmeter._generated.models.METERED + :ivar is_soft_limit: Soft limit. + :vartype is_soft_limit: bool + :ivar is_unlimited: Deprecated, ignored by the backend. Please use isSoftLimit instead; this + field will be removed in the future. + :vartype is_unlimited: bool + :ivar issue_after_reset: Initial grant amount. + :vartype issue_after_reset: float + :ivar issue_after_reset_priority: Issue grant after reset priority. + :vartype issue_after_reset_priority: int + :ivar preserve_overage_at_reset: Preserve overage at reset. + :vartype preserve_overage_at_reset: bool + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: The annotations of the entitlement. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar subject_key: The identifier key unique to the subject. NOTE: Subjects are being + deprecated, please use the new customer APIs. Required. + :vartype subject_key: str + :ivar feature_key: The feature the subject is entitled to use. Required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Required. + :vartype feature_id: str + :ivar last_reset: The time the last reset happened. Required. + :vartype last_reset: ~datetime.datetime + :ivar current_usage_period: The current usage period. Required. + :vartype current_usage_period: ~openmeter._generated.models.Period + :ivar measure_usage_from: The time from which usage is measured. If not specified on creation, + defaults to entitlement creation time. Required. + :vartype measure_usage_from: ~datetime.datetime + :ivar usage_period: THe usage period of the entitlement. Required. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriod + """ + + type: Literal[EntitlementType.METERED] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. METERED.""" + is_soft_limit: Optional[bool] = rest_field( + name="isSoftLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Soft limit.""" + is_unlimited: Optional[bool] = rest_field( + name="isUnlimited", visibility=["read", "create", "update", "delete", "query"] + ) + """Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed + in the future.""" + issue_after_reset: Optional[float] = rest_field( + name="issueAfterReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Initial grant amount.""" + issue_after_reset_priority: Optional[int] = rest_field( + name="issueAfterResetPriority", visibility=["read", "create", "update", "delete", "query"] + ) + """Issue grant after reset priority.""" + preserve_overage_at_reset: Optional[bool] = rest_field( + name="preserveOverageAtReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Preserve overage at reset.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """The annotations of the entitlement.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + subject_key: str = rest_field(name="subjectKey", visibility=["read", "create", "update", "delete", "query"]) + """The identifier key unique to the subject. NOTE: Subjects are being deprecated, please use the + new customer APIs. Required.""" + feature_key: str = rest_field(name="featureKey", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + feature_id: str = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + last_reset: datetime.datetime = rest_field(name="lastReset", visibility=["read"], format="rfc3339") + """The time the last reset happened. Required.""" + current_usage_period: "_models.Period" = rest_field(name="currentUsagePeriod", visibility=["read"]) + """The current usage period. Required.""" + measure_usage_from: datetime.datetime = rest_field(name="measureUsageFrom", visibility=["read"], format="rfc3339") + """The time from which usage is measured. If not specified on creation, defaults to entitlement + creation time. Required.""" + usage_period: "_models.RecurringPeriod" = rest_field(name="usagePeriod", visibility=["read"]) + """THe usage period of the entitlement. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.METERED], + active_from: datetime.datetime, + subject_key: str, + feature_key: str, + feature_id: str, + is_soft_limit: Optional[bool] = None, + is_unlimited: Optional[bool] = None, + issue_after_reset: Optional[float] = None, + issue_after_reset_priority: Optional[int] = None, + preserve_overage_at_reset: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementMeteredCreateInputs(_Model): + """Create inpurs for metered entitlement. + + :ivar feature_key: The feature the subject is entitled to use. Either featureKey or featureId + is required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Either featureKey or featureId is + required. + :vartype feature_id: str + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: Required. METERED. + :vartype type: str or ~openmeter._generated.models.METERED + :ivar is_soft_limit: Soft limit. + :vartype is_soft_limit: bool + :ivar is_unlimited: Deprecated, ignored by the backend. Please use isSoftLimit instead; this + field will be removed in the future. + :vartype is_unlimited: bool + :ivar usage_period: The usage period associated with the entitlement. Required. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriodCreateInput + :ivar measure_usage_from: Defines the time from which usage is measured. If not specified on + creation, defaults to entitlement creation time. Is either a Union[str, + "_models.MeasureUsageFromPreset"] type or a datetime.datetime type. + :vartype measure_usage_from: str or ~openmeter.models.MeasureUsageFromPreset or + ~datetime.datetime + :ivar issue_after_reset: Initial grant amount. + :vartype issue_after_reset: float + :ivar issue_after_reset_priority: Issue grant after reset priority. + :vartype issue_after_reset_priority: int + :ivar preserve_overage_at_reset: Preserve overage at reset. + :vartype preserve_overage_at_reset: bool + """ + + feature_key: Optional[str] = rest_field( + name="featureKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + feature_id: Optional[str] = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + type: Literal[EntitlementType.METERED] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. METERED.""" + is_soft_limit: Optional[bool] = rest_field( + name="isSoftLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Soft limit.""" + is_unlimited: Optional[bool] = rest_field( + name="isUnlimited", visibility=["read", "create", "update", "delete", "query"] + ) + """Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed + in the future.""" + usage_period: "_models.RecurringPeriodCreateInput" = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The usage period associated with the entitlement. Required.""" + measure_usage_from: Optional["_types.MeasureUsageFrom"] = rest_field( + name="measureUsageFrom", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the time from which usage is measured. If not specified on creation, defaults to + entitlement creation time. Is either a Union[str, \"_models.MeasureUsageFromPreset\"] type or a + datetime.datetime type.""" + issue_after_reset: Optional[float] = rest_field( + name="issueAfterReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Initial grant amount.""" + issue_after_reset_priority: Optional[int] = rest_field( + name="issueAfterResetPriority", visibility=["read", "create", "update", "delete", "query"] + ) + """Issue grant after reset priority.""" + preserve_overage_at_reset: Optional[bool] = rest_field( + name="preserveOverageAtReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Preserve overage at reset.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.METERED], + usage_period: "_models.RecurringPeriodCreateInput", + feature_key: Optional[str] = None, + feature_id: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + is_soft_limit: Optional[bool] = None, + is_unlimited: Optional[bool] = None, + measure_usage_from: Optional["_types.MeasureUsageFrom"] = None, + issue_after_reset: Optional[float] = None, + issue_after_reset_priority: Optional[int] = None, + preserve_overage_at_reset: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementMeteredV2(_Model): + """Metered entitlements are useful for many different use cases, from setting up usage based + access to implementing complex credit systems. Access is determined based on feature usage + using a balance calculation (the "usage allowance" provided by the issued grants is "burnt + down" by the usage). + + :ivar type: Required. METERED. + :vartype type: str or ~openmeter._generated.models.METERED + :ivar is_soft_limit: Soft limit. + :vartype is_soft_limit: bool + :ivar preserve_overage_at_reset: Preserve overage at reset. + :vartype preserve_overage_at_reset: bool + :ivar issue_after_reset: Initial grant amount. + :vartype issue_after_reset: float + :ivar issue_after_reset_priority: Issue grant after reset priority. + :vartype issue_after_reset_priority: int + :ivar issue: Issue after reset. + :vartype issue: ~openmeter._generated.models.IssueAfterReset + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: The annotations of the entitlement. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar feature_key: The feature the subject is entitled to use. Required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Required. + :vartype feature_id: str + :ivar last_reset: The time the last reset happened. Required. + :vartype last_reset: ~datetime.datetime + :ivar current_usage_period: The current usage period. Required. + :vartype current_usage_period: ~openmeter._generated.models.Period + :ivar measure_usage_from: The time from which usage is measured. If not specified on creation, + defaults to entitlement creation time. Required. + :vartype measure_usage_from: ~datetime.datetime + :ivar usage_period: THe usage period of the entitlement. Required. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriod + :ivar customer_key: The identifier key unique to the customer. + :vartype customer_key: str + :ivar customer_id: The identifier unique to the customer. Required. + :vartype customer_id: str + """ + + type: Literal[EntitlementType.METERED] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. METERED.""" + is_soft_limit: Optional[bool] = rest_field( + name="isSoftLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Soft limit.""" + preserve_overage_at_reset: Optional[bool] = rest_field( + name="preserveOverageAtReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Preserve overage at reset.""" + issue_after_reset: Optional[float] = rest_field( + name="issueAfterReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Initial grant amount.""" + issue_after_reset_priority: Optional[int] = rest_field( + name="issueAfterResetPriority", visibility=["read", "create", "update", "delete", "query"] + ) + """Issue grant after reset priority.""" + issue: Optional["_models.IssueAfterReset"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Issue after reset.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """The annotations of the entitlement.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + feature_key: str = rest_field(name="featureKey", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + feature_id: str = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + last_reset: datetime.datetime = rest_field(name="lastReset", visibility=["read"], format="rfc3339") + """The time the last reset happened. Required.""" + current_usage_period: "_models.Period" = rest_field(name="currentUsagePeriod", visibility=["read"]) + """The current usage period. Required.""" + measure_usage_from: datetime.datetime = rest_field(name="measureUsageFrom", visibility=["read"], format="rfc3339") + """The time from which usage is measured. If not specified on creation, defaults to entitlement + creation time. Required.""" + usage_period: "_models.RecurringPeriod" = rest_field(name="usagePeriod", visibility=["read"]) + """THe usage period of the entitlement. Required.""" + customer_key: Optional[str] = rest_field( + name="customerKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The identifier key unique to the customer.""" + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The identifier unique to the customer. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.METERED], + active_from: datetime.datetime, + feature_key: str, + feature_id: str, + customer_id: str, + is_soft_limit: Optional[bool] = None, + preserve_overage_at_reset: Optional[bool] = None, + issue_after_reset: Optional[float] = None, + issue_after_reset_priority: Optional[int] = None, + issue: Optional["_models.IssueAfterReset"] = None, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + customer_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementMeteredV2CreateInputs(_Model): + """Create inputs for metered entitlement. + + :ivar feature_key: The feature the subject is entitled to use. Either featureKey or featureId + is required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Either featureKey or featureId is + required. + :vartype feature_id: str + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: Required. METERED. + :vartype type: str or ~openmeter._generated.models.METERED + :ivar is_soft_limit: Soft limit. + :vartype is_soft_limit: bool + :ivar usage_period: The usage period associated with the entitlement. Required. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriodCreateInput + :ivar measure_usage_from: Defines the time from which usage is measured. If not specified on + creation, defaults to entitlement creation time. Is either a Union[str, + "_models.MeasureUsageFromPreset"] type or a datetime.datetime type. + :vartype measure_usage_from: str or ~openmeter.models.MeasureUsageFromPreset or + ~datetime.datetime + :ivar preserve_overage_at_reset: Preserve overage at reset. + :vartype preserve_overage_at_reset: bool + :ivar issue_after_reset: Initial grant amount. + :vartype issue_after_reset: float + :ivar issue_after_reset_priority: Issue grant after reset priority. + :vartype issue_after_reset_priority: int + :ivar issue: Issue after reset. + :vartype issue: ~openmeter._generated.models.IssueAfterReset + :ivar grants: Grants. + :vartype grants: list[~openmeter._generated.models.EntitlementGrantCreateInputV2] + """ + + feature_key: Optional[str] = rest_field( + name="featureKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + feature_id: Optional[str] = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + type: Literal[EntitlementType.METERED] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. METERED.""" + is_soft_limit: Optional[bool] = rest_field( + name="isSoftLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Soft limit.""" + usage_period: "_models.RecurringPeriodCreateInput" = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The usage period associated with the entitlement. Required.""" + measure_usage_from: Optional["_types.MeasureUsageFrom"] = rest_field( + name="measureUsageFrom", visibility=["read", "create", "update", "delete", "query"] + ) + """Defines the time from which usage is measured. If not specified on creation, defaults to + entitlement creation time. Is either a Union[str, \"_models.MeasureUsageFromPreset\"] type or a + datetime.datetime type.""" + preserve_overage_at_reset: Optional[bool] = rest_field( + name="preserveOverageAtReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Preserve overage at reset.""" + issue_after_reset: Optional[float] = rest_field( + name="issueAfterReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Initial grant amount.""" + issue_after_reset_priority: Optional[int] = rest_field( + name="issueAfterResetPriority", visibility=["read", "create", "update", "delete", "query"] + ) + """Issue grant after reset priority.""" + issue: Optional["_models.IssueAfterReset"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Issue after reset.""" + grants: Optional[list["_models.EntitlementGrantCreateInputV2"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Grants.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.METERED], + usage_period: "_models.RecurringPeriodCreateInput", + feature_key: Optional[str] = None, + feature_id: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + is_soft_limit: Optional[bool] = None, + measure_usage_from: Optional["_types.MeasureUsageFrom"] = None, + preserve_overage_at_reset: Optional[bool] = None, + issue_after_reset: Optional[float] = None, + issue_after_reset_priority: Optional[int] = None, + issue: Optional["_models.IssueAfterReset"] = None, + grants: Optional[list["_models.EntitlementGrantCreateInputV2"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_types.Entitlement"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_types.Entitlement"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementStatic(_Model): + """A static entitlement. + + :ivar type: Required. STATIC. + :vartype type: str or ~openmeter._generated.models.STATIC + :ivar config: The JSON parsable config of the entitlement. This value is also returned when + checking entitlement access and it is useful for configuring fine-grained access settings to + the feature, implemented in your own system. Has to be an object. Required. + :vartype config: str + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: The annotations of the entitlement. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar subject_key: The identifier key unique to the subject. NOTE: Subjects are being + deprecated, please use the new customer APIs. Required. + :vartype subject_key: str + :ivar feature_key: The feature the subject is entitled to use. Required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Required. + :vartype feature_id: str + :ivar current_usage_period: The current usage period. + :vartype current_usage_period: ~openmeter._generated.models.Period + :ivar usage_period: The defined usage period of the entitlement. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriod + """ + + type: Literal[EntitlementType.STATIC] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. STATIC.""" + config: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The JSON parsable config of the entitlement. This value is also returned when checking + entitlement access and it is useful for configuring fine-grained access settings to the + feature, implemented in your own system. Has to be an object. Required.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """The annotations of the entitlement.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + subject_key: str = rest_field(name="subjectKey", visibility=["read", "create", "update", "delete", "query"]) + """The identifier key unique to the subject. NOTE: Subjects are being deprecated, please use the + new customer APIs. Required.""" + feature_key: str = rest_field(name="featureKey", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + feature_id: str = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + current_usage_period: Optional["_models.Period"] = rest_field( + name="currentUsagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The current usage period.""" + usage_period: Optional["_models.RecurringPeriod"] = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The defined usage period of the entitlement.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.STATIC], + config: str, + active_from: datetime.datetime, + subject_key: str, + feature_key: str, + feature_id: str, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + current_usage_period: Optional["_models.Period"] = None, + usage_period: Optional["_models.RecurringPeriod"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementStaticCreateInputs(_Model): + """Create inputs for static entitlement. + + :ivar feature_key: The feature the subject is entitled to use. Either featureKey or featureId + is required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Either featureKey or featureId is + required. + :vartype feature_id: str + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar usage_period: The usage period associated with the entitlement. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriodCreateInput + :ivar type: Required. STATIC. + :vartype type: str or ~openmeter._generated.models.STATIC + :ivar config: The JSON parsable config of the entitlement. This value is also returned when + checking entitlement access and it is useful for configuring fine-grained access settings to + the feature, implemented in your own system. Has to be an object. Required. + :vartype config: str + """ + + feature_key: Optional[str] = rest_field( + name="featureKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + feature_id: Optional[str] = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Either featureKey or featureId is required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + usage_period: Optional["_models.RecurringPeriodCreateInput"] = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The usage period associated with the entitlement.""" + type: Literal[EntitlementType.STATIC] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. STATIC.""" + config: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The JSON parsable config of the entitlement. This value is also returned when checking + entitlement access and it is useful for configuring fine-grained access settings to the + feature, implemented in your own system. Has to be an object. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.STATIC], + config: str, + feature_key: Optional[str] = None, + feature_id: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + usage_period: Optional["_models.RecurringPeriodCreateInput"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementStaticV2(_Model): + """A static entitlement. + + :ivar type: Required. STATIC. + :vartype type: str or ~openmeter._generated.models.STATIC + :ivar config: The JSON parsable config of the entitlement. This value is also returned when + checking entitlement access and it is useful for configuring fine-grained access settings to + the feature, implemented in your own system. Has to be an object. Required. + :vartype config: str + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: The annotations of the entitlement. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + :ivar feature_key: The feature the subject is entitled to use. Required. + :vartype feature_key: str + :ivar feature_id: The feature the subject is entitled to use. Required. + :vartype feature_id: str + :ivar current_usage_period: The current usage period. + :vartype current_usage_period: ~openmeter._generated.models.Period + :ivar usage_period: The defined usage period of the entitlement. + :vartype usage_period: ~openmeter._generated.models.RecurringPeriod + :ivar customer_key: The identifier key unique to the customer. + :vartype customer_key: str + :ivar customer_id: The identifier unique to the customer. Required. + :vartype customer_id: str + """ + + type: Literal[EntitlementType.STATIC] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. STATIC.""" + config: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The JSON parsable config of the entitlement. This value is also returned when checking + entitlement access and it is useful for configuring fine-grained access settings to the + feature, implemented in your own system. Has to be an object. Required.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """The annotations of the entitlement.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + feature_key: str = rest_field(name="featureKey", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + feature_id: str = rest_field(name="featureId", visibility=["read", "create", "update", "delete", "query"]) + """The feature the subject is entitled to use. Required.""" + current_usage_period: Optional["_models.Period"] = rest_field( + name="currentUsagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The current usage period.""" + usage_period: Optional["_models.RecurringPeriod"] = rest_field( + name="usagePeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The defined usage period of the entitlement.""" + customer_key: Optional[str] = rest_field( + name="customerKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The identifier key unique to the customer.""" + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The identifier unique to the customer. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.STATIC], + config: str, + active_from: datetime.datetime, + feature_key: str, + feature_id: str, + customer_id: str, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + current_usage_period: Optional["_models.Period"] = None, + usage_period: Optional["_models.RecurringPeriod"] = None, + customer_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementV2PaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_types.EntitlementV2"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_types.EntitlementV2"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntitlementValue(_Model): + """Entitlements are the core of OpenMeter access management. They define access to features for + subjects. Entitlements can be metered, boolean, or static. + + :ivar has_access: Whether the subject has access to the feature. Shared accross all entitlement + types. Required. + :vartype has_access: bool + :ivar balance: Only available for metered entitlements. Metered entitlements are built around a + balance calculation where feature usage is deducted from the issued grants. Balance represents + the remaining balance of the entitlement, it's value never turns negative. + :vartype balance: float + :ivar usage: Only available for metered entitlements. Returns the total feature usage in the + current period. + :vartype usage: float + :ivar overage: Only available for metered entitlements. Overage represents the usage that + wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period + but they were only granted 80, there would be 20 overage. + :vartype overage: float + :ivar total_available_grant_amount: Only available for metered entitlements. The summed amount + of all grant active at query time PLUS the used amount of since inactive grants. + :vartype total_available_grant_amount: float + :ivar config: Only available for static entitlements. The JSON parsable config of the + entitlement. + :vartype config: str + """ + + has_access: bool = rest_field(name="hasAccess", visibility=["read"]) + """Whether the subject has access to the feature. Shared accross all entitlement types. Required.""" + balance: Optional[float] = rest_field(visibility=["read"]) + """Only available for metered entitlements. Metered entitlements are built around a balance + calculation where feature usage is deducted from the issued grants. Balance represents the + remaining balance of the entitlement, it's value never turns negative.""" + usage: Optional[float] = rest_field(visibility=["read"]) + """Only available for metered entitlements. Returns the total feature usage in the current period.""" + overage: Optional[float] = rest_field(visibility=["read"]) + """Only available for metered entitlements. Overage represents the usage that wasn't covered by + grants, e.g. if the subject had a total feature usage of 100 in the period but they were only + granted 80, there would be 20 overage.""" + total_available_grant_amount: Optional[float] = rest_field(name="totalAvailableGrantAmount", visibility=["read"]) + """Only available for metered entitlements. The summed amount of all grant active at query time + PLUS the used amount of since inactive grants.""" + config: Optional[str] = rest_field(visibility=["read"]) + """Only available for static entitlements. The JSON parsable config of the entitlement.""" + + +class EntitlementValueV2(_Model): + """EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 + APIs. + + :ivar has_access: Whether the subject has access to the feature. Shared accross all entitlement + types. Required. + :vartype has_access: bool + :ivar balance: Only available for metered entitlements. Metered entitlements are built around a + balance calculation where feature usage is deducted from the issued grants. Balance represents + the remaining balance of the entitlement, it's value never turns negative. + :vartype balance: float + :ivar usage: Only available for metered entitlements. Returns the total feature usage in the + current period. + :vartype usage: float + :ivar overage: Only available for metered entitlements. Overage represents the usage that + wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period + but they were only granted 80, there would be 20 overage. + :vartype overage: float + :ivar total_available_grant_amount: Only available for metered entitlements. The summed amount + of all grant active at query time PLUS the used amount of since inactive grants. + :vartype total_available_grant_amount: float + :ivar config: Only available for static entitlements. The JSON parsable config of the + entitlement. + :vartype config: str + :ivar grant_balances: Only available for metered entitlements. The closing balance of each + active grant at query time. The key is the grant ID and the value is the remaining balance. + :vartype grant_balances: dict[str, float] + """ + + has_access: bool = rest_field(name="hasAccess", visibility=["read"]) + """Whether the subject has access to the feature. Shared accross all entitlement types. Required.""" + balance: Optional[float] = rest_field(visibility=["read"]) + """Only available for metered entitlements. Metered entitlements are built around a balance + calculation where feature usage is deducted from the issued grants. Balance represents the + remaining balance of the entitlement, it's value never turns negative.""" + usage: Optional[float] = rest_field(visibility=["read"]) + """Only available for metered entitlements. Returns the total feature usage in the current period.""" + overage: Optional[float] = rest_field(visibility=["read"]) + """Only available for metered entitlements. Overage represents the usage that wasn't covered by + grants, e.g. if the subject had a total feature usage of 100 in the period but they were only + granted 80, there would be 20 overage.""" + total_available_grant_amount: Optional[float] = rest_field(name="totalAvailableGrantAmount", visibility=["read"]) + """Only available for metered entitlements. The summed amount of all grant active at query time + PLUS the used amount of since inactive grants.""" + config: Optional[str] = rest_field(visibility=["read"]) + """Only available for static entitlements. The JSON parsable config of the entitlement.""" + grant_balances: Optional[dict[str, float]] = rest_field(name="grantBalances", visibility=["read"]) + """Only available for metered entitlements. The closing balance of each active grant at query + time. The key is the grant ID and the value is the remaining balance.""" + + +class ErrorExtension(_Model): + """Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode]. + + :ivar field: The path to the field. Required. + :vartype field: str + :ivar code: The machine readable description of the error. Required. + :vartype code: str + :ivar message: The human readable description of the error. Required. + :vartype message: str + """ + + field: str = rest_field(visibility=["read"]) + """The path to the field. Required.""" + code: str = rest_field(visibility=["read"]) + """The machine readable description of the error. Required.""" + message: str = rest_field(visibility=["read"]) + """The human readable description of the error. Required.""" + + +class Event(_Model): + """CloudEvents Specification JSON Schema + + Optional properties are nullable according to the CloudEvents specification: + OPTIONAL not omitted attributes MAY be represented as a null JSON value. + + :ivar id: Identifies the event. Required. + :vartype id: str + :ivar source: Identifies the context in which an event happened. Required. + :vartype source: str + :ivar specversion: The version of the CloudEvents specification which the event uses. Required. + :vartype specversion: str + :ivar type: Contains a value describing the type of event related to the originating + occurrence. Required. + :vartype type: str + :ivar datacontenttype: Content type of the CloudEvents data value. Only the value + "application/json" is allowed over HTTP. Default value is "application/json". + :vartype datacontenttype: str + :ivar dataschema: Identifies the schema that data adheres to. + :vartype dataschema: str + :ivar subject: Describes the subject of the event in the context of the event producer + (identified by source). Required. + :vartype subject: str + :ivar time: Timestamp of when the occurrence happened. Must adhere to RFC 3339. + :vartype time: ~datetime.datetime + :ivar data: The event payload. Optional, if present it must be a JSON object. + :vartype data: dict[str, any] + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifies the event. Required.""" + source: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifies the context in which an event happened. Required.""" + specversion: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The version of the CloudEvents specification which the event uses. Required.""" + type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Contains a value describing the type of event related to the originating occurrence. Required.""" + datacontenttype: Optional[Literal["application/json"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Content type of the CloudEvents data value. Only the value \"application/json\" is allowed over + HTTP. Default value is \"application/json\".""" + dataschema: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifies the schema that data adheres to.""" + subject: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Describes the subject of the event in the context of the event producer (identified by source). + Required.""" + time: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Timestamp of when the occurrence happened. Must adhere to RFC 3339.""" + data: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The event payload. Optional, if present it must be a JSON object.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + source: str, + specversion: str, + type: str, + subject: str, + datacontenttype: Optional[Literal["application/json"]] = None, + dataschema: Optional[str] = None, + time: Optional[datetime.datetime] = None, + data: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EventDeliveryAttemptResponse(_Model): + """The response of the event delivery attempt. + + :ivar status_code: Status Code. + :vartype status_code: int + :ivar body: Response Body. Required. + :vartype body: str + :ivar duration_ms: Response Duration. Required. + :vartype duration_ms: int + :ivar url: URL. + :vartype url: str + """ + + status_code: Optional[int] = rest_field(name="statusCode", visibility=["read"]) + """Status Code.""" + body: str = rest_field(visibility=["read"]) + """Response Body. Required.""" + duration_ms: int = rest_field(name="durationMs", visibility=["read"]) + """Response Duration. Required.""" + url: Optional[str] = rest_field(visibility=["read"]) + """URL.""" + + +class ExpirationPeriod(_Model): + """The grant expiration definition. + + :ivar duration: The unit of time for the expiration period. Required. Known values are: "HOUR", + "DAY", "WEEK", "MONTH", and "YEAR". + :vartype duration: str or ~openmeter.models.ExpirationDuration + :ivar count: The number of time units in the expiration period. Required. + :vartype count: int + """ + + duration: Union[str, "_models.ExpirationDuration"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The unit of time for the expiration period. Required. Known values are: \"HOUR\", \"DAY\", + \"WEEK\", \"MONTH\", and \"YEAR\".""" + count: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of time units in the expiration period. Required.""" + + @overload + def __init__( + self, + *, + duration: Union[str, "_models.ExpirationDuration"], + count: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Feature(_Model): + """Represents a feature that can be enabled or disabled for a plan. Used both for product catalog + and entitlements. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar archived_at: Archival Time. + :vartype archived_at: ~datetime.datetime + :ivar key: The unique key of the feature. Required. + :vartype key: str + :ivar name: The human-readable name of the feature. Required. + :vartype name: str + :ivar metadata: Optional metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar meter_slug: Meter slug. + :vartype meter_slug: str + :ivar meter_group_by_filters: Meter group by filters. + :vartype meter_group_by_filters: dict[str, str] + :ivar advanced_meter_group_by_filters: Advanced meter group by filters. + :vartype advanced_meter_group_by_filters: dict[str, ~openmeter._generated.models.FilterString] + :ivar unit_cost: Unit cost. Is either a FeatureManualUnitCost type or a FeatureLLMUnitCost + type. + :vartype unit_cost: ~openmeter._generated.models.FeatureManualUnitCost or + ~openmeter._generated.models.FeatureLLMUnitCost + :ivar id: Readonly unique ULID identifier. Required. + :vartype id: str + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + archived_at: Optional[datetime.datetime] = rest_field(name="archivedAt", visibility=["read"], format="rfc3339") + """Archival Time.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique key of the feature. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The human-readable name of the feature. Required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional metadata.""" + meter_slug: Optional[str] = rest_field(name="meterSlug", visibility=["read", "create", "update", "delete", "query"]) + """Meter slug.""" + meter_group_by_filters: Optional[dict[str, str]] = rest_field( + name="meterGroupByFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """Meter group by filters.""" + advanced_meter_group_by_filters: Optional[dict[str, "_models.FilterString"]] = rest_field( + name="advancedMeterGroupByFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """Advanced meter group by filters.""" + unit_cost: Optional["_types.FeatureUnitCost"] = rest_field( + name="unitCost", visibility=["read", "create", "update", "delete", "query"] + ) + """Unit cost. Is either a FeatureManualUnitCost type or a FeatureLLMUnitCost type.""" + id: str = rest_field(visibility=["read"]) + """Readonly unique ULID identifier. Required.""" + + @overload + def __init__( + self, + *, + key: str, + name: str, + metadata: Optional["_models.Metadata"] = None, + meter_slug: Optional[str] = None, + meter_group_by_filters: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, "_models.FilterString"]] = None, + unit_cost: Optional["_types.FeatureUnitCost"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FeatureCreateInputs(_Model): + """Represents a feature that can be enabled or disabled for a plan. Used both for product catalog + and entitlements. + + :ivar key: The unique key of the feature. Required. + :vartype key: str + :ivar name: The human-readable name of the feature. Required. + :vartype name: str + :ivar metadata: Optional metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar meter_slug: Meter slug. + :vartype meter_slug: str + :ivar meter_group_by_filters: Meter group by filters. + :vartype meter_group_by_filters: dict[str, str] + :ivar advanced_meter_group_by_filters: Advanced meter group by filters. + :vartype advanced_meter_group_by_filters: dict[str, ~openmeter._generated.models.FilterString] + :ivar unit_cost: Unit cost. Is either a FeatureManualUnitCost type or a FeatureLLMUnitCost + type. + :vartype unit_cost: ~openmeter._generated.models.FeatureManualUnitCost or + ~openmeter._generated.models.FeatureLLMUnitCost + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique key of the feature. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The human-readable name of the feature. Required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional metadata.""" + meter_slug: Optional[str] = rest_field(name="meterSlug", visibility=["read", "create", "update", "delete", "query"]) + """Meter slug.""" + meter_group_by_filters: Optional[dict[str, str]] = rest_field( + name="meterGroupByFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """Meter group by filters.""" + advanced_meter_group_by_filters: Optional[dict[str, "_models.FilterString"]] = rest_field( + name="advancedMeterGroupByFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """Advanced meter group by filters.""" + unit_cost: Optional["_types.FeatureUnitCost"] = rest_field( + name="unitCost", visibility=["read", "create", "update", "delete", "query"] + ) + """Unit cost. Is either a FeatureManualUnitCost type or a FeatureLLMUnitCost type.""" + + @overload + def __init__( + self, + *, + key: str, + name: str, + metadata: Optional["_models.Metadata"] = None, + meter_slug: Optional[str] = None, + meter_group_by_filters: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, "_models.FilterString"]] = None, + unit_cost: Optional["_types.FeatureUnitCost"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FeatureLLMUnitCost(_Model): + """LLM cost lookup configuration. Maps meter group-by dimensions to LLM cost database fields. + + :ivar type: Required. LLM. + :vartype type: str or ~openmeter._generated.models.LLM + :ivar provider_property: Provider property. + :vartype provider_property: str + :ivar provider: Provider. + :vartype provider: str + :ivar model_property: Model property. + :vartype model_property: str + :ivar model: Model. + :vartype model: str + :ivar token_type_property: Token type property. + :vartype token_type_property: str + :ivar token_type: Token type. + :vartype token_type: str + :ivar pricing: Resolved pricing. + :vartype pricing: ~openmeter._generated.models.FeatureLLMUnitCostPricing + """ + + type: Literal[FeatureUnitCostType.LLM] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. LLM.""" + provider_property: Optional[str] = rest_field( + name="providerProperty", visibility=["read", "create", "update", "delete", "query"] + ) + """Provider property.""" + provider: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Provider.""" + model_property: Optional[str] = rest_field( + name="modelProperty", visibility=["read", "create", "update", "delete", "query"] + ) + """Model property.""" + model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Model.""" + token_type_property: Optional[str] = rest_field( + name="tokenTypeProperty", visibility=["read", "create", "update", "delete", "query"] + ) + """Token type property.""" + token_type: Optional[str] = rest_field(name="tokenType", visibility=["read", "create", "update", "delete", "query"]) + """Token type.""" + pricing: Optional["_models.FeatureLLMUnitCostPricing"] = rest_field(visibility=["read"]) + """Resolved pricing.""" + + @overload + def __init__( + self, + *, + type: Literal[FeatureUnitCostType.LLM], + provider_property: Optional[str] = None, + provider: Optional[str] = None, + model_property: Optional[str] = None, + model: Optional[str] = None, + token_type_property: Optional[str] = None, + token_type: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FeatureLLMUnitCostPricing(_Model): + """Resolved per-token pricing from the LLM cost database. + + :ivar input_per_token: Input per token. Required. + :vartype input_per_token: str + :ivar output_per_token: Output per token. Required. + :vartype output_per_token: str + :ivar cache_read_per_token: Cache read per token. + :vartype cache_read_per_token: str + :ivar reasoning_per_token: Reasoning per token. + :vartype reasoning_per_token: str + :ivar cache_write_per_token: Cache write per token. + :vartype cache_write_per_token: str + """ + + input_per_token: str = rest_field(name="inputPerToken", visibility=["read", "create", "update", "delete", "query"]) + """Input per token. Required.""" + output_per_token: str = rest_field( + name="outputPerToken", visibility=["read", "create", "update", "delete", "query"] + ) + """Output per token. Required.""" + cache_read_per_token: Optional[str] = rest_field( + name="cacheReadPerToken", visibility=["read", "create", "update", "delete", "query"] + ) + """Cache read per token.""" + reasoning_per_token: Optional[str] = rest_field( + name="reasoningPerToken", visibility=["read", "create", "update", "delete", "query"] + ) + """Reasoning per token.""" + cache_write_per_token: Optional[str] = rest_field( + name="cacheWritePerToken", visibility=["read", "create", "update", "delete", "query"] + ) + """Cache write per token.""" + + @overload + def __init__( + self, + *, + input_per_token: str, + output_per_token: str, + cache_read_per_token: Optional[str] = None, + reasoning_per_token: Optional[str] = None, + cache_write_per_token: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FeatureManualUnitCost(_Model): + """A fixed per-unit cost amount. + + :ivar type: Required. MANUAL. + :vartype type: str or ~openmeter._generated.models.MANUAL + :ivar amount: Fixed per-unit cost amount in USD. Required. + :vartype amount: str + """ + + type: Literal[FeatureUnitCostType.MANUAL] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. MANUAL.""" + amount: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Fixed per-unit cost amount in USD. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[FeatureUnitCostType.MANUAL], + amount: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FeatureMeta(_Model): + """Limited representation of a feature resource which includes only its unique identifiers (id, + key). + + :ivar id: Feature Unique Identifier. Required. + :vartype id: str + :ivar key: Feature Key. Required. + :vartype key: str + """ + + id: str = rest_field(visibility=["read", "create", "update"]) + """Feature Unique Identifier. Required.""" + key: str = rest_field(visibility=["read", "create", "update"]) + """Feature Key. Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + key: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FeaturePaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.Feature] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.Feature"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.Feature"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FilterIDExact(_Model): + """A filter for a ID (ULID) field allowing only equality or inclusion. + + :ivar in_property: The field must be in the provided list of values. + :vartype in_property: list[str] + """ + + in_property: Optional[list[str]] = rest_field( + name="$in", visibility=["read", "create", "update", "delete", "query"] + ) + """The field must be in the provided list of values.""" + + @overload + def __init__( + self, + *, + in_property: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FilterString(_Model): + """A filter for a string field. + + :ivar eq: The field must be equal to the provided value. + :vartype eq: str + :ivar ne: The field must not be equal to the provided value. + :vartype ne: str + :ivar in_property: The field must be in the provided list of values. + :vartype in_property: list[str] + :ivar nin: The field must not be in the provided list of values. + :vartype nin: list[str] + :ivar like: The field must match the provided value. + :vartype like: str + :ivar nlike: The field must not match the provided value. + :vartype nlike: str + :ivar ilike: The field must match the provided value, ignoring case. + :vartype ilike: str + :ivar nilike: The field must not match the provided value, ignoring case. + :vartype nilike: str + :ivar gt: The field must be greater than the provided value. + :vartype gt: str + :ivar gte: The field must be greater than or equal to the provided value. + :vartype gte: str + :ivar lt: The field must be less than the provided value. + :vartype lt: str + :ivar lte: The field must be less than or equal to the provided value. + :vartype lte: str + :ivar and_property: Provide a list of filters to be combined with a logical AND. + :vartype and_property: list[~openmeter._generated.models.FilterString] + :ivar or_property: Provide a list of filters to be combined with a logical OR. + :vartype or_property: list[~openmeter._generated.models.FilterString] + """ + + eq: Optional[str] = rest_field(name="$eq", visibility=["read", "create", "update", "delete", "query"]) + """The field must be equal to the provided value.""" + ne: Optional[str] = rest_field(name="$ne", visibility=["read", "create", "update", "delete", "query"]) + """The field must not be equal to the provided value.""" + in_property: Optional[list[str]] = rest_field( + name="$in", visibility=["read", "create", "update", "delete", "query"] + ) + """The field must be in the provided list of values.""" + nin: Optional[list[str]] = rest_field(name="$nin", visibility=["read", "create", "update", "delete", "query"]) + """The field must not be in the provided list of values.""" + like: Optional[str] = rest_field(name="$like", visibility=["read", "create", "update", "delete", "query"]) + """The field must match the provided value.""" + nlike: Optional[str] = rest_field(name="$nlike", visibility=["read", "create", "update", "delete", "query"]) + """The field must not match the provided value.""" + ilike: Optional[str] = rest_field(name="$ilike", visibility=["read", "create", "update", "delete", "query"]) + """The field must match the provided value, ignoring case.""" + nilike: Optional[str] = rest_field(name="$nilike", visibility=["read", "create", "update", "delete", "query"]) + """The field must not match the provided value, ignoring case.""" + gt: Optional[str] = rest_field(name="$gt", visibility=["read", "create", "update", "delete", "query"]) + """The field must be greater than the provided value.""" + gte: Optional[str] = rest_field(name="$gte", visibility=["read", "create", "update", "delete", "query"]) + """The field must be greater than or equal to the provided value.""" + lt: Optional[str] = rest_field(name="$lt", visibility=["read", "create", "update", "delete", "query"]) + """The field must be less than the provided value.""" + lte: Optional[str] = rest_field(name="$lte", visibility=["read", "create", "update", "delete", "query"]) + """The field must be less than or equal to the provided value.""" + and_property: Optional[list["_models.FilterString"]] = rest_field( + name="$and", visibility=["read", "create", "update", "delete", "query"] + ) + """Provide a list of filters to be combined with a logical AND.""" + or_property: Optional[list["_models.FilterString"]] = rest_field( + name="$or", visibility=["read", "create", "update", "delete", "query"] + ) + """Provide a list of filters to be combined with a logical OR.""" + + @overload + def __init__( + self, + *, + eq: Optional[str] = None, + ne: Optional[str] = None, + in_property: Optional[list[str]] = None, + nin: Optional[list[str]] = None, + like: Optional[str] = None, + nlike: Optional[str] = None, + ilike: Optional[str] = None, + nilike: Optional[str] = None, + gt: Optional[str] = None, + gte: Optional[str] = None, + lt: Optional[str] = None, + lte: Optional[str] = None, + and_property: Optional[list["_models.FilterString"]] = None, + or_property: Optional[list["_models.FilterString"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FilterTime(_Model): + """A filter for a time field. + + :ivar gt: The field must be greater than the provided value. + :vartype gt: ~datetime.datetime + :ivar gte: The field must be greater than or equal to the provided value. + :vartype gte: ~datetime.datetime + :ivar lt: The field must be less than the provided value. + :vartype lt: ~datetime.datetime + :ivar lte: The field must be less than or equal to the provided value. + :vartype lte: ~datetime.datetime + :ivar and_property: Provide a list of filters to be combined with a logical AND. + :vartype and_property: list[~openmeter._generated.models.FilterTime] + :ivar or_property: Provide a list of filters to be combined with a logical OR. + :vartype or_property: list[~openmeter._generated.models.FilterTime] + """ + + gt: Optional[datetime.datetime] = rest_field( + name="$gt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The field must be greater than the provided value.""" + gte: Optional[datetime.datetime] = rest_field( + name="$gte", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The field must be greater than or equal to the provided value.""" + lt: Optional[datetime.datetime] = rest_field( + name="$lt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The field must be less than the provided value.""" + lte: Optional[datetime.datetime] = rest_field( + name="$lte", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The field must be less than or equal to the provided value.""" + and_property: Optional[list["_models.FilterTime"]] = rest_field( + name="$and", visibility=["read", "create", "update", "delete", "query"] + ) + """Provide a list of filters to be combined with a logical AND.""" + or_property: Optional[list["_models.FilterTime"]] = rest_field( + name="$or", visibility=["read", "create", "update", "delete", "query"] + ) + """Provide a list of filters to be combined with a logical OR.""" + + @overload + def __init__( + self, + *, + gt: Optional[datetime.datetime] = None, + gte: Optional[datetime.datetime] = None, + lt: Optional[datetime.datetime] = None, + lte: Optional[datetime.datetime] = None, + and_property: Optional[list["_models.FilterTime"]] = None, + or_property: Optional[list["_models.FilterTime"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FlatPrice(_Model): + """Flat price. + + :ivar type: The type of the price. Required. FLAT. + :vartype type: str or ~openmeter._generated.models.FLAT + :ivar amount: The amount of the flat price. Required. + :vartype amount: str + """ + + type: Literal[PriceType.FLAT] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. Required. FLAT.""" + amount: str = rest_field(visibility=["read", "create", "update"]) + """The amount of the flat price. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.FLAT], + amount: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FlatPriceWithPaymentTerm(_Model): + """Flat price with payment term. + + :ivar type: The type of the price. Required. FLAT. + :vartype type: str or ~openmeter._generated.models.FLAT + :ivar amount: The amount of the flat price. Required. + :vartype amount: str + :ivar payment_term: The payment term of the flat price. Defaults to in advance. Known values + are: "in_advance" and "in_arrears". + :vartype payment_term: str or ~openmeter.models.PricePaymentTerm + """ + + type: Literal[PriceType.FLAT] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. Required. FLAT.""" + amount: str = rest_field(visibility=["read", "create", "update"]) + """The amount of the flat price. Required.""" + payment_term: Optional[Union[str, "_models.PricePaymentTerm"]] = rest_field( + name="paymentTerm", visibility=["read", "create", "update"] + ) + """The payment term of the flat price. Defaults to in advance. Known values are: \"in_advance\" + and \"in_arrears\".""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.FLAT], + amount: str, + payment_term: Optional[Union[str, "_models.PricePaymentTerm"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ForbiddenProblemResponse(UnexpectedProblemResponse): + """The server understood the request but refuses to authorize it. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GrantBurnDownHistorySegment(_Model): + """A segment of the grant burn down history. + + A given segment represents the usage of a grant between events that changed either the grant + burn down priority order or the usag period. + + :ivar period: The period of the segment. Required. + :vartype period: ~openmeter._generated.models.Period + :ivar usage: The total usage of the grant in the period. Required. + :vartype usage: float + :ivar overage: Overuse that wasn't covered by grants. Required. + :vartype overage: float + :ivar balance_at_start: entitlement balance at the start of the period. Required. + :vartype balance_at_start: float + :ivar grant_balances_at_start: The balance breakdown of each active grant at the start of the + period: GrantID: Balance. Required. + :vartype grant_balances_at_start: dict[str, float] + :ivar balance_at_end: The entitlement balance at the end of the period. Required. + :vartype balance_at_end: float + :ivar grant_balances_at_end: The balance breakdown of each active grant at the end of the + period: GrantID: Balance. Required. + :vartype grant_balances_at_end: dict[str, float] + :ivar grant_usages: Which grants were actually burnt down in the period and by what amount. + Required. + :vartype grant_usages: list[~openmeter._generated.models.GrantUsageRecord] + """ + + period: "_models.Period" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The period of the segment. Required.""" + usage: float = rest_field(visibility=["read"]) + """The total usage of the grant in the period. Required.""" + overage: float = rest_field(visibility=["read"]) + """Overuse that wasn't covered by grants. Required.""" + balance_at_start: float = rest_field(name="balanceAtStart", visibility=["read"]) + """entitlement balance at the start of the period. Required.""" + grant_balances_at_start: dict[str, float] = rest_field(name="grantBalancesAtStart", visibility=["read"]) + """The balance breakdown of each active grant at the start of the period: GrantID: Balance. + Required.""" + balance_at_end: float = rest_field(name="balanceAtEnd", visibility=["read"]) + """The entitlement balance at the end of the period. Required.""" + grant_balances_at_end: dict[str, float] = rest_field(name="grantBalancesAtEnd", visibility=["read"]) + """The balance breakdown of each active grant at the end of the period: GrantID: Balance. + Required.""" + grant_usages: list["_models.GrantUsageRecord"] = rest_field(name="grantUsages", visibility=["read"]) + """Which grants were actually burnt down in the period and by what amount. Required.""" + + @overload + def __init__( + self, + *, + period: "_models.Period", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GrantPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.EntitlementGrant] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.EntitlementGrant"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.EntitlementGrant"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GrantUsageRecord(_Model): + """Usage Record. + + :ivar grant_id: The id of the grant. Required. + :vartype grant_id: str + :ivar usage: The usage in the period. Required. + :vartype usage: float + """ + + grant_id: str = rest_field(name="grantId", visibility=["read", "create", "update", "delete", "query"]) + """The id of the grant. Required.""" + usage: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The usage in the period. Required.""" + + @overload + def __init__( + self, + *, + grant_id: str, + usage: float, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GrantV2PaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.EntitlementGrantV2] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.EntitlementGrantV2"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.EntitlementGrantV2"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IDResource(_Model): + """IDResource is a resouce with an ID. + + :ivar id: ID. Required. + :vartype id: str + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + + +class IngestedEvent(_Model): + """An ingested event with optional validation error. + + :ivar event: The original event ingested. Required. + :vartype event: ~openmeter._generated.models.Event + :ivar customer_id: The customer ID if the event is associated with a customer. + :vartype customer_id: str + :ivar validation_error: The validation error if the event failed validation. + :vartype validation_error: str + :ivar ingested_at: The date and time the event was ingested. Required. + :vartype ingested_at: ~datetime.datetime + :ivar stored_at: The date and time the event was stored. Required. + :vartype stored_at: ~datetime.datetime + """ + + event: "_models.Event" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The original event ingested. Required.""" + customer_id: Optional[str] = rest_field( + name="customerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The customer ID if the event is associated with a customer.""" + validation_error: Optional[str] = rest_field( + name="validationError", visibility=["read", "create", "update", "delete", "query"] + ) + """The validation error if the event failed validation.""" + ingested_at: datetime.datetime = rest_field( + name="ingestedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The date and time the event was ingested. Required.""" + stored_at: datetime.datetime = rest_field( + name="storedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The date and time the event was stored. Required.""" + + @overload + def __init__( + self, + *, + event: "_models.Event", + ingested_at: datetime.datetime, + stored_at: datetime.datetime, + customer_id: Optional[str] = None, + validation_error: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InstallWithApiKeyRequest(_Model): + """InstallWithApiKeyRequest. + + :ivar name: Name of the application to install. + + If name is not provided defaults to the marketplace listing's name. + :vartype name: str + :ivar create_billing_profile: If true, a billing profile will be created for the app. The + Stripe app will be also set as the default billing profile if the current default is a Sandbox + app. + :vartype create_billing_profile: bool + :ivar api_key: The API key for the provider. For example, the Stripe API key. Required. + :vartype api_key: str + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the application to install. + + If name is not provided defaults to the marketplace listing's name.""" + create_billing_profile: Optional[bool] = rest_field( + name="createBillingProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """If true, a billing profile will be created for the app. The Stripe app will be also set as the + default billing profile if the current default is a Sandbox app.""" + api_key: str = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) + """The API key for the provider. For example, the Stripe API key. Required.""" + + @overload + def __init__( + self, + *, + api_key: str, + name: Optional[str] = None, + create_billing_profile: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InternalServerErrorProblemResponse(UnexpectedProblemResponse): + """The server encountered an unexpected condition that prevented it from fulfilling the request. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Invoice(_Model): + """Invoice represents an invoice in the system. + + :ivar id: ID. Required. + :vartype id: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar type: Type of the invoice. The type of invoice determines the purpose of the invoice and + how it should be handled. Supported types: + + * standard: A regular commercial invoice document between a supplier and customer. + * credit_note: Reflects a refund either partial or complete of the preceding document. A + credit note effectively *extends* the previous document. Required. Known values are: "standard" + and "credit_note". + :vartype type: str or ~openmeter.models.InvoiceType + :ivar supplier: The taxable entity supplying the goods or services. Required. + :vartype supplier: ~openmeter._generated.models.BillingParty + :ivar customer: Legal entity receiving the goods or services. Required. + :vartype customer: ~openmeter._generated.models.BillingInvoiceCustomerExtendedDetails + :ivar number: Number specifies the human readable key used to reference this Invoice. + + The invoice number can change in the draft phases, as we are allocating temporary draft + invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + + Please note that the number is (depending on the upstream settings) either unique for the + whole organization or unique for the customer, or in multi (stripe) account setups unique for + the + account. Required. + :vartype number: str + :ivar currency: Currency for all invoice line items. + + Multi currency invoices are not supported yet. Required. + :vartype currency: str + :ivar preceding: Key information regarding previous invoices and potentially details as to why + they were corrected. + :vartype preceding: list[~openmeter._generated.models.CreditNoteOriginalInvoiceRef] + :ivar totals: Summary of all the invoice totals, including taxes (calculated). Required. + :vartype totals: ~openmeter._generated.models.InvoiceTotals + :ivar status: The status of the invoice. + + This field only conatins a simplified status, for more detailed information use the + statusDetails field. Required. Known values are: "gathering", "draft", "issuing", "issued", + "payment_processing", "overdue", "paid", "uncollectible", and "voided". + :vartype status: str or ~openmeter.models.InvoiceStatus + :ivar status_details: The details of the current invoice status. Required. + :vartype status_details: ~openmeter._generated.models.InvoiceStatusDetails + :ivar issued_at: The time the invoice was issued. Depending on the status of the invoice this + can mean multiple things: + + * draft, gathering: The time the invoice will be issued based on the workflow settings. + * issued: The time the invoice was issued. + :vartype issued_at: ~datetime.datetime + :ivar draft_until: The time until the invoice is in draft status. + + On draft invoice creation it is calculated from the workflow settings. + + If manual approval is required, the draftUntil time is set. + :vartype draft_until: ~datetime.datetime + :ivar quantity_snapshoted_at: The time when the quantity snapshots on the invoice lines were + taken. + :vartype quantity_snapshoted_at: ~datetime.datetime + :ivar collection_at: The time when the invoice will be/has been collected. + :vartype collection_at: ~datetime.datetime + :ivar due_at: Due time of the fulfillment of the invoice (if available). + :vartype due_at: ~datetime.datetime + :ivar period: The period the invoice covers. If the invoice has no line items, it's not set. + :vartype period: ~openmeter._generated.models.Period + :ivar voided_at: The time the invoice was voided. + + If the invoice was voided, this field will be set to the time the invoice was voided. + :vartype voided_at: ~datetime.datetime + :ivar sent_to_customer_at: The time the invoice was sent to customer. + :vartype sent_to_customer_at: ~datetime.datetime + :ivar workflow: The workflow associated with the invoice. + + It is always a snapshot of the workflow settings at the time of invoice creation. The + field is optional as it should be explicitly requested with expand options. Required. + :vartype workflow: ~openmeter._generated.models.InvoiceWorkflowSettings + :ivar lines: List of invoice lines representing each of the items sold to the customer. + :vartype lines: list[~openmeter._generated.models.InvoiceLine] + :ivar payment: Information on when, how, and to whom the invoice should be paid. + :vartype payment: ~openmeter._generated.models.InvoicePaymentTerms + :ivar validation_issues: Validation issues reported by the invoice workflow. + :vartype validation_issues: list[~openmeter._generated.models.ValidationIssue] + :ivar external_ids: External IDs of the invoice in other apps such as Stripe. + :vartype external_ids: ~openmeter._generated.models.InvoiceAppExternalIds + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + type: Union[str, "_models.InvoiceType"] = rest_field(visibility=["read"]) + """Type of the invoice. The type of invoice determines the purpose of the invoice and how it + should be handled. Supported types: + + * standard: A regular commercial invoice document between a supplier and customer. + * credit_note: Reflects a refund either partial or complete of the preceding document. A + credit note effectively *extends* the previous document. Required. Known values are: + \"standard\" and \"credit_note\".""" + supplier: "_models.BillingParty" = rest_field(visibility=["read", "create", "update"]) + """The taxable entity supplying the goods or services. Required.""" + customer: "_models.BillingInvoiceCustomerExtendedDetails" = rest_field(visibility=["read", "create", "update"]) + """Legal entity receiving the goods or services. Required.""" + number: str = rest_field(visibility=["read"]) + """Number specifies the human readable key used to reference this Invoice. + + The invoice number can change in the draft phases, as we are allocating temporary draft + invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + + Please note that the number is (depending on the upstream settings) either unique for the + whole organization or unique for the customer, or in multi (stripe) account setups unique for + the + account. Required.""" + currency: str = rest_field(visibility=["read", "create"]) + """Currency for all invoice line items. + + Multi currency invoices are not supported yet. Required.""" + preceding: Optional[list["_types.InvoiceDocumentRef"]] = rest_field(visibility=["read"]) + """Key information regarding previous invoices and potentially details as to why they were + corrected.""" + totals: "_models.InvoiceTotals" = rest_field(visibility=["read"]) + """Summary of all the invoice totals, including taxes (calculated). Required.""" + status: Union[str, "_models.InvoiceStatus"] = rest_field(visibility=["read"]) + """The status of the invoice. + + This field only conatins a simplified status, for more detailed information use the + statusDetails field. Required. Known values are: \"gathering\", \"draft\", \"issuing\", + \"issued\", \"payment_processing\", \"overdue\", \"paid\", \"uncollectible\", and \"voided\".""" + status_details: "_models.InvoiceStatusDetails" = rest_field(name="statusDetails", visibility=["read"]) + """The details of the current invoice status. Required.""" + issued_at: Optional[datetime.datetime] = rest_field(name="issuedAt", visibility=["read"], format="rfc3339") + """The time the invoice was issued. Depending on the status of the invoice this can mean multiple + things: + + * draft, gathering: The time the invoice will be issued based on the workflow settings. + * issued: The time the invoice was issued.""" + draft_until: Optional[datetime.datetime] = rest_field( + name="draftUntil", visibility=["read", "update"], format="rfc3339" + ) + """The time until the invoice is in draft status. + + On draft invoice creation it is calculated from the workflow settings. + + If manual approval is required, the draftUntil time is set.""" + quantity_snapshoted_at: Optional[datetime.datetime] = rest_field( + name="quantitySnapshotedAt", visibility=["read"], format="rfc3339" + ) + """The time when the quantity snapshots on the invoice lines were taken.""" + collection_at: Optional[datetime.datetime] = rest_field(name="collectionAt", visibility=["read"], format="rfc3339") + """The time when the invoice will be/has been collected.""" + due_at: Optional[datetime.datetime] = rest_field(name="dueAt", visibility=["read"], format="rfc3339") + """Due time of the fulfillment of the invoice (if available).""" + period: Optional["_models.Period"] = rest_field(visibility=["read", "create"]) + """The period the invoice covers. If the invoice has no line items, it's not set.""" + voided_at: Optional[datetime.datetime] = rest_field(name="voidedAt", visibility=["read"], format="rfc3339") + """The time the invoice was voided. + + If the invoice was voided, this field will be set to the time the invoice was voided.""" + sent_to_customer_at: Optional[datetime.datetime] = rest_field( + name="sentToCustomerAt", visibility=["read"], format="rfc3339" + ) + """The time the invoice was sent to customer.""" + workflow: "_models.InvoiceWorkflowSettings" = rest_field(visibility=["read", "create", "update"]) + """The workflow associated with the invoice. + + It is always a snapshot of the workflow settings at the time of invoice creation. The + field is optional as it should be explicitly requested with expand options. Required.""" + lines: Optional[list["_models.InvoiceLine"]] = rest_field(visibility=["read", "update"]) + """List of invoice lines representing each of the items sold to the customer.""" + payment: Optional["_models.InvoicePaymentTerms"] = rest_field(visibility=["read"]) + """Information on when, how, and to whom the invoice should be paid.""" + validation_issues: Optional[list["_models.ValidationIssue"]] = rest_field( + name="validationIssues", visibility=["read"] + ) + """Validation issues reported by the invoice workflow.""" + external_ids: Optional["_models.InvoiceAppExternalIds"] = rest_field(name="externalIds", visibility=["read"]) + """External IDs of the invoice in other apps such as Stripe.""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + supplier: "_models.BillingParty", + customer: "_models.BillingInvoiceCustomerExtendedDetails", + currency: str, + workflow: "_models.InvoiceWorkflowSettings", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + draft_until: Optional[datetime.datetime] = None, + period: Optional["_models.Period"] = None, + lines: Optional[list["_models.InvoiceLine"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceAppExternalIds(_Model): + """InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + + :ivar invoicing: The external ID of the invoice in the invoicing app if available. + :vartype invoicing: str + :ivar tax: The external ID of the invoice in the tax app if available. + :vartype tax: str + :ivar payment: The external ID of the invoice in the payment app if available. + :vartype payment: str + """ + + invoicing: Optional[str] = rest_field(visibility=["read"]) + """The external ID of the invoice in the invoicing app if available.""" + tax: Optional[str] = rest_field(visibility=["read"]) + """The external ID of the invoice in the tax app if available.""" + payment: Optional[str] = rest_field(visibility=["read"]) + """The external ID of the invoice in the payment app if available.""" + + +class InvoiceAvailableActionDetails(_Model): + """InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + non-gathering invoices. + + :ivar resulting_state: The state the invoice will reach if the action is activated and + all intermediate steps are successful. + + For example advancing a draft_created invoice will result in a draft_manual_approval_needed + invoice. Required. + :vartype resulting_state: str + """ + + resulting_state: str = rest_field(name="resultingState", visibility=["read"]) + """The state the invoice will reach if the action is activated and + all intermediate steps are successful. + + For example advancing a draft_created invoice will result in a draft_manual_approval_needed + invoice. Required.""" + + +class InvoiceAvailableActionInvoiceDetails(_Model): + """InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for gathering + invoices. + + """ + + +class InvoiceAvailableActions(_Model): + """InvoiceAvailableActions represents the actions that can be performed on the invoice. + + :ivar advance: Advance the invoice to the next status. + :vartype advance: ~openmeter._generated.models.InvoiceAvailableActionDetails + :ivar approve: Approve an invoice that requires manual approval. + :vartype approve: ~openmeter._generated.models.InvoiceAvailableActionDetails + :ivar delete: Delete the invoice (only non-issued invoices can be deleted). + :vartype delete: ~openmeter._generated.models.InvoiceAvailableActionDetails + :ivar retry: Retry an invoice issuing step that failed. + :vartype retry: ~openmeter._generated.models.InvoiceAvailableActionDetails + :ivar snapshot_quantities: Snapshot quantities for usage based line items. + :vartype snapshot_quantities: ~openmeter._generated.models.InvoiceAvailableActionDetails + :ivar void: Void an already issued invoice. + :vartype void: ~openmeter._generated.models.InvoiceAvailableActionDetails + :ivar invoice: Invoice a gathering invoice. + :vartype invoice: ~openmeter._generated.models.InvoiceAvailableActionInvoiceDetails + """ + + advance: Optional["_models.InvoiceAvailableActionDetails"] = rest_field(visibility=["read"]) + """Advance the invoice to the next status.""" + approve: Optional["_models.InvoiceAvailableActionDetails"] = rest_field(visibility=["read"]) + """Approve an invoice that requires manual approval.""" + delete: Optional["_models.InvoiceAvailableActionDetails"] = rest_field(visibility=["read"]) + """Delete the invoice (only non-issued invoices can be deleted).""" + retry: Optional["_models.InvoiceAvailableActionDetails"] = rest_field(visibility=["read"]) + """Retry an invoice issuing step that failed.""" + snapshot_quantities: Optional["_models.InvoiceAvailableActionDetails"] = rest_field( + name="snapshotQuantities", visibility=["read"] + ) + """Snapshot quantities for usage based line items.""" + void: Optional["_models.InvoiceAvailableActionDetails"] = rest_field(visibility=["read"]) + """Void an already issued invoice.""" + invoice: Optional["_models.InvoiceAvailableActionInvoiceDetails"] = rest_field(visibility=["read"]) + """Invoice a gathering invoice.""" + + +class InvoiceDetailedLine(_Model): + """InvoiceDetailedLine represents a line item that is sold to the customer as a manually added + fee. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: ID of the line. Required. + :vartype id: str + :ivar managed_by: managedBy specifies if the line is manually added via the api or managed by + OpenMeter. Required. Known values are: "subscription", "system", and "manual". + :vartype managed_by: str or ~openmeter.models.InvoiceLineManagedBy + :ivar status: Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. Required. Known values are: "valid", "detailed", and "split". + :vartype status: str or ~openmeter.models.InvoiceLineStatus + :ivar discounts: Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + :vartype discounts: ~openmeter._generated.models.InvoiceLineDiscounts + :ivar credit_allocations: Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + :vartype credit_allocations: list[~openmeter._generated.models.InvoiceLineCreditAllocation] + :ivar invoice: The invoice this item belongs to. + :vartype invoice: ~openmeter._generated.models.InvoiceReference + :ivar currency: The currency of this line. Required. + :vartype currency: str + :ivar taxes: Taxes applied to the invoice totals. + :vartype taxes: list[~openmeter._generated.models.InvoiceLineTaxItem] + :ivar tax_config: Tax config specify the tax configuration for this line. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar totals: Totals for this line. Required. + :vartype totals: ~openmeter._generated.models.InvoiceTotals + :ivar period: Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required. + :vartype period: ~openmeter._generated.models.Period + :ivar external_ids: External IDs of the invoice in other apps such as Stripe. + :vartype external_ids: ~openmeter._generated.models.InvoiceLineAppExternalIds + :ivar subscription: Subscription are the references to the subscritpions that this line is + related to. + :vartype subscription: ~openmeter._generated.models.InvoiceLineSubscriptionReference + :ivar invoice_at: The time this line item should be invoiced. Required. + :vartype invoice_at: ~datetime.datetime + :ivar type: Type of the line. Required. FLAT_FEE. + :vartype type: str or ~openmeter._generated.models.FLAT_FEE + :ivar per_unit_amount: Price of the item being sold. + :vartype per_unit_amount: str + :ivar payment_term: Payment term of the line. Known values are: "in_advance" and "in_arrears". + :vartype payment_term: str or ~openmeter.models.PricePaymentTerm + :ivar quantity: Quantity of the item being sold. + :vartype quantity: str + :ivar rate_card: The rate card that is used for this line. + :vartype rate_card: ~openmeter._generated.models.InvoiceDetailedLineRateCard + :ivar category: Category of the flat fee. Known values are: "regular" and "commitment". + :vartype category: str or ~openmeter.models.InvoiceDetailedLineCostCategory + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read", "update"]) + """ID of the line. Required.""" + managed_by: Union[str, "_models.InvoiceLineManagedBy"] = rest_field(name="managedBy", visibility=["read"]) + """managedBy specifies if the line is manually added via the api or managed by OpenMeter. + Required. Known values are: \"subscription\", \"system\", and \"manual\".""" + status: Union[str, "_models.InvoiceLineStatus"] = rest_field(visibility=["read"]) + """Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. Required. Known values are: \"valid\", \"detailed\", and + \"split\".""" + discounts: Optional["_models.InvoiceLineDiscounts"] = rest_field(visibility=["read"]) + """Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines.""" + credit_allocations: Optional[list["_models.InvoiceLineCreditAllocation"]] = rest_field( + name="creditAllocations", visibility=["read"] + ) + """Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied.""" + invoice: Optional["_models.InvoiceReference"] = rest_field(visibility=["read", "create"]) + """The invoice this item belongs to.""" + currency: str = rest_field(visibility=["read", "create"]) + """The currency of this line. Required.""" + taxes: Optional[list["_models.InvoiceLineTaxItem"]] = rest_field(visibility=["read"]) + """Taxes applied to the invoice totals.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config specify the tax configuration for this line.""" + totals: "_models.InvoiceTotals" = rest_field(visibility=["read"]) + """Totals for this line. Required.""" + period: "_models.Period" = rest_field(visibility=["read", "create", "update"]) + """Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required.""" + external_ids: Optional["_models.InvoiceLineAppExternalIds"] = rest_field(name="externalIds", visibility=["read"]) + """External IDs of the invoice in other apps such as Stripe.""" + subscription: Optional["_models.InvoiceLineSubscriptionReference"] = rest_field(visibility=["read"]) + """Subscription are the references to the subscritpions that this line is related to.""" + invoice_at: datetime.datetime = rest_field( + name="invoiceAt", visibility=["read", "create", "update"], format="rfc3339" + ) + """The time this line item should be invoiced. Required.""" + type: Literal[InvoiceLineTypes.FLAT_FEE] = rest_field(visibility=["read"]) + """Type of the line. Required. FLAT_FEE.""" + per_unit_amount: Optional[str] = rest_field(name="perUnitAmount", visibility=["read", "create", "update"]) + """Price of the item being sold.""" + payment_term: Optional[Union[str, "_models.PricePaymentTerm"]] = rest_field( + name="paymentTerm", visibility=["read", "create", "update"] + ) + """Payment term of the line. Known values are: \"in_advance\" and \"in_arrears\".""" + quantity: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Quantity of the item being sold.""" + rate_card: Optional["_models.InvoiceDetailedLineRateCard"] = rest_field( + name="rateCard", visibility=["read", "create", "update"] + ) + """The rate card that is used for this line.""" + category: Optional[Union[str, "_models.InvoiceDetailedLineCostCategory"]] = rest_field(visibility=["read"]) + """Category of the flat fee. Known values are: \"regular\" and \"commitment\".""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + name: str, + id: str, # pylint: disable=redefined-builtin + currency: str, + period: "_models.Period", + invoice_at: datetime.datetime, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + invoice: Optional["_models.InvoiceReference"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + per_unit_amount: Optional[str] = None, + payment_term: Optional[Union[str, "_models.PricePaymentTerm"]] = None, + quantity: Optional[str] = None, + rate_card: Optional["_models.InvoiceDetailedLineRateCard"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceDetailedLineRateCard(_Model): + """InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. + + :ivar tax_config: Tax config. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar price: Price. Required. + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm + :ivar quantity: Quantity of the item being sold. + + Default: 1. + :vartype quantity: str + :ivar discounts: The discounts that are applied to the line. + :vartype discounts: ~openmeter._generated.models.BillingDiscounts + """ + + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config.""" + price: "_models.FlatPriceWithPaymentTerm" = rest_field(visibility=["read", "create", "update"]) + """Price. Required.""" + quantity: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Quantity of the item being sold. + + Default: 1.""" + discounts: Optional["_models.BillingDiscounts"] = rest_field(visibility=["read", "create", "update"]) + """The discounts that are applied to the line.""" + + @overload + def __init__( + self, + *, + price: "_models.FlatPriceWithPaymentTerm", + tax_config: Optional["_models.TaxConfig"] = None, + quantity: Optional[str] = None, + discounts: Optional["_models.BillingDiscounts"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceLine(_Model): + """InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: ID of the line. Required. + :vartype id: str + :ivar managed_by: managedBy specifies if the line is manually added via the api or managed by + OpenMeter. Required. Known values are: "subscription", "system", and "manual". + :vartype managed_by: str or ~openmeter.models.InvoiceLineManagedBy + :ivar status: Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. Required. Known values are: "valid", "detailed", and "split". + :vartype status: str or ~openmeter.models.InvoiceLineStatus + :ivar discounts: Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + :vartype discounts: ~openmeter._generated.models.InvoiceLineDiscounts + :ivar credit_allocations: Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + :vartype credit_allocations: list[~openmeter._generated.models.InvoiceLineCreditAllocation] + :ivar invoice: The invoice this item belongs to. + :vartype invoice: ~openmeter._generated.models.InvoiceReference + :ivar currency: The currency of this line. Required. + :vartype currency: str + :ivar taxes: Taxes applied to the invoice totals. + :vartype taxes: list[~openmeter._generated.models.InvoiceLineTaxItem] + :ivar tax_config: Tax config specify the tax configuration for this line. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar totals: Totals for this line. Required. + :vartype totals: ~openmeter._generated.models.InvoiceTotals + :ivar period: Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required. + :vartype period: ~openmeter._generated.models.Period + :ivar invoice_at: The time this line item should be invoiced. Required. + :vartype invoice_at: ~datetime.datetime + :ivar external_ids: External IDs of the invoice in other apps such as Stripe. + :vartype external_ids: ~openmeter._generated.models.InvoiceLineAppExternalIds + :ivar subscription: Subscription are the references to the subscritpions that this line is + related to. + :vartype subscription: ~openmeter._generated.models.InvoiceLineSubscriptionReference + :ivar type: Type of the line. Required. USAGE_BASED. + :vartype type: str or ~openmeter._generated.models.USAGE_BASED + :ivar price: Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar feature_key: The feature that the usage is based on. + :vartype feature_key: str + :ivar children: The lines detailing the item or service sold. + :vartype children: list[~openmeter._generated.models.InvoiceDetailedLine] + :ivar rate_card: The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + :vartype rate_card: ~openmeter._generated.models.InvoiceUsageBasedRateCard + :ivar quantity: The quantity of the item being sold. + + Any usage discounts applied previously are deducted from this quantity. + :vartype quantity: str + :ivar metered_quantity: The quantity of the item that has been metered for the period before + any discounts were applied. + :vartype metered_quantity: str + :ivar pre_line_period_quantity: The quantity of the item used before this line's period. + + It is non-zero in case of progressive billing, when this shows how much of the usage was + already billed. + + Any usage discounts applied previously are deducted from this quantity. + :vartype pre_line_period_quantity: str + :ivar metered_pre_line_period_quantity: The metered quantity of the item used in before this + line's period without any discounts applied. + + It is non-zero in case of progressive billing, when this shows how much of the usage was + already billed. + :vartype metered_pre_line_period_quantity: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read", "update"]) + """ID of the line. Required.""" + managed_by: Union[str, "_models.InvoiceLineManagedBy"] = rest_field(name="managedBy", visibility=["read"]) + """managedBy specifies if the line is manually added via the api or managed by OpenMeter. + Required. Known values are: \"subscription\", \"system\", and \"manual\".""" + status: Union[str, "_models.InvoiceLineStatus"] = rest_field(visibility=["read"]) + """Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. Required. Known values are: \"valid\", \"detailed\", and + \"split\".""" + discounts: Optional["_models.InvoiceLineDiscounts"] = rest_field(visibility=["read"]) + """Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines.""" + credit_allocations: Optional[list["_models.InvoiceLineCreditAllocation"]] = rest_field( + name="creditAllocations", visibility=["read"] + ) + """Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied.""" + invoice: Optional["_models.InvoiceReference"] = rest_field(visibility=["read", "create"]) + """The invoice this item belongs to.""" + currency: str = rest_field(visibility=["read", "create"]) + """The currency of this line. Required.""" + taxes: Optional[list["_models.InvoiceLineTaxItem"]] = rest_field(visibility=["read"]) + """Taxes applied to the invoice totals.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config specify the tax configuration for this line.""" + totals: "_models.InvoiceTotals" = rest_field(visibility=["read"]) + """Totals for this line. Required.""" + period: "_models.Period" = rest_field(visibility=["read", "create", "update"]) + """Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required.""" + invoice_at: datetime.datetime = rest_field( + name="invoiceAt", visibility=["read", "create", "update"], format="rfc3339" + ) + """The time this line item should be invoiced. Required.""" + external_ids: Optional["_models.InvoiceLineAppExternalIds"] = rest_field(name="externalIds", visibility=["read"]) + """External IDs of the invoice in other apps such as Stripe.""" + subscription: Optional["_models.InvoiceLineSubscriptionReference"] = rest_field(visibility=["read"]) + """Subscription are the references to the subscritpions that this line is related to.""" + type: Literal[InvoiceLineTypes.USAGE_BASED] = rest_field(visibility=["read"]) + """Type of the line. Required. USAGE_BASED.""" + price: Optional["_types.RateCardUsageBasedPrice"] = rest_field(visibility=["read", "create", "update"]) + """Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments""" + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """The feature that the usage is based on.""" + children: Optional[list["_models.InvoiceDetailedLine"]] = rest_field(visibility=["read"]) + """The lines detailing the item or service sold.""" + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = rest_field( + name="rateCard", visibility=["read", "create", "update"] + ) + """The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item.""" + quantity: Optional[str] = rest_field(visibility=["read"]) + """The quantity of the item being sold. + + Any usage discounts applied previously are deducted from this quantity.""" + metered_quantity: Optional[str] = rest_field(name="meteredQuantity", visibility=["read"]) + """The quantity of the item that has been metered for the period before any discounts were + applied.""" + pre_line_period_quantity: Optional[str] = rest_field(name="preLinePeriodQuantity", visibility=["read"]) + """The quantity of the item used before this line's period. + + It is non-zero in case of progressive billing, when this shows how much of the usage was + already billed. + + Any usage discounts applied previously are deducted from this quantity.""" + metered_pre_line_period_quantity: Optional[str] = rest_field( + name="meteredPreLinePeriodQuantity", visibility=["read"] + ) + """The metered quantity of the item used in before this line's period without any discounts + applied. + + It is non-zero in case of progressive billing, when this shows how much of the usage was + already billed.""" + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + name: str, + id: str, # pylint: disable=redefined-builtin + currency: str, + period: "_models.Period", + invoice_at: datetime.datetime, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + invoice: Optional["_models.InvoiceReference"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + price: Optional["_types.RateCardUsageBasedPrice"] = None, + feature_key: Optional[str] = None, + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceLineAmountDiscount(_Model): + """InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied + before taxes. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: ID of the charge or discount. Required. + :vartype id: str + :ivar reason: Reason code. Required. Is one of the following types: DiscountReasonMaximumSpend, + DiscountReasonRatecardPercentage, DiscountReasonRatecardUsage + :vartype reason: ~openmeter._generated.models.DiscountReasonMaximumSpend or + ~openmeter._generated.models.DiscountReasonRatecardPercentage or + ~openmeter._generated.models.DiscountReasonRatecardUsage + :ivar description: Text description as to why the discount was applied. + :vartype description: str + :ivar external_ids: External IDs of the invoice in other apps such as Stripe. + :vartype external_ids: ~openmeter._generated.models.InvoiceLineAppExternalIds + :ivar amount: Amount in the currency of the invoice. Required. + :vartype amount: str + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """ID of the charge or discount. Required.""" + reason: "_types.BillingDiscountReason" = rest_field(visibility=["read"]) + """Reason code. Required. Is one of the following types: DiscountReasonMaximumSpend, + DiscountReasonRatecardPercentage, DiscountReasonRatecardUsage""" + description: Optional[str] = rest_field(visibility=["read"]) + """Text description as to why the discount was applied.""" + external_ids: Optional["_models.InvoiceLineAppExternalIds"] = rest_field(name="externalIds", visibility=["read"]) + """External IDs of the invoice in other apps such as Stripe.""" + amount: str = rest_field(visibility=["read"]) + """Amount in the currency of the invoice. Required.""" + + +class InvoiceLineAppExternalIds(_Model): + """InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as + Stripe. + + :ivar invoicing: The external ID of the invoice in the invoicing app if available. + :vartype invoicing: str + :ivar tax: The external ID of the invoice in the tax app if available. + :vartype tax: str + """ + + invoicing: Optional[str] = rest_field(visibility=["read"]) + """The external ID of the invoice in the invoicing app if available.""" + tax: Optional[str] = rest_field(visibility=["read"]) + """The external ID of the invoice in the tax app if available.""" + + +class InvoiceLineCreditAllocation(_Model): + """InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are + applied. + + :ivar amount: Amount in the currency of the invoice. Required. + :vartype amount: str + :ivar description: Text description as to why the credit was allocated. + :vartype description: str + """ + + amount: str = rest_field(visibility=["read"]) + """Amount in the currency of the invoice. Required.""" + description: Optional[str] = rest_field(visibility=["read"]) + """Text description as to why the credit was allocated.""" + + +class InvoiceLineDiscounts(_Model): + """InvoiceLineDiscounts represents the discounts applied to the invoice line by type. + + :ivar amount: Amount based discounts applied to the line. + + Amount based discounts are deduced from the total price of the line. + :vartype amount: list[~openmeter._generated.models.InvoiceLineAmountDiscount] + :ivar usage: Usage based discounts applied to the line. + + Usage based discounts are deduced from the usage of the line before price calculations are + applied. + :vartype usage: list[~openmeter._generated.models.InvoiceLineUsageDiscount] + """ + + amount: Optional[list["_models.InvoiceLineAmountDiscount"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Amount based discounts applied to the line. + + Amount based discounts are deduced from the total price of the line.""" + usage: Optional[list["_models.InvoiceLineUsageDiscount"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Usage based discounts applied to the line. + + Usage based discounts are deduced from the usage of the line before price calculations are + applied.""" + + @overload + def __init__( + self, + *, + amount: Optional[list["_models.InvoiceLineAmountDiscount"]] = None, + usage: Optional[list["_models.InvoiceLineUsageDiscount"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceLineReplaceUpdate(_Model): + """InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. + + This type makes ID optional to allow for creating new lines as part of the update. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar tax_config: Tax config specify the tax configuration for this line. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar period: Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required. + :vartype period: ~openmeter._generated.models.Period + :ivar invoice_at: The time this line item should be invoiced. Required. + :vartype invoice_at: ~datetime.datetime + :ivar price: Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar feature_key: The feature that the usage is based on. + :vartype feature_key: str + :ivar rate_card: The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + :vartype rate_card: ~openmeter._generated.models.InvoiceUsageBasedRateCard + :ivar id: The ID of the line. + :vartype id: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config specify the tax configuration for this line.""" + period: "_models.Period" = rest_field(visibility=["read", "create", "update"]) + """Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required.""" + invoice_at: datetime.datetime = rest_field( + name="invoiceAt", visibility=["read", "create", "update"], format="rfc3339" + ) + """The time this line item should be invoiced. Required.""" + price: Optional["_types.RateCardUsageBasedPrice"] = rest_field(visibility=["read", "create", "update"]) + """Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments""" + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """The feature that the usage is based on.""" + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = rest_field( + name="rateCard", visibility=["read", "create", "update"] + ) + """The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item.""" + id: Optional[str] = rest_field(visibility=["update"]) + """The ID of the line.""" + + @overload + def __init__( + self, + *, + name: str, + period: "_models.Period", + invoice_at: datetime.datetime, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + price: Optional["_types.RateCardUsageBasedPrice"] = None, + feature_key: Optional[str] = None, + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceLineSubscriptionReference(_Model): + """InvoiceLineSubscriptionReference contains the references to the subscription that this line is + related to. + + :ivar subscription: The subscription. Required. + :vartype subscription: ~openmeter._generated.models.IDResource + :ivar phase: The phase of the subscription. Required. + :vartype phase: ~openmeter._generated.models.IDResource + :ivar item: The item this line is related to. Required. + :vartype item: ~openmeter._generated.models.IDResource + :ivar billing_period: The billing period of the subscription. In case the subscription item's + billing period is different from the subscription's billing period, this field will contain the + billing period of the subscription itself. For example, in case of: + + * A monthly billed subscription anchored to 2025-01-01 + * A subscription item billed daily + + An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed + daily, but the subscription's billing period + will be 2025-01-01 to 2025-01-31. Required. + :vartype billing_period: ~openmeter._generated.models.Period + """ + + subscription: "_models.IDResource" = rest_field(visibility=["read"]) + """The subscription. Required.""" + phase: "_models.IDResource" = rest_field(visibility=["read"]) + """The phase of the subscription. Required.""" + item: "_models.IDResource" = rest_field(visibility=["read"]) + """The item this line is related to. Required.""" + billing_period: "_models.Period" = rest_field(name="billingPeriod", visibility=["read"]) + """The billing period of the subscription. In case the subscription item's billing period is + different from the subscription's billing period, this field will contain the billing period of + the subscription itself. For example, in case of: + + * A monthly billed subscription anchored to 2025-01-01 + * A subscription item billed daily + + An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed + daily, but the subscription's billing period + will be 2025-01-01 to 2025-01-31. Required.""" + + +class InvoiceLineTaxItem(_Model): + """TaxConfig stores the configuration for a tax line relative to an invoice line. + + :ivar config: Tax provider configuration. + :vartype config: ~openmeter._generated.models.TaxConfig + :ivar percent: Percent defines the percentage set manually or determined from the rate key + (calculated if rate present). A nil percent implies that this tax combo is **exempt** from + tax."). + :vartype percent: float + :ivar surcharge: Some countries require an additional surcharge (calculated if rate present). + :vartype surcharge: str + :ivar behavior: Is the tax item inclusive or exclusive of the base amount. Known values are: + "inclusive" and "exclusive". + :vartype behavior: str or ~openmeter.models.InvoiceLineTaxBehavior + """ + + config: Optional["_models.TaxConfig"] = rest_field(visibility=["read"]) + """Tax provider configuration.""" + percent: Optional[float] = rest_field(visibility=["read"]) + """Percent defines the percentage set manually or determined from the rate key (calculated if rate + present). A nil percent implies that this tax combo is **exempt** from tax.\").""" + surcharge: Optional[str] = rest_field(visibility=["read"]) + """Some countries require an additional surcharge (calculated if rate present).""" + behavior: Optional[Union[str, "_models.InvoiceLineTaxBehavior"]] = rest_field(visibility=["read"]) + """Is the tax item inclusive or exclusive of the base amount. Known values are: \"inclusive\" and + \"exclusive\".""" + + +class InvoiceLineUsageDiscount(_Model): + """InvoiceLineUsageDiscount represents an usage-based discount applied to the line. + + The deduction is done before the pricing algorithm is applied. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: ID of the charge or discount. Required. + :vartype id: str + :ivar reason: Reason code. Required. Is one of the following types: DiscountReasonMaximumSpend, + DiscountReasonRatecardPercentage, DiscountReasonRatecardUsage + :vartype reason: ~openmeter._generated.models.DiscountReasonMaximumSpend or + ~openmeter._generated.models.DiscountReasonRatecardPercentage or + ~openmeter._generated.models.DiscountReasonRatecardUsage + :ivar description: Text description as to why the discount was applied. + :vartype description: str + :ivar external_ids: External IDs of the invoice in other apps such as Stripe. + :vartype external_ids: ~openmeter._generated.models.InvoiceLineAppExternalIds + :ivar quantity: Usage quantity in the unit of the underlying meter. Required. + :vartype quantity: str + :ivar pre_line_period_quantity: Usage quantity in the unit of the underlying meter. + :vartype pre_line_period_quantity: str + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """ID of the charge or discount. Required.""" + reason: "_types.BillingDiscountReason" = rest_field(visibility=["read"]) + """Reason code. Required. Is one of the following types: DiscountReasonMaximumSpend, + DiscountReasonRatecardPercentage, DiscountReasonRatecardUsage""" + description: Optional[str] = rest_field(visibility=["read"]) + """Text description as to why the discount was applied.""" + external_ids: Optional["_models.InvoiceLineAppExternalIds"] = rest_field(name="externalIds", visibility=["read"]) + """External IDs of the invoice in other apps such as Stripe.""" + quantity: str = rest_field(visibility=["read"]) + """Usage quantity in the unit of the underlying meter. Required.""" + pre_line_period_quantity: Optional[str] = rest_field(name="preLinePeriodQuantity", visibility=["read"]) + """Usage quantity in the unit of the underlying meter.""" + + +class InvoicePaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.Invoice] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.Invoice"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.Invoice"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoicePaymentTerms(_Model): + """Payment contains details as to how the invoice should be paid. + + :ivar terms: The terms of payment for the invoice. Is either a PaymentTermInstant type or a + PaymentTermDueDate type. + :vartype terms: ~openmeter._generated.models.PaymentTermInstant or + ~openmeter._generated.models.PaymentTermDueDate + """ + + terms: Optional["_types.PaymentTerms"] = rest_field(visibility=["read", "create", "update"]) + """The terms of payment for the invoice. Is either a PaymentTermInstant type or a + PaymentTermDueDate type.""" + + @overload + def __init__( + self, + *, + terms: Optional["_types.PaymentTerms"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoicePendingLineCreate(_Model): + """InvoicePendingLineCreate represents the create model for an invoice line that is sold to the + customer based on usage. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar tax_config: Tax config specify the tax configuration for this line. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar period: Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required. + :vartype period: ~openmeter._generated.models.Period + :ivar invoice_at: The time this line item should be invoiced. Required. + :vartype invoice_at: ~datetime.datetime + :ivar price: Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar feature_key: The feature that the usage is based on. + :vartype feature_key: str + :ivar rate_card: The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + :vartype rate_card: ~openmeter._generated.models.InvoiceUsageBasedRateCard + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config specify the tax configuration for this line.""" + period: "_models.Period" = rest_field(visibility=["read", "create", "update"]) + """Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required.""" + invoice_at: datetime.datetime = rest_field( + name="invoiceAt", visibility=["read", "create", "update"], format="rfc3339" + ) + """The time this line item should be invoiced. Required.""" + price: Optional["_types.RateCardUsageBasedPrice"] = rest_field(visibility=["read", "create", "update"]) + """Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments""" + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """The feature that the usage is based on.""" + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = rest_field( + name="rateCard", visibility=["read", "create", "update"] + ) + """The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item.""" + + @overload + def __init__( + self, + *, + name: str, + period: "_models.Period", + invoice_at: datetime.datetime, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + price: Optional["_types.RateCardUsageBasedPrice"] = None, + feature_key: Optional[str] = None, + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoicePendingLineCreateInput(_Model): + """InvoicePendingLineCreate represents the create model for a pending invoice line. + + :ivar currency: The currency of the lines to be created. Required. + :vartype currency: str + :ivar lines: The lines to be created. Required. + :vartype lines: list[~openmeter._generated.models.InvoicePendingLineCreate] + """ + + currency: str = rest_field(visibility=["create"]) + """The currency of the lines to be created. Required.""" + lines: list["_models.InvoicePendingLineCreate"] = rest_field(visibility=["create"]) + """The lines to be created. Required.""" + + @overload + def __init__( + self, + *, + currency: str, + lines: list["_models.InvoicePendingLineCreate"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoicePendingLineCreateResponse(_Model): + """InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. + + :ivar lines: The lines that were created. Required. + :vartype lines: list[~openmeter._generated.models.InvoiceLine] + :ivar invoice: The invoice containing the created lines. Required. + :vartype invoice: ~openmeter._generated.models.Invoice + :ivar is_invoice_new: Whether the invoice was newly created. Required. + :vartype is_invoice_new: bool + """ + + lines: list["_models.InvoiceLine"] = rest_field(visibility=["read"]) + """The lines that were created. Required.""" + invoice: "_models.Invoice" = rest_field(visibility=["read"]) + """The invoice containing the created lines. Required.""" + is_invoice_new: bool = rest_field(name="isInvoiceNew", visibility=["read"]) + """Whether the invoice was newly created. Required.""" + + +class InvoicePendingLinesActionFiltersInput(_Model): + """InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. + + :ivar line_ids: The pending line items to include in the invoice, if not provided: + + * all line items that have invoice_at < asOf will be included + * [progressive billing only] all usage based line items will be included up to asOf, new + usage-based line items will be staged for the rest of the billing cycle + + All lineIDs present in the list, must exists and must be invoicable as of asOf, or the + action will fail. + :vartype line_ids: list[str] + """ + + line_ids: Optional[list[str]] = rest_field(name="lineIds", visibility=["create"]) + """The pending line items to include in the invoice, if not provided: + + * all line items that have invoice_at < asOf will be included + * [progressive billing only] all usage based line items will be included up to asOf, new + usage-based line items will be staged for the rest of the billing cycle + + All lineIDs present in the list, must exists and must be invoicable as of asOf, or the + action will fail.""" + + @overload + def __init__( + self, + *, + line_ids: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoicePendingLinesActionInput(_Model): + """BillingInvoiceActionInput is the input for creating an invoice. + + Invoice creation is always based on already pending line items created by the + billingCreateLineByCustomer + operation. Empty invoices are not allowed. + + :ivar filters: Filters to apply when creating the invoice. + :vartype filters: ~openmeter._generated.models.InvoicePendingLinesActionFiltersInput + :ivar as_of: The time as of which the invoice is created. + + If not provided, the current time is used. + :vartype as_of: ~datetime.datetime + :ivar customer_id: The customer ID for which to create the invoice. Required. + :vartype customer_id: str + :ivar progressive_billing_override: Override the progressive billing setting of the customer. + + Can be used to disable/enable progressive billing in case the business logic + requires it, if not provided the billing profile's progressive billing setting will be used. + :vartype progressive_billing_override: bool + """ + + filters: Optional["_models.InvoicePendingLinesActionFiltersInput"] = rest_field(visibility=["create"]) + """Filters to apply when creating the invoice.""" + as_of: Optional[datetime.datetime] = rest_field(name="asOf", visibility=["create"], format="rfc3339") + """The time as of which the invoice is created. + + If not provided, the current time is used.""" + customer_id: str = rest_field(name="customerId", visibility=["create"]) + """The customer ID for which to create the invoice. Required.""" + progressive_billing_override: Optional[bool] = rest_field(name="progressiveBillingOverride", visibility=["create"]) + """Override the progressive billing setting of the customer. + + Can be used to disable/enable progressive billing in case the business logic + requires it, if not provided the billing profile's progressive billing setting will be used.""" + + @overload + def __init__( + self, + *, + customer_id: str, + filters: Optional["_models.InvoicePendingLinesActionFiltersInput"] = None, + as_of: Optional[datetime.datetime] = None, + progressive_billing_override: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceReference(_Model): + """Reference to an invoice. + + :ivar id: The ID of the invoice. Required. + :vartype id: str + :ivar number: The number of the invoice. + :vartype number: str + """ + + id: str = rest_field(visibility=["read"]) + """The ID of the invoice. Required.""" + number: Optional[str] = rest_field(visibility=["read"]) + """The number of the invoice.""" + + +class InvoiceReplaceUpdate(_Model): + """InvoiceReplaceUpdate represents the update model for an invoice. + + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar supplier: The supplier of the lines included in the invoice. Required. + :vartype supplier: ~openmeter._generated.models.BillingPartyReplaceUpdate + :ivar customer: The customer the invoice is sent to. Required. + :vartype customer: ~openmeter._generated.models.BillingPartyReplaceUpdate + :ivar lines: The lines included in the invoice. Required. + :vartype lines: list[~openmeter._generated.models.InvoiceLineReplaceUpdate] + :ivar workflow: The workflow settings for the invoice. Required. + :vartype workflow: ~openmeter._generated.models.InvoiceWorkflowReplaceUpdate + """ + + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + supplier: "_models.BillingPartyReplaceUpdate" = rest_field(visibility=["update"]) + """The supplier of the lines included in the invoice. Required.""" + customer: "_models.BillingPartyReplaceUpdate" = rest_field(visibility=["update"]) + """The customer the invoice is sent to. Required.""" + lines: list["_models.InvoiceLineReplaceUpdate"] = rest_field(visibility=["update"]) + """The lines included in the invoice. Required.""" + workflow: "_models.InvoiceWorkflowReplaceUpdate" = rest_field(visibility=["update"]) + """The workflow settings for the invoice. Required.""" + + @overload + def __init__( + self, + *, + supplier: "_models.BillingPartyReplaceUpdate", + customer: "_models.BillingPartyReplaceUpdate", + lines: list["_models.InvoiceLineReplaceUpdate"], + workflow: "_models.InvoiceWorkflowReplaceUpdate", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceSimulationInput(_Model): + """InvoiceSimulationInput is the input for simulating an invoice. + + :ivar number: The number of the invoice. + :vartype number: str + :ivar currency: Currency for all invoice line items. + + Multi currency invoices are not supported yet. Required. + :vartype currency: str + :ivar lines: Lines to be included in the generated invoice. Required. + :vartype lines: list[~openmeter._generated.models.InvoiceSimulationLine] + """ + + number: Optional[str] = rest_field(visibility=["create"]) + """The number of the invoice.""" + currency: str = rest_field(visibility=["create"]) + """Currency for all invoice line items. + + Multi currency invoices are not supported yet. Required.""" + lines: list["_models.InvoiceSimulationLine"] = rest_field(visibility=["create"]) + """Lines to be included in the generated invoice. Required.""" + + @overload + def __init__( + self, + *, + currency: str, + lines: list["_models.InvoiceSimulationLine"], + number: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceSimulationLine(_Model): + """InvoiceSimulationLine represents a usage-based line item that can be input to the simulation + endpoint. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar tax_config: Tax config specify the tax configuration for this line. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar period: Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required. + :vartype period: ~openmeter._generated.models.Period + :ivar invoice_at: The time this line item should be invoiced. Required. + :vartype invoice_at: ~datetime.datetime + :ivar price: Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar feature_key: The feature that the usage is based on. + :vartype feature_key: str + :ivar rate_card: The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + :vartype rate_card: ~openmeter._generated.models.InvoiceUsageBasedRateCard + :ivar quantity: The quantity of the item being sold. Required. + :vartype quantity: str + :ivar pre_line_period_quantity: The quantity of the item used before this line's period, if the + line is billed progressively. + :vartype pre_line_period_quantity: str + :ivar id: ID of the line. If not specified it will be auto-generated. + + When discounts are specified, this must be provided, so that the discount can reference it. + :vartype id: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config specify the tax configuration for this line.""" + period: "_models.Period" = rest_field(visibility=["read", "create", "update"]) + """Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. Required.""" + invoice_at: datetime.datetime = rest_field( + name="invoiceAt", visibility=["read", "create", "update"], format="rfc3339" + ) + """The time this line item should be invoiced. Required.""" + price: Optional["_types.RateCardUsageBasedPrice"] = rest_field(visibility=["read", "create", "update"]) + """Price of the usage-based item being sold. Is one of the following types: + FlatPriceWithPaymentTerm, UnitPriceWithCommitments, TieredPriceWithCommitments, + DynamicPriceWithCommitments, PackagePriceWithCommitments""" + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """The feature that the usage is based on.""" + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = rest_field( + name="rateCard", visibility=["read", "create", "update"] + ) + """The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item.""" + quantity: str = rest_field(visibility=["create"]) + """The quantity of the item being sold. Required.""" + pre_line_period_quantity: Optional[str] = rest_field(name="preLinePeriodQuantity", visibility=["create"]) + """The quantity of the item used before this line's period, if the line is billed progressively.""" + id: Optional[str] = rest_field(visibility=["create"]) + """ID of the line. If not specified it will be auto-generated. + + When discounts are specified, this must be provided, so that the discount can reference it.""" + + @overload + def __init__( + self, + *, + name: str, + period: "_models.Period", + invoice_at: datetime.datetime, + quantity: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + price: Optional["_types.RateCardUsageBasedPrice"] = None, + feature_key: Optional[str] = None, + rate_card: Optional["_models.InvoiceUsageBasedRateCard"] = None, + pre_line_period_quantity: Optional[str] = None, + id: Optional[str] = None, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceStatusDetails(_Model): + """InvoiceStatusDetails represents the details of the invoice status. + + API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine + the next steps of the invoice instead of the extendedStatus field. + + :ivar immutable: Is the invoice editable?. Required. + :vartype immutable: bool + :ivar failed: Is the invoice in a failed state?. Required. + :vartype failed: bool + :ivar extended_status: Extended status information for the invoice. Required. + :vartype extended_status: str + :ivar available_actions: The actions that can be performed on the invoice. Required. + :vartype available_actions: ~openmeter._generated.models.InvoiceAvailableActions + """ + + immutable: bool = rest_field(visibility=["read"]) + """Is the invoice editable?. Required.""" + failed: bool = rest_field(visibility=["read"]) + """Is the invoice in a failed state?. Required.""" + extended_status: str = rest_field(name="extendedStatus", visibility=["read"]) + """Extended status information for the invoice. Required.""" + available_actions: "_models.InvoiceAvailableActions" = rest_field( + name="availableActions", visibility=["read", "create", "update", "delete", "query"] + ) + """The actions that can be performed on the invoice. Required.""" + + @overload + def __init__( + self, + *, + available_actions: "_models.InvoiceAvailableActions", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceTotals(_Model): + """Totals contains the summaries of all calculations for the invoice. + + :ivar amount: The total value of the line before taxes, discounts and commitments. Required. + :vartype amount: str + :ivar charges_total: The amount of value of the line that are due to additional charges. + Required. + :vartype charges_total: str + :ivar discounts_total: The amount of value of the line that are due to discounts. Required. + :vartype discounts_total: str + :ivar credits_total: The amount of value of the line that are due to credits. Required. + :vartype credits_total: str + :ivar taxes_inclusive_total: The total amount of taxes that are included in the line. Required. + :vartype taxes_inclusive_total: str + :ivar taxes_exclusive_total: The total amount of taxes that are added on top of amount from the + line. Required. + :vartype taxes_exclusive_total: str + :ivar taxes_total: The total amount of taxes for this line. Required. + :vartype taxes_total: str + :ivar total: The total amount value of the line after taxes, discounts and commitments. + Required. + :vartype total: str + """ + + amount: str = rest_field(visibility=["read"]) + """The total value of the line before taxes, discounts and commitments. Required.""" + charges_total: str = rest_field(name="chargesTotal", visibility=["read"]) + """The amount of value of the line that are due to additional charges. Required.""" + discounts_total: str = rest_field(name="discountsTotal", visibility=["read"]) + """The amount of value of the line that are due to discounts. Required.""" + credits_total: str = rest_field(name="creditsTotal", visibility=["read"]) + """The amount of value of the line that are due to credits. Required.""" + taxes_inclusive_total: str = rest_field(name="taxesInclusiveTotal", visibility=["read"]) + """The total amount of taxes that are included in the line. Required.""" + taxes_exclusive_total: str = rest_field(name="taxesExclusiveTotal", visibility=["read"]) + """The total amount of taxes that are added on top of amount from the line. Required.""" + taxes_total: str = rest_field(name="taxesTotal", visibility=["read"]) + """The total amount of taxes for this line. Required.""" + total: str = rest_field(visibility=["read"]) + """The total amount value of the line after taxes, discounts and commitments. Required.""" + + +class InvoiceUsageBasedRateCard(_Model): + """InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. + + :ivar feature_key: Feature key. + :vartype feature_key: str + :ivar tax_config: Tax config. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar price: The price of the rate card. When null, the feature or service is free. Required. + Is one of the following types: FlatPriceWithPaymentTerm, UnitPriceWithCommitments, + TieredPriceWithCommitments, DynamicPriceWithCommitments, PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar discounts: The discounts that are applied to the line. + :vartype discounts: ~openmeter._generated.models.BillingDiscounts + """ + + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """Feature key.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config.""" + price: "_types.RateCardUsageBasedPrice" = rest_field(visibility=["read", "create", "update"]) + """The price of the rate card. When null, the feature or service is free. Required. Is one of the + following types: FlatPriceWithPaymentTerm, UnitPriceWithCommitments, + TieredPriceWithCommitments, DynamicPriceWithCommitments, PackagePriceWithCommitments""" + discounts: Optional["_models.BillingDiscounts"] = rest_field(visibility=["read", "create", "update"]) + """The discounts that are applied to the line.""" + + @overload + def __init__( + self, + *, + price: "_types.RateCardUsageBasedPrice", + feature_key: Optional[str] = None, + tax_config: Optional["_models.TaxConfig"] = None, + discounts: Optional["_models.BillingDiscounts"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceWorkflowInvoicingSettingsReplaceUpdate(_Model): # pylint: disable=name-too-long + """InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing + settings of an invoice workflow. + + :ivar auto_advance: Whether to automatically issue the invoice after the draftPeriod has + passed. + :vartype auto_advance: bool + :ivar draft_period: The period for the invoice to be kept in draft status for manual reviews. + :vartype draft_period: str + :ivar due_after: The period after which the invoice is due. With some payment solutions it's + only applicable for manual collection method. + :vartype due_after: str + :ivar subscription_end_proration_mode: Controls how subscription-ending shortened service + periods are billed. Known values are: "bill_full_period" and "bill_actual_period". + :vartype subscription_end_proration_mode: str or + ~openmeter.models.BillingWorkflowInvoicingSubscriptionEndProrationMode + :ivar default_tax_config: Default tax configuration to apply to the invoices. + + Setting a tax code (``stripe.code`` / ``taxCodeId``) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and ``behavior`` remains + fully supported. + :vartype default_tax_config: ~openmeter._generated.models.TaxConfig + """ + + auto_advance: Optional[bool] = rest_field(name="autoAdvance", visibility=["read", "create", "update"]) + """Whether to automatically issue the invoice after the draftPeriod has passed.""" + draft_period: Optional[str] = rest_field(name="draftPeriod", visibility=["read", "create", "update"]) + """The period for the invoice to be kept in draft status for manual reviews.""" + due_after: Optional[str] = rest_field(name="dueAfter", visibility=["read", "create", "update"]) + """The period after which the invoice is due. With some payment solutions it's only applicable for + manual collection method.""" + subscription_end_proration_mode: Optional[ + Union[str, "_models.BillingWorkflowInvoicingSubscriptionEndProrationMode"] + ] = rest_field(name="subscriptionEndProrationMode", visibility=["read", "create", "update"]) + """Controls how subscription-ending shortened service periods are billed. Known values are: + \"bill_full_period\" and \"bill_actual_period\".""" + default_tax_config: Optional["_models.TaxConfig"] = rest_field( + name="defaultTaxConfig", visibility=["read", "create", "update"] + ) + """Default tax configuration to apply to the invoices. + + Setting a tax code (``stripe.code`` / ``taxCodeId``) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and ``behavior`` remains + fully supported.""" + + @overload + def __init__( + self, + *, + auto_advance: Optional[bool] = None, + draft_period: Optional[str] = None, + due_after: Optional[str] = None, + subscription_end_proration_mode: Optional[ + Union[str, "_models.BillingWorkflowInvoicingSubscriptionEndProrationMode"] + ] = None, + default_tax_config: Optional["_models.TaxConfig"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceWorkflowReplaceUpdate(_Model): + """InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. + + Fields that are immutable a re removed from the model. This is based on + InvoiceWorkflowSettings. + + :ivar workflow: The workflow used for this invoice. Required. + :vartype workflow: ~openmeter._generated.models.InvoiceWorkflowSettingsReplaceUpdate + """ + + workflow: "_models.InvoiceWorkflowSettingsReplaceUpdate" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The workflow used for this invoice. Required.""" + + @overload + def __init__( + self, + *, + workflow: "_models.InvoiceWorkflowSettingsReplaceUpdate", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceWorkflowSettings(_Model): + """InvoiceWorkflowSettings represents the workflow settings used by the invoice. + + This is a clone of the billing profile's workflow settings at the time of invoice creation + with customer overrides considered. + + :ivar apps: The apps that will be used to orchestrate the invoice's workflow. Is either a + BillingProfileApps type or a BillingProfileAppReferences type. + :vartype apps: ~openmeter._generated.models.BillingProfileApps or + ~openmeter._generated.models.BillingProfileAppReferences + :ivar source_billing_profile_id: sourceBillingProfileID is the billing profile on which the + workflow was based on. + + The profile is snapshotted on invoice creation, after which it can be altered independently + of the profile itself. Required. + :vartype source_billing_profile_id: str + :ivar workflow: The workflow details used by this invoice. Required. + :vartype workflow: ~openmeter._generated.models.BillingWorkflow + """ + + apps: Optional["_types.BillingProfileAppsOrReference"] = rest_field(visibility=["read"]) + """The apps that will be used to orchestrate the invoice's workflow. Is either a + BillingProfileApps type or a BillingProfileAppReferences type.""" + source_billing_profile_id: str = rest_field(name="sourceBillingProfileId", visibility=["read"]) + """sourceBillingProfileID is the billing profile on which the workflow was based on. + + The profile is snapshotted on invoice creation, after which it can be altered independently + of the profile itself. Required.""" + workflow: "_models.BillingWorkflow" = rest_field(visibility=["read", "create", "update"]) + """The workflow details used by this invoice. Required.""" + + @overload + def __init__( + self, + *, + workflow: "_models.BillingWorkflow", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class InvoiceWorkflowSettingsReplaceUpdate(_Model): + """Mutable workflow settings for an invoice. + + Other fields on the invoice's workflow are not mutable, they serve as a history of the + invoice's workflow + at creation time. + + :ivar invoicing: The invoicing settings for this workflow. Required. + :vartype invoicing: ~openmeter._generated.models.InvoiceWorkflowInvoicingSettingsReplaceUpdate + :ivar payment: The payment settings for this workflow. Required. + :vartype payment: ~openmeter._generated.models.BillingWorkflowPaymentSettings + """ + + invoicing: "_models.InvoiceWorkflowInvoicingSettingsReplaceUpdate" = rest_field(visibility=["update"]) + """The invoicing settings for this workflow. Required.""" + payment: "_models.BillingWorkflowPaymentSettings" = rest_field(visibility=["update"]) + """The payment settings for this workflow. Required.""" + + @overload + def __init__( + self, + *, + invoicing: "_models.InvoiceWorkflowInvoicingSettingsReplaceUpdate", + payment: "_models.BillingWorkflowPaymentSettings", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class IssueAfterReset(_Model): + """Issue after reset. + + :ivar amount: Initial grant amount. Required. + :vartype amount: float + :ivar priority: Issue grant after reset priority. + :vartype priority: int + """ + + amount: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Initial grant amount. Required.""" + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Issue grant after reset priority.""" + + @overload + def __init__( + self, + *, + amount: float, + priority: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListRequestFilter(_Model): + """ListRequestFilter. + + :ivar id: + :vartype id: ~openmeter._generated.models.FilterString + :ivar source: + :vartype source: ~openmeter._generated.models.FilterString + :ivar subject: + :vartype subject: ~openmeter._generated.models.FilterString + :ivar customer_id: + :vartype customer_id: ~openmeter._generated.models.FilterIDExact + :ivar type: + :vartype type: ~openmeter._generated.models.FilterString + :ivar time: + :vartype time: ~openmeter._generated.models.FilterTime + :ivar ingested_at: + :vartype ingested_at: ~openmeter._generated.models.FilterTime + """ + + id: Optional["_models.FilterString"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + source: Optional["_models.FilterString"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + subject: Optional["_models.FilterString"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + customer_id: Optional["_models.FilterIDExact"] = rest_field( + name="customerId", visibility=["read", "create", "update", "delete", "query"] + ) + type: Optional["_models.FilterString"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + time: Optional["_models.FilterTime"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + ingested_at: Optional["_models.FilterTime"] = rest_field( + name="ingestedAt", visibility=["read", "create", "update", "delete", "query"] + ) + + @overload + def __init__( + self, + *, + id: Optional["_models.FilterString"] = None, # pylint: disable=redefined-builtin + source: Optional["_models.FilterString"] = None, + subject: Optional["_models.FilterString"] = None, + customer_id: Optional["_models.FilterIDExact"] = None, + type: Optional["_models.FilterString"] = None, + time: Optional["_models.FilterTime"] = None, + ingested_at: Optional["_models.FilterTime"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MarketplaceInstallRequestPayload(_Model): + """Marketplace install request payload. + + :ivar name: Name of the application to install. + + If name is not provided defaults to the marketplace listing's name. + :vartype name: str + :ivar create_billing_profile: If true, a billing profile will be created for the app. The + Stripe app will be also set as the default billing profile if the current default is a Sandbox + app. + :vartype create_billing_profile: bool + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the application to install. + + If name is not provided defaults to the marketplace listing's name.""" + create_billing_profile: Optional[bool] = rest_field( + name="createBillingProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """If true, a billing profile will be created for the app. The Stripe app will be also set as the + default billing profile if the current default is a Sandbox app.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + create_billing_profile: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MarketplaceInstallResponse(_Model): + """Marketplace install response. + + :ivar app: Required. Is one of the following types: StripeApp, SandboxApp, CustomInvoicingApp + :vartype app: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp + or ~openmeter._generated.models.CustomInvoicingApp + :ivar default_for_capability_types: Default for capabilities. Required. + :vartype default_for_capability_types: list[str or ~openmeter.models.AppCapabilityType] + """ + + app: "_types.App" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. Is one of the following types: StripeApp, SandboxApp, CustomInvoicingApp""" + default_for_capability_types: list[Union[str, "_models.AppCapabilityType"]] = rest_field( + name="defaultForCapabilityTypes", visibility=["read", "create", "update", "delete", "query"] + ) + """Default for capabilities. Required.""" + + @overload + def __init__( + self, + *, + app: "_types.App", + default_for_capability_types: list[Union[str, "_models.AppCapabilityType"]], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MarketplaceListing(_Model): + """A marketplace listing. + Represent an available app in the app marketplace that can be installed to the organization. + + Marketplace apps only exist in config so they don't extend the Resource model. + + :ivar type: The app's type. Required. Known values are: "stripe", "sandbox", and + "custom_invoicing". + :vartype type: str or ~openmeter.models.AppType + :ivar name: The app's name. Required. + :vartype name: str + :ivar description: The app's description. Required. + :vartype description: str + :ivar capabilities: The app's capabilities. Required. + :vartype capabilities: list[~openmeter._generated.models.AppCapability] + :ivar install_methods: Install methods. + + List of methods to install the app. Required. + :vartype install_methods: list[str or ~openmeter.models.InstallMethod] + """ + + type: Union[str, "_models.AppType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type. Required. Known values are: \"stripe\", \"sandbox\", and \"custom_invoicing\".""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's name. Required.""" + description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's description. Required.""" + capabilities: list["_models.AppCapability"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's capabilities. Required.""" + install_methods: list[Union[str, "_models.InstallMethod"]] = rest_field( + name="installMethods", visibility=["read", "create", "update", "delete", "query"] + ) + """Install methods. + + List of methods to install the app. Required.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.AppType"], + name: str, + description: str, + capabilities: list["_models.AppCapability"], + install_methods: list[Union[str, "_models.InstallMethod"]], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MarketplaceListingPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.MarketplaceListing] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.MarketplaceListing"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.MarketplaceListing"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Metadata(_Model): + """Set of key-value pairs. Metadata can be used to store additional information about a resource.""" + + +class Meter(_Model): + """A meter is a configuration that defines how to match and aggregate events. + + :ivar id: ID. Required. + :vartype id: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar name: Display name. + :vartype name: str + :ivar slug: A unique, human-readable identifier for the meter. Must consist only alphanumeric + and underscore characters. Required. + :vartype slug: str + :ivar aggregation: The aggregation type to use for the meter. Required. Known values are: + "SUM", "COUNT", "UNIQUE_COUNT", "AVG", "MIN", "MAX", and "LATEST". + :vartype aggregation: str or ~openmeter.models.MeterAggregation + :ivar event_type: The event type to aggregate. Required. + :vartype event_type: str + :ivar event_from: The date since the meter should include events. Useful to skip old events. If + not specified, all historical events are included. + :vartype event_from: ~datetime.datetime + :ivar value_property: JSONPath expression to extract the value from the ingested event's data + property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be + parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the + valueProperty is ignored. + :vartype value_property: str + :ivar group_by: Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + :vartype group_by: dict[str, str] + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Display name.""" + slug: str = rest_field(visibility=["read", "create"]) + """A unique, human-readable identifier for the meter. Must consist only alphanumeric and + underscore characters. Required.""" + aggregation: Union[str, "_models.MeterAggregation"] = rest_field(visibility=["read", "create"]) + """The aggregation type to use for the meter. Required. Known values are: \"SUM\", \"COUNT\", + \"UNIQUE_COUNT\", \"AVG\", \"MIN\", \"MAX\", and \"LATEST\".""" + event_type: str = rest_field(name="eventType", visibility=["read", "create"]) + """The event type to aggregate. Required.""" + event_from: Optional[datetime.datetime] = rest_field( + name="eventFrom", visibility=["read", "create"], format="rfc3339" + ) + """The date since the meter should include events. Useful to skip old events. If not specified, + all historical events are included.""" + value_property: Optional[str] = rest_field(name="valueProperty", visibility=["read", "create"]) + """JSONPath expression to extract the value from the ingested event's data property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be + parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the + valueProperty is ignored.""" + group_by: Optional[dict[str, str]] = rest_field(name="groupBy", visibility=["read", "create", "update"]) + """Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + + @overload + def __init__( + self, + *, + slug: str, + aggregation: Union[str, "_models.MeterAggregation"], + event_type: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + name: Optional[str] = None, + event_from: Optional[datetime.datetime] = None, + value_property: Optional[str] = None, + group_by: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MeterCreate(_Model): + """A meter create model. + + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar name: Display name. + :vartype name: str + :ivar slug: A unique, human-readable identifier for the meter. Must consist only alphanumeric + and underscore characters. Required. + :vartype slug: str + :ivar aggregation: The aggregation type to use for the meter. Required. Known values are: + "SUM", "COUNT", "UNIQUE_COUNT", "AVG", "MIN", "MAX", and "LATEST". + :vartype aggregation: str or ~openmeter.models.MeterAggregation + :ivar event_type: The event type to aggregate. Required. + :vartype event_type: str + :ivar event_from: The date since the meter should include events. Useful to skip old events. If + not specified, all historical events are included. + :vartype event_from: ~datetime.datetime + :ivar value_property: JSONPath expression to extract the value from the ingested event's data + property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be + parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the + valueProperty is ignored. + :vartype value_property: str + :ivar group_by: Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + :vartype group_by: dict[str, str] + """ + + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name.""" + slug: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A unique, human-readable identifier for the meter. Must consist only alphanumeric and + underscore characters. Required.""" + aggregation: Union[str, "_models.MeterAggregation"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The aggregation type to use for the meter. Required. Known values are: \"SUM\", \"COUNT\", + \"UNIQUE_COUNT\", \"AVG\", \"MIN\", \"MAX\", and \"LATEST\".""" + event_type: str = rest_field(name="eventType", visibility=["read", "create", "update", "delete", "query"]) + """The event type to aggregate. Required.""" + event_from: Optional[datetime.datetime] = rest_field( + name="eventFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The date since the meter should include events. Useful to skip old events. If not specified, + all historical events are included.""" + value_property: Optional[str] = rest_field( + name="valueProperty", visibility=["read", "create", "update", "delete", "query"] + ) + """JSONPath expression to extract the value from the ingested event's data property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be + parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the + valueProperty is ignored.""" + group_by: Optional[dict[str, str]] = rest_field( + name="groupBy", visibility=["read", "create", "update", "delete", "query"] + ) + """Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters.""" + + @overload + def __init__( + self, + *, + slug: str, + aggregation: Union[str, "_models.MeterAggregation"], + event_type: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + name: Optional[str] = None, + event_from: Optional[datetime.datetime] = None, + value_property: Optional[str] = None, + group_by: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MeterQueryRequest(_Model): + """A meter query request. + + :ivar client_id: Client ID Useful to track progress of a query. + :vartype client_id: str + :ivar from_property: Start date-time in RFC 3339 format. + + Inclusive. + :vartype from_property: ~datetime.datetime + :ivar to: End date-time in RFC 3339 format. + + Inclusive. + :vartype to: ~datetime.datetime + :ivar window_size: If not specified, a single usage aggregate will be returned for the entirety + of the specified period for each subject and group. Known values are: "MINUTE", "HOUR", "DAY", + and "MONTH". + :vartype window_size: str or ~openmeter.models.WindowSize + :ivar window_time_zone: The value is the name of the time zone as defined in the IANA Time Zone + Database (`http://www.iana.org/time-zones `_). If not + specified, the UTC timezone will be used. + :vartype window_time_zone: str + :ivar subject: Filtering by multiple subjects. + :vartype subject: list[str] + :ivar filter_customer_id: Filtering by multiple customers. + :vartype filter_customer_id: list[str] + :ivar filter_group_by: Simple filter for group bys with exact match. + :vartype filter_group_by: dict[str, list[str]] + :ivar advanced_meter_group_by_filters: Optional advanced meter group by filters. You can use + this to filter for values of the meter groupBy fields. + :vartype advanced_meter_group_by_filters: dict[str, ~openmeter._generated.models.FilterString] + :ivar group_by: If not specified a single aggregate will be returned for each subject and time + window. ``subject`` is a reserved group by value. + :vartype group_by: list[str] + """ + + client_id: Optional[str] = rest_field(name="clientId", visibility=["read", "create", "update", "delete", "query"]) + """Client ID Useful to track progress of a query.""" + from_property: Optional[datetime.datetime] = rest_field( + name="from", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Start date-time in RFC 3339 format. + + Inclusive.""" + to: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """End date-time in RFC 3339 format. + + Inclusive.""" + window_size: Optional[Union[str, "_models.WindowSize"]] = rest_field( + name="windowSize", visibility=["read", "create", "update", "delete", "query"] + ) + """If not specified, a single usage aggregate will be returned for the entirety of the specified + period for each subject and group. Known values are: \"MINUTE\", \"HOUR\", \"DAY\", and + \"MONTH\".""" + window_time_zone: Optional[str] = rest_field( + name="windowTimeZone", visibility=["read", "create", "update", "delete", "query"] + ) + """The value is the name of the time zone as defined in the IANA Time Zone Database + (`http://www.iana.org/time-zones `_). If not specified, the UTC + timezone will be used.""" + subject: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Filtering by multiple subjects.""" + filter_customer_id: Optional[list[str]] = rest_field( + name="filterCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """Filtering by multiple customers.""" + filter_group_by: Optional[dict[str, list[str]]] = rest_field( + name="filterGroupBy", visibility=["read", "create", "update", "delete", "query"] + ) + """Simple filter for group bys with exact match.""" + advanced_meter_group_by_filters: Optional[dict[str, "_models.FilterString"]] = rest_field( + name="advancedMeterGroupByFilters", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional advanced meter group by filters. You can use this to filter for values of the meter + groupBy fields.""" + group_by: Optional[list[str]] = rest_field( + name="groupBy", visibility=["read", "create", "update", "delete", "query"] + ) + """If not specified a single aggregate will be returned for each subject and time window. + ``subject`` is a reserved group by value.""" + + @overload + def __init__( + self, + *, + client_id: Optional[str] = None, + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, "_models.WindowSize"]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[list[str]] = None, + filter_customer_id: Optional[list[str]] = None, + filter_group_by: Optional[dict[str, list[str]]] = None, + advanced_meter_group_by_filters: Optional[dict[str, "_models.FilterString"]] = None, + group_by: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MeterQueryResult(_Model): + """The result of a meter query. + + :ivar from_property: The start of the period the usage is queried from. If not specified, the + usage is queried from the beginning of time. + :vartype from_property: ~datetime.datetime + :ivar to: The end of the period the usage is queried to. If not specified, the usage is queried + up to the current time. + :vartype to: ~datetime.datetime + :ivar window_size: The window size that the usage is aggregated. If not specified, the usage is + aggregated over the entire period. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". + :vartype window_size: str or ~openmeter.models.WindowSize + :ivar data: The usage data. If no data is available, an empty array is returned. Required. + :vartype data: list[~openmeter._generated.models.MeterQueryRow] + """ + + from_property: Optional[datetime.datetime] = rest_field( + name="from", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start of the period the usage is queried from. If not specified, the usage is queried from + the beginning of time.""" + to: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end of the period the usage is queried to. If not specified, the usage is queried up to the + current time.""" + window_size: Optional[Union[str, "_models.WindowSize"]] = rest_field( + name="windowSize", visibility=["read", "create", "update", "delete", "query"] + ) + """The window size that the usage is aggregated. If not specified, the usage is aggregated over + the entire period. Known values are: \"MINUTE\", \"HOUR\", \"DAY\", and \"MONTH\".""" + data: list["_models.MeterQueryRow"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The usage data. If no data is available, an empty array is returned. Required.""" + + @overload + def __init__( + self, + *, + data: list["_models.MeterQueryRow"], + from_property: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, "_models.WindowSize"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MeterQueryRow(_Model): + """A row in the result of a meter query. + + :ivar value: The aggregated value. Required. + :vartype value: float + :ivar window_start: The start of the window the value is aggregated over. Required. + :vartype window_start: ~datetime.datetime + :ivar window_end: The end of the window the value is aggregated over. Required. + :vartype window_end: ~datetime.datetime + :ivar subject: The subject the value is aggregated over. If not specified, the value is + aggregated over all subjects. Required. + :vartype subject: str + :ivar customer_id: The customer ID the value is aggregated over. + :vartype customer_id: str + :ivar group_by: The group by values the value is aggregated over. Required. + :vartype group_by: dict[str, str] + """ + + value: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The aggregated value. Required.""" + window_start: datetime.datetime = rest_field( + name="windowStart", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start of the window the value is aggregated over. Required.""" + window_end: datetime.datetime = rest_field( + name="windowEnd", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end of the window the value is aggregated over. Required.""" + subject: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The subject the value is aggregated over. If not specified, the value is aggregated over all + subjects. Required.""" + customer_id: Optional[str] = rest_field( + name="customerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The customer ID the value is aggregated over.""" + group_by: dict[str, str] = rest_field(name="groupBy", visibility=["read", "create", "update", "delete", "query"]) + """The group by values the value is aggregated over. Required.""" + + @overload + def __init__( + self, + *, + value: float, + window_start: datetime.datetime, + window_end: datetime.datetime, + subject: str, + group_by: dict[str, str], + customer_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MeterUpdate(_Model): + """A meter update model. + + Only the properties that can be updated are included. + For example, the slug and aggregation cannot be updated. + + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar name: Display name. + :vartype name: str + :ivar group_by: Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + :vartype group_by: dict[str, str] + """ + + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """Display name.""" + group_by: Optional[dict[str, str]] = rest_field(name="groupBy", visibility=["read", "create", "update"]) + """Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters.""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + name: Optional[str] = None, + group_by: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MigrateRequest(_Model): + """MigrateRequest. + + :ivar timing: Timing configuration for the migration, when the migration should take effect. If + not supported by the subscription, 400 will be returned. Is either a Union[str, + "_models.SubscriptionTimingEnum"] type or a datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar target_version: The version of the plan to migrate to. If not provided, the subscription + will migrate to the latest version of the current plan. + :vartype target_version: int + :ivar starting_phase: The key of the phase to start the subscription in. If not provided, the + subscription will start in the first phase of the plan. + :vartype starting_phase: str + :ivar billing_anchor: The billing anchor of the subscription. The provided date will be + normalized according to the billing cadence to the nearest recurrence before start time. If not + provided, the previous subscription billing anchor will be used. + :vartype billing_anchor: ~datetime.datetime + """ + + timing: Optional["_types.SubscriptionTiming"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Timing configuration for the migration, when the migration should take effect. If not supported + by the subscription, 400 will be returned. Is either a Union[str, + \"_models.SubscriptionTimingEnum\"] type or a datetime.datetime type.""" + target_version: Optional[int] = rest_field( + name="targetVersion", visibility=["read", "create", "update", "delete", "query"] + ) + """The version of the plan to migrate to. If not provided, the subscription will migrate to the + latest version of the current plan.""" + starting_phase: Optional[str] = rest_field( + name="startingPhase", visibility=["read", "create", "update", "delete", "query"] + ) + """The key of the phase to start the subscription in. If not provided, the subscription will start + in the first phase of the plan.""" + billing_anchor: Optional[datetime.datetime] = rest_field( + name="billingAnchor", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The billing anchor of the subscription. The provided date will be normalized according to the + billing cadence to the nearest recurrence before start time. If not provided, the previous + subscription billing anchor will be used.""" + + @overload + def __init__( + self, + *, + timing: Optional["_types.SubscriptionTiming"] = None, + target_version: Optional[int] = None, + starting_phase: Optional[str] = None, + billing_anchor: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotFoundProblemResponse(UnexpectedProblemResponse): + """The origin server did not find a current representation for the target resource or is not + willing to disclose that one exists. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationChannelMeta(_Model): + """Metadata only fields of a notification channel. + + :ivar id: Channel Unique Identifier. Required. + :vartype id: str + :ivar type: Channel Type. Required. "WEBHOOK" + :vartype type: str or ~openmeter.models.NotificationChannelType + """ + + id: str = rest_field(visibility=["read"]) + """Channel Unique Identifier. Required.""" + type: Union[str, "_models.NotificationChannelType"] = rest_field(visibility=["read", "create"]) + """Channel Type. Required. \"WEBHOOK\"""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.NotificationChannelType"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationChannelPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.NotificationChannelWebhook] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_types.NotificationChannel"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_types.NotificationChannel"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationChannelWebhook(_Model): + """Notification channel with webhook type. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: Channel Unique Identifier. Required. + :vartype id: str + :ivar type: Channel Type. Required. WEBHOOK. + :vartype type: str or ~openmeter._generated.models.WEBHOOK + :ivar name: Channel Name. Required. + :vartype name: str + :ivar disabled: Channel Disabled. + :vartype disabled: bool + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar url: Webhook URL. Required. + :vartype url: str + :ivar custom_headers: Custom HTTP Headers. + :vartype custom_headers: dict[str, str] + :ivar signing_secret: Signing Secret. + :vartype signing_secret: str + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """Channel Unique Identifier. Required.""" + type: Literal[NotificationChannelType.WEBHOOK] = rest_field(visibility=["read", "create"]) + """Channel Type. Required. WEBHOOK.""" + name: str = rest_field(visibility=["read", "create", "update"]) + """Channel Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Channel Disabled.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + url: str = rest_field(visibility=["read", "create", "update"]) + """Webhook URL. Required.""" + custom_headers: Optional[dict[str, str]] = rest_field(name="customHeaders", visibility=["read", "create", "update"]) + """Custom HTTP Headers.""" + signing_secret: Optional[str] = rest_field(name="signingSecret", visibility=["read", "create", "update"]) + """Signing Secret.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationChannelType.WEBHOOK], + name: str, + url: str, + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + custom_headers: Optional[dict[str, str]] = None, + signing_secret: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationChannelWebhookCreateRequest(_Model): + """Request with input parameters for creating new notification channel with webhook type. + + :ivar type: Channel Type. Required. WEBHOOK. + :vartype type: str or ~openmeter._generated.models.WEBHOOK + :ivar name: Channel Name. Required. + :vartype name: str + :ivar disabled: Channel Disabled. + :vartype disabled: bool + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar url: Webhook URL. Required. + :vartype url: str + :ivar custom_headers: Custom HTTP Headers. + :vartype custom_headers: dict[str, str] + :ivar signing_secret: Signing Secret. + :vartype signing_secret: str + """ + + type: Literal[NotificationChannelType.WEBHOOK] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Channel Type. Required. WEBHOOK.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Channel Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Channel Disabled.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Webhook URL. Required.""" + custom_headers: Optional[dict[str, str]] = rest_field( + name="customHeaders", visibility=["read", "create", "update", "delete", "query"] + ) + """Custom HTTP Headers.""" + signing_secret: Optional[str] = rest_field( + name="signingSecret", visibility=["read", "create", "update", "delete", "query"] + ) + """Signing Secret.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationChannelType.WEBHOOK], + name: str, + url: str, + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + custom_headers: Optional[dict[str, str]] = None, + signing_secret: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationEvent(_Model): + """Type of the notification event. + + :ivar id: Event Identifier. Required. + :vartype id: str + :ivar type: Event Type. Required. Known values are: "entitlements.balance.threshold", + "entitlements.reset", "invoice.created", and "invoice.updated". + :vartype type: str or ~openmeter.models.NotificationEventType + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar rule: The nnotification rule which generated this event. Required. Is one of the + following types: NotificationRuleBalanceThreshold, NotificationRuleEntitlementReset, + NotificationRuleInvoiceCreated, NotificationRuleInvoiceUpdated + :vartype rule: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :ivar delivery_status: Delivery Status. Required. + :vartype delivery_status: list[~openmeter._generated.models.NotificationEventDeliveryStatus] + :ivar payload: Timestamp when the notification event was created in RFC 3339 format. Required. + Is one of the following types: NotificationEventResetPayload, + NotificationEventBalanceThresholdPayload, NotificationEventInvoiceCreatedPayload, + NotificationEventInvoiceUpdatedPayload + :vartype payload: ~openmeter._generated.models.NotificationEventResetPayload or + ~openmeter._generated.models.NotificationEventBalanceThresholdPayload or + ~openmeter._generated.models.NotificationEventInvoiceCreatedPayload or + ~openmeter._generated.models.NotificationEventInvoiceUpdatedPayload + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + """ + + id: str = rest_field(visibility=["read"]) + """Event Identifier. Required.""" + type: Union[str, "_models.NotificationEventType"] = rest_field(visibility=["read"]) + """Event Type. Required. Known values are: \"entitlements.balance.threshold\", + \"entitlements.reset\", \"invoice.created\", and \"invoice.updated\".""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + rule: "_types.NotificationRule" = rest_field(visibility=["read"]) + """The nnotification rule which generated this event. Required. Is one of the following types: + NotificationRuleBalanceThreshold, NotificationRuleEntitlementReset, + NotificationRuleInvoiceCreated, NotificationRuleInvoiceUpdated""" + delivery_status: list["_models.NotificationEventDeliveryStatus"] = rest_field( + name="deliveryStatus", visibility=["read"] + ) + """Delivery Status. Required.""" + payload: "_types.NotificationEventPayload" = rest_field(visibility=["read"]) + """Timestamp when the notification event was created in RFC 3339 format. Required. Is one of the + following types: NotificationEventResetPayload, NotificationEventBalanceThresholdPayload, + NotificationEventInvoiceCreatedPayload, NotificationEventInvoiceUpdatedPayload""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + + +class NotificationEventBalanceThresholdPayload(_Model): + """Payload for notification event with ``entitlements.balance.threshold`` type. + + :ivar id: Notification Event Identifier. Required. + :vartype id: str + :ivar type: Notification Event Type. Required. ENTITLEMENTS_BALANCE_THRESHOLD. + :vartype type: str or ~openmeter._generated.models.ENTITLEMENTS_BALANCE_THRESHOLD + :ivar timestamp: Creation Time. Required. + :vartype timestamp: ~datetime.datetime + :ivar data: Payload Data. Required. + :vartype data: ~openmeter._generated.models.NotificationEventBalanceThresholdPayloadData + """ + + id: str = rest_field(visibility=["read"]) + """Notification Event Identifier. Required.""" + type: Literal[NotificationEventType.ENTITLEMENTS_BALANCE_THRESHOLD] = rest_field(visibility=["read"]) + """Notification Event Type. Required. ENTITLEMENTS_BALANCE_THRESHOLD.""" + timestamp: datetime.datetime = rest_field(visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + data: "_models.NotificationEventBalanceThresholdPayloadData" = rest_field(visibility=["read"]) + """Payload Data. Required.""" + + +class NotificationEventBalanceThresholdPayloadData(_Model): # pylint: disable=name-too-long + """Data of the payload for notification event with ``entitlements.balance.threshold`` type. + + :ivar entitlement: Entitlement. Required. + :vartype entitlement: ~openmeter._generated.models.EntitlementMetered + :ivar feature: Feature. Required. + :vartype feature: ~openmeter._generated.models.Feature + :ivar subject: Subject. Required. + :vartype subject: ~openmeter._generated.models.Subject + :ivar value: Entitlement Value. Required. + :vartype value: ~openmeter._generated.models.EntitlementValue + :ivar customer: Customer. + :vartype customer: ~openmeter._generated.models.Customer + :ivar threshold: Threshold. Required. + :vartype threshold: ~openmeter._generated.models.NotificationRuleBalanceThresholdValue + """ + + entitlement: "_models.EntitlementMetered" = rest_field(visibility=["read"]) + """Entitlement. Required.""" + feature: "_models.Feature" = rest_field(visibility=["read"]) + """Feature. Required.""" + subject: "_models.Subject" = rest_field(visibility=["read"]) + """Subject. Required.""" + value: "_models.EntitlementValue" = rest_field(visibility=["read"]) + """Entitlement Value. Required.""" + customer: Optional["_models.Customer"] = rest_field(visibility=["read"]) + """Customer.""" + threshold: "_models.NotificationRuleBalanceThresholdValue" = rest_field(visibility=["read"]) + """Threshold. Required.""" + + +class NotificationEventDeliveryAttempt(_Model): + """The delivery attempt of the notification event. + + :ivar state: State of teh delivery attempt. Required. Known values are: "SUCCESS", "FAILED", + "SENDING", "PENDING", and "RESENDING". + :vartype state: str or ~openmeter.models.NotificationEventDeliveryStatusState + :ivar response: Response returned by the notification event recipient. Required. + :vartype response: ~openmeter._generated.models.EventDeliveryAttemptResponse + :ivar timestamp: Timestamp of the delivery attempt. Required. + :vartype timestamp: ~datetime.datetime + """ + + state: Union[str, "_models.NotificationEventDeliveryStatusState"] = rest_field(visibility=["read"]) + """State of teh delivery attempt. Required. Known values are: \"SUCCESS\", \"FAILED\", + \"SENDING\", \"PENDING\", and \"RESENDING\".""" + response: "_models.EventDeliveryAttemptResponse" = rest_field(visibility=["read"]) + """Response returned by the notification event recipient. Required.""" + timestamp: datetime.datetime = rest_field(visibility=["read"], format="rfc3339") + """Timestamp of the delivery attempt. Required.""" + + +class NotificationEventDeliveryStatus(_Model): + """The delivery status of the notification event. + + :ivar state: Delivery state of the notification event to the channel. Required. Known values + are: "SUCCESS", "FAILED", "SENDING", "PENDING", and "RESENDING". + :vartype state: str or ~openmeter.models.NotificationEventDeliveryStatusState + :ivar reason: State Reason. Required. + :vartype reason: str + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar channel: Notification Channel. Required. + :vartype channel: ~openmeter._generated.models.NotificationChannelMeta + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar next_attempt: Timestamp of the next delivery attempt. + :vartype next_attempt: ~datetime.datetime + :ivar attempts: Delivery Attempts. Required. + :vartype attempts: list[~openmeter._generated.models.NotificationEventDeliveryAttempt] + """ + + state: Union[str, "_models.NotificationEventDeliveryStatusState"] = rest_field(visibility=["read"]) + """Delivery state of the notification event to the channel. Required. Known values are: + \"SUCCESS\", \"FAILED\", \"SENDING\", \"PENDING\", and \"RESENDING\".""" + reason: str = rest_field(visibility=["read"]) + """State Reason. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + channel: "_models.NotificationChannelMeta" = rest_field(visibility=["read"]) + """Notification Channel. Required.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + next_attempt: Optional[datetime.datetime] = rest_field(name="nextAttempt", visibility=["read"], format="rfc3339") + """Timestamp of the next delivery attempt.""" + attempts: list["_models.NotificationEventDeliveryAttempt"] = rest_field(visibility=["read"]) + """Delivery Attempts. Required.""" + + +class NotificationEventEntitlementValuePayloadBase(_Model): # pylint: disable=name-too-long + """Base data for any payload with entitlement entitlement value. + + :ivar entitlement: Entitlement. Required. + :vartype entitlement: ~openmeter._generated.models.EntitlementMetered + :ivar feature: Feature. Required. + :vartype feature: ~openmeter._generated.models.Feature + :ivar subject: Subject. Required. + :vartype subject: ~openmeter._generated.models.Subject + :ivar value: Entitlement Value. Required. + :vartype value: ~openmeter._generated.models.EntitlementValue + :ivar customer: Customer. + :vartype customer: ~openmeter._generated.models.Customer + """ + + entitlement: "_models.EntitlementMetered" = rest_field(visibility=["read"]) + """Entitlement. Required.""" + feature: "_models.Feature" = rest_field(visibility=["read"]) + """Feature. Required.""" + subject: "_models.Subject" = rest_field(visibility=["read"]) + """Subject. Required.""" + value: "_models.EntitlementValue" = rest_field(visibility=["read"]) + """Entitlement Value. Required.""" + customer: Optional["_models.Customer"] = rest_field(visibility=["read"]) + """Customer.""" + + +class NotificationEventInvoiceCreatedPayload(_Model): + """Payload for notification event with ``invoice.created`` type. + + :ivar id: Notification Event Identifier. Required. + :vartype id: str + :ivar type: Notification Event Type. Required. INVOICE_CREATED. + :vartype type: str or ~openmeter._generated.models.INVOICE_CREATED + :ivar timestamp: Creation Time. Required. + :vartype timestamp: ~datetime.datetime + :ivar data: Payload Data. Required. + :vartype data: ~openmeter._generated.models.Invoice + """ + + id: str = rest_field(visibility=["read"]) + """Notification Event Identifier. Required.""" + type: Literal[NotificationEventType.INVOICE_CREATED] = rest_field(visibility=["read"]) + """Notification Event Type. Required. INVOICE_CREATED.""" + timestamp: datetime.datetime = rest_field(visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + data: "_models.Invoice" = rest_field(visibility=["read"]) + """Payload Data. Required.""" + + +class NotificationEventInvoiceUpdatedPayload(_Model): + """Payload for notification event with ``invoice.updated`` type. + + :ivar id: Notification Event Identifier. Required. + :vartype id: str + :ivar type: Notification Event Type. Required. INVOICE_UPDATED. + :vartype type: str or ~openmeter._generated.models.INVOICE_UPDATED + :ivar timestamp: Creation Time. Required. + :vartype timestamp: ~datetime.datetime + :ivar data: Payload Data. Required. + :vartype data: ~openmeter._generated.models.Invoice + """ + + id: str = rest_field(visibility=["read"]) + """Notification Event Identifier. Required.""" + type: Literal[NotificationEventType.INVOICE_UPDATED] = rest_field(visibility=["read"]) + """Notification Event Type. Required. INVOICE_UPDATED.""" + timestamp: datetime.datetime = rest_field(visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + data: "_models.Invoice" = rest_field(visibility=["read"]) + """Payload Data. Required.""" + + +class NotificationEventPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.NotificationEvent] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.NotificationEvent"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.NotificationEvent"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationEventResendRequest(_Model): + """A notification event that will be re-sent. + + :ivar channels: Channels. + :vartype channels: list[str] + """ + + channels: Optional[list[str]] = rest_field(visibility=["create"]) + """Channels.""" + + @overload + def __init__( + self, + *, + channels: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationEventResetPayload(_Model): + """Payload for notification event with ``entitlements.reset`` type. + + :ivar id: Notification Event Identifier. Required. + :vartype id: str + :ivar type: Notification Event Type. Required. ENTITLEMENTS_RESET. + :vartype type: str or ~openmeter._generated.models.ENTITLEMENTS_RESET + :ivar timestamp: Creation Time. Required. + :vartype timestamp: ~datetime.datetime + :ivar data: Payload Data. Required. + :vartype data: ~openmeter._generated.models.NotificationEventEntitlementValuePayloadBase + """ + + id: str = rest_field(visibility=["read"]) + """Notification Event Identifier. Required.""" + type: Literal[NotificationEventType.ENTITLEMENTS_RESET] = rest_field(visibility=["read"]) + """Notification Event Type. Required. ENTITLEMENTS_RESET.""" + timestamp: datetime.datetime = rest_field(visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + data: "_models.NotificationEventEntitlementValuePayloadBase" = rest_field(visibility=["read"]) + """Payload Data. Required.""" + + +class NotificationRuleBalanceThreshold(_Model): + """Notification rule with entitlements.balance.threshold type. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: Rule Unique Identifier. Required. + :vartype id: str + :ivar type: Rule Type. Required. ENTITLEMENTS_BALANCE_THRESHOLD. + :vartype type: str or ~openmeter._generated.models.ENTITLEMENTS_BALANCE_THRESHOLD + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar channels: Channels assigned to Rule. Required. + :vartype channels: list[~openmeter._generated.models.NotificationChannelMeta] + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar thresholds: Entitlement Balance Thresholds. Required. + :vartype thresholds: list[~openmeter._generated.models.NotificationRuleBalanceThresholdValue] + :ivar features: Features. + :vartype features: list[~openmeter._generated.models.FeatureMeta] + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """Rule Unique Identifier. Required.""" + type: Literal[NotificationEventType.ENTITLEMENTS_BALANCE_THRESHOLD] = rest_field( + visibility=["read", "create", "update"] + ) + """Rule Type. Required. ENTITLEMENTS_BALANCE_THRESHOLD.""" + name: str = rest_field(visibility=["read", "create", "update"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Rule Disabled.""" + channels: list["_models.NotificationChannelMeta"] = rest_field(visibility=["read", "create", "update"]) + """Channels assigned to Rule. Required.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + thresholds: list["_models.NotificationRuleBalanceThresholdValue"] = rest_field( + visibility=["read", "create", "update"] + ) + """Entitlement Balance Thresholds. Required.""" + features: Optional[list["_models.FeatureMeta"]] = rest_field(visibility=["read", "create", "update"]) + """Features.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.ENTITLEMENTS_BALANCE_THRESHOLD], + name: str, + channels: list["_models.NotificationChannelMeta"], + thresholds: list["_models.NotificationRuleBalanceThresholdValue"], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + features: Optional[list["_models.FeatureMeta"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleBalanceThresholdCreateRequest(_Model): # pylint: disable=name-too-long + """Request with input parameters for creating new notification rule with + entitlements.balance.threshold type. + + :ivar type: Rule Type. Required. ENTITLEMENTS_BALANCE_THRESHOLD. + :vartype type: str or ~openmeter._generated.models.ENTITLEMENTS_BALANCE_THRESHOLD + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar thresholds: Entitlement Balance Thresholds. Required. + :vartype thresholds: list[~openmeter._generated.models.NotificationRuleBalanceThresholdValue] + :ivar channels: Channels. Required. + :vartype channels: list[str] + :ivar features: Features. + :vartype features: list[str] + """ + + type: Literal[NotificationEventType.ENTITLEMENTS_BALANCE_THRESHOLD] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Rule Type. Required. ENTITLEMENTS_BALANCE_THRESHOLD.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Disabled.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + thresholds: list["_models.NotificationRuleBalanceThresholdValue"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Entitlement Balance Thresholds. Required.""" + channels: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Channels. Required.""" + features: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Features.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.ENTITLEMENTS_BALANCE_THRESHOLD], + name: str, + thresholds: list["_models.NotificationRuleBalanceThresholdValue"], + channels: list[str], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + features: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleBalanceThresholdValue(_Model): + """Threshold value with multiple supported types. + + :ivar value: Threshold Value. Required. + :vartype value: float + :ivar type: Type of the threshold. Required. Known values are: "PERCENT", "NUMBER", + "balance_value", "usage_percentage", and "usage_value". + :vartype type: str or ~openmeter.models.NotificationRuleBalanceThresholdValueType + """ + + value: float = rest_field(visibility=["read", "create", "update"]) + """Threshold Value. Required.""" + type: Union[str, "_models.NotificationRuleBalanceThresholdValueType"] = rest_field( + visibility=["read", "create", "update"] + ) + """Type of the threshold. Required. Known values are: \"PERCENT\", \"NUMBER\", \"balance_value\", + \"usage_percentage\", and \"usage_value\".""" + + @overload + def __init__( + self, + *, + value: float, + type: Union[str, "_models.NotificationRuleBalanceThresholdValueType"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleEntitlementReset(_Model): + """Notification rule with entitlements.reset type. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: Rule Unique Identifier. Required. + :vartype id: str + :ivar type: Rule Type. Required. ENTITLEMENTS_RESET. + :vartype type: str or ~openmeter._generated.models.ENTITLEMENTS_RESET + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar channels: Channels assigned to Rule. Required. + :vartype channels: list[~openmeter._generated.models.NotificationChannelMeta] + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar features: Features. + :vartype features: list[~openmeter._generated.models.FeatureMeta] + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """Rule Unique Identifier. Required.""" + type: Literal[NotificationEventType.ENTITLEMENTS_RESET] = rest_field(visibility=["read", "create", "update"]) + """Rule Type. Required. ENTITLEMENTS_RESET.""" + name: str = rest_field(visibility=["read", "create", "update"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Rule Disabled.""" + channels: list["_models.NotificationChannelMeta"] = rest_field(visibility=["read", "create", "update"]) + """Channels assigned to Rule. Required.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + features: Optional[list["_models.FeatureMeta"]] = rest_field(visibility=["read", "create", "update"]) + """Features.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.ENTITLEMENTS_RESET], + name: str, + channels: list["_models.NotificationChannelMeta"], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + features: Optional[list["_models.FeatureMeta"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleEntitlementResetCreateRequest(_Model): # pylint: disable=name-too-long + """Request with input parameters for creating new notification rule with entitlements.reset type. + + :ivar type: Rule Type. Required. ENTITLEMENTS_RESET. + :vartype type: str or ~openmeter._generated.models.ENTITLEMENTS_RESET + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar channels: Channels. Required. + :vartype channels: list[str] + :ivar features: Features. + :vartype features: list[str] + """ + + type: Literal[NotificationEventType.ENTITLEMENTS_RESET] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Rule Type. Required. ENTITLEMENTS_RESET.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Disabled.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + channels: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Channels. Required.""" + features: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Features.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.ENTITLEMENTS_RESET], + name: str, + channels: list[str], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + features: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleInvoiceCreated(_Model): + """Notification rule with invoice.created type. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: Rule Unique Identifier. Required. + :vartype id: str + :ivar type: Rule Type. Required. INVOICE_CREATED. + :vartype type: str or ~openmeter._generated.models.INVOICE_CREATED + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar channels: Channels assigned to Rule. Required. + :vartype channels: list[~openmeter._generated.models.NotificationChannelMeta] + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """Rule Unique Identifier. Required.""" + type: Literal[NotificationEventType.INVOICE_CREATED] = rest_field(visibility=["read", "create", "update"]) + """Rule Type. Required. INVOICE_CREATED.""" + name: str = rest_field(visibility=["read", "create", "update"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Rule Disabled.""" + channels: list["_models.NotificationChannelMeta"] = rest_field(visibility=["read", "create", "update"]) + """Channels assigned to Rule. Required.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.INVOICE_CREATED], + name: str, + channels: list["_models.NotificationChannelMeta"], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleInvoiceCreatedCreateRequest(_Model): # pylint: disable=name-too-long + """Request with input parameters for creating new notification rule with invoice.created type. + + :ivar type: Rule Type. Required. INVOICE_CREATED. + :vartype type: str or ~openmeter._generated.models.INVOICE_CREATED + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar channels: Channels. Required. + :vartype channels: list[str] + """ + + type: Literal[NotificationEventType.INVOICE_CREATED] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Rule Type. Required. INVOICE_CREATED.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Disabled.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + channels: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Channels. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.INVOICE_CREATED], + name: str, + channels: list[str], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleInvoiceUpdated(_Model): + """Notification rule with invoice.updated type. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: Rule Unique Identifier. Required. + :vartype id: str + :ivar type: Rule Type. Required. INVOICE_UPDATED. + :vartype type: str or ~openmeter._generated.models.INVOICE_UPDATED + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar channels: Channels assigned to Rule. Required. + :vartype channels: list[~openmeter._generated.models.NotificationChannelMeta] + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """Rule Unique Identifier. Required.""" + type: Literal[NotificationEventType.INVOICE_UPDATED] = rest_field(visibility=["read", "create", "update"]) + """Rule Type. Required. INVOICE_UPDATED.""" + name: str = rest_field(visibility=["read", "create", "update"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update"]) + """Rule Disabled.""" + channels: list["_models.NotificationChannelMeta"] = rest_field(visibility=["read", "create", "update"]) + """Channels assigned to Rule. Required.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.INVOICE_UPDATED], + name: str, + channels: list["_models.NotificationChannelMeta"], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRuleInvoiceUpdatedCreateRequest(_Model): # pylint: disable=name-too-long + """Request with input parameters for creating new notification rule with invoice.updated type. + + :ivar type: Rule Type. Required. INVOICE_UPDATED. + :vartype type: str or ~openmeter._generated.models.INVOICE_UPDATED + :ivar name: Rule Name. Required. + :vartype name: str + :ivar disabled: Rule Disabled. + :vartype disabled: bool + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar channels: Channels. Required. + :vartype channels: list[str] + """ + + type: Literal[NotificationEventType.INVOICE_UPDATED] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Rule Type. Required. INVOICE_UPDATED.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Name. Required.""" + disabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Rule Disabled.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + channels: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Channels. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[NotificationEventType.INVOICE_UPDATED], + name: str, + channels: list[str], + disabled: Optional[bool] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class NotificationRulePaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_types.NotificationRule"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_types.NotificationRule"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PackagePriceWithCommitments(_Model): + """Package price with spend commitments. + + :ivar type: The type of the price. Required. PACKAGE. + :vartype type: str or ~openmeter._generated.models.PACKAGE + :ivar amount: Amount. Required. + :vartype amount: str + :ivar quantity_per_package: Quantity per package. Required. + :vartype quantity_per_package: str + :ivar minimum_amount: Minimum amount. + :vartype minimum_amount: str + :ivar maximum_amount: Maximum amount. + :vartype maximum_amount: str + """ + + type: Literal[PriceType.PACKAGE] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. Required. PACKAGE.""" + amount: str = rest_field(visibility=["read", "create", "update"]) + """Amount. Required.""" + quantity_per_package: str = rest_field(name="quantityPerPackage", visibility=["read", "create", "update"]) + """Quantity per package. Required.""" + minimum_amount: Optional[str] = rest_field(name="minimumAmount", visibility=["read", "create", "update"]) + """Minimum amount.""" + maximum_amount: Optional[str] = rest_field(name="maximumAmount", visibility=["read", "create", "update"]) + """Maximum amount.""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.PACKAGE], + amount: str, + quantity_per_package: str, + minimum_amount: Optional[str] = None, + maximum_amount: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PaymentDueDate(_Model): + """PaymentDueDate contains an amount that should be paid by the given date. + + :ivar due_at: When the payment is due. Required. + :vartype due_at: ~datetime.datetime + :ivar notes: Other details to take into account for the due date. + :vartype notes: str + :ivar amount: How much needs to be paid by the date. Required. + :vartype amount: str + :ivar percent: Percentage of the total that should be paid by the date. + :vartype percent: float + :ivar currency: If different from the parent document's base currency. + :vartype currency: str + """ + + due_at: datetime.datetime = rest_field(name="dueAt", visibility=["read"], format="rfc3339") + """When the payment is due. Required.""" + notes: Optional[str] = rest_field(visibility=["read"]) + """Other details to take into account for the due date.""" + amount: str = rest_field(visibility=["read"]) + """How much needs to be paid by the date. Required.""" + percent: Optional[float] = rest_field(visibility=["read"]) + """Percentage of the total that should be paid by the date.""" + currency: Optional[str] = rest_field(visibility=["read"]) + """If different from the parent document's base currency.""" + + +class PaymentTermDueDate(_Model): + """PaymentTermDueDate defines the terms for payment on a specific date. + + :ivar type: Type of terms to be applied. Required. Due on a specific date. + :vartype type: str or ~openmeter._generated.models.DUE_DATE + :ivar detail: Text detail of the chosen payment terms. + :vartype detail: str + :ivar notes: Description of the conditions for payment. + :vartype notes: str + :ivar due_at: When the payment is due. Required. + :vartype due_at: list[~openmeter._generated.models.PaymentDueDate] + """ + + type: Literal[PaymentTermType.DUE_DATE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type of terms to be applied. Required. Due on a specific date.""" + detail: Optional[str] = rest_field(visibility=["read"]) + """Text detail of the chosen payment terms.""" + notes: Optional[str] = rest_field(visibility=["read"]) + """Description of the conditions for payment.""" + due_at: list["_models.PaymentDueDate"] = rest_field(name="dueAt", visibility=["read"]) + """When the payment is due. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[PaymentTermType.DUE_DATE], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PaymentTermInstant(_Model): + """PaymentTermInstant defines the terms for payment on receipt of invoice. + + :ivar type: Type of terms to be applied. Required. On receipt of invoice. + :vartype type: str or ~openmeter._generated.models.INSTANT + :ivar detail: Text detail of the chosen payment terms. + :vartype detail: str + :ivar notes: Description of the conditions for payment. + :vartype notes: str + """ + + type: Literal[PaymentTermType.INSTANT] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type of terms to be applied. Required. On receipt of invoice.""" + detail: Optional[str] = rest_field(visibility=["read"]) + """Text detail of the chosen payment terms.""" + notes: Optional[str] = rest_field(visibility=["read"]) + """Description of the conditions for payment.""" + + @overload + def __init__( + self, + *, + type: Literal[PaymentTermType.INSTANT], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Period(_Model): + """A period with a start and end time. + + :ivar from_property: Period start time. Required. + :vartype from_property: ~datetime.datetime + :ivar to: Period end time. Required. + :vartype to: ~datetime.datetime + """ + + from_property: datetime.datetime = rest_field( + name="from", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Period start time. Required.""" + to: datetime.datetime = rest_field(visibility=["read", "create", "update", "delete", "query"], format="rfc3339") + """Period end time. Required.""" + + @overload + def __init__( + self, + *, + from_property: datetime.datetime, + to: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Plan(_Model): + """Plans provide a template for subscriptions. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar key: Key. Required. + :vartype key: str + :ivar alignment: Alignment configuration for the plan. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar version: Version. Required. + :vartype version: int + :ivar currency: Currency. Required. + :vartype currency: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar effective_from: Effective start date. + :vartype effective_from: ~datetime.datetime + :ivar effective_to: Effective end date. + :vartype effective_to: ~datetime.datetime + :ivar status: Status. Required. Known values are: "draft", "active", "archived", and + "scheduled". + :vartype status: str or ~openmeter.models.PlanStatus + :ivar settlement_mode: Settlement mode. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar phases: Plan phases. Required. + :vartype phases: list[~openmeter._generated.models.PlanPhase] + :ivar validation_errors: Validation errors. Required. + :vartype validation_errors: list[~openmeter._generated.models.ValidationError] + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + key: str = rest_field(visibility=["read", "create"]) + """Key. Required.""" + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Alignment configuration for the plan.""" + version: int = rest_field(visibility=["read"]) + """Version. Required.""" + currency: str = rest_field(visibility=["read", "create"]) + """Currency. Required.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read", "create", "update"]) + """Billing cadence. Required.""" + pro_rating_config: Optional["_models.ProRatingConfig"] = rest_field( + name="proRatingConfig", visibility=["read", "create", "update"] + ) + """Pro-rating configuration.""" + effective_from: Optional[datetime.datetime] = rest_field( + name="effectiveFrom", visibility=["read"], format="rfc3339" + ) + """Effective start date.""" + effective_to: Optional[datetime.datetime] = rest_field(name="effectiveTo", visibility=["read"], format="rfc3339") + """Effective end date.""" + status: Union[str, "_models.PlanStatus"] = rest_field(visibility=["read"]) + """Status. Required. Known values are: \"draft\", \"active\", \"archived\", and \"scheduled\".""" + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = rest_field( + name="settlementMode", visibility=["read", "create", "update"] + ) + """Settlement mode. Known values are: \"credit_then_invoice\" and \"credit_only\".""" + phases: list["_models.PlanPhase"] = rest_field(visibility=["read", "create", "update"]) + """Plan phases. Required.""" + validation_errors: list["_models.ValidationError"] = rest_field(name="validationErrors", visibility=["read"]) + """Validation errors. Required.""" + + @overload + def __init__( + self, + *, + name: str, + key: str, + currency: str, + billing_cadence: datetime.timedelta, + phases: list["_models.PlanPhase"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + alignment: Optional["_models.Alignment"] = None, + pro_rating_config: Optional["_models.ProRatingConfig"] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanAddon(_Model): + """The PlanAddon describes the association between a plan and add-on. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar addon: Addon. Required. + :vartype addon: ~openmeter._generated.models.Addon + :ivar from_plan_phase: The plan phase from the add-on becomes purchasable. Required. + :vartype from_plan_phase: str + :ivar max_quantity: Max quantity of the add-on. + :vartype max_quantity: int + :ivar validation_errors: Validation errors. Required. + :vartype validation_errors: list[~openmeter._generated.models.ValidationError] + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + addon: "_models.Addon" = rest_field(visibility=["read"]) + """Addon. Required.""" + from_plan_phase: str = rest_field(name="fromPlanPhase", visibility=["read", "create", "update"]) + """The plan phase from the add-on becomes purchasable. Required.""" + max_quantity: Optional[int] = rest_field(name="maxQuantity", visibility=["read", "create", "update"]) + """Max quantity of the add-on.""" + validation_errors: list["_models.ValidationError"] = rest_field(name="validationErrors", visibility=["read"]) + """Validation errors. Required.""" + + @overload + def __init__( + self, + *, + from_plan_phase: str, + metadata: Optional["_models.Metadata"] = None, + max_quantity: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanAddonCreate(_Model): + """A plan add-on assignment create request. + + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar from_plan_phase: The plan phase from the add-on becomes purchasable. Required. + :vartype from_plan_phase: str + :ivar max_quantity: Max quantity of the add-on. + :vartype max_quantity: int + :ivar addon_id: Add-on unique identifier. Required. + :vartype addon_id: str + """ + + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + from_plan_phase: str = rest_field(name="fromPlanPhase", visibility=["read", "create", "update", "delete", "query"]) + """The plan phase from the add-on becomes purchasable. Required.""" + max_quantity: Optional[int] = rest_field( + name="maxQuantity", visibility=["read", "create", "update", "delete", "query"] + ) + """Max quantity of the add-on.""" + addon_id: str = rest_field(name="addonId", visibility=["read", "create", "update", "delete", "query"]) + """Add-on unique identifier. Required.""" + + @overload + def __init__( + self, + *, + from_plan_phase: str, + addon_id: str, + metadata: Optional["_models.Metadata"] = None, + max_quantity: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanAddonPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.PlanAddon] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.PlanAddon"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.PlanAddon"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanAddonReplaceUpdate(_Model): + """Resource update operation model. + + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar from_plan_phase: The plan phase from the add-on becomes purchasable. Required. + :vartype from_plan_phase: str + :ivar max_quantity: Max quantity of the add-on. + :vartype max_quantity: int + """ + + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update"]) + """Metadata.""" + from_plan_phase: str = rest_field(name="fromPlanPhase", visibility=["read", "create", "update"]) + """The plan phase from the add-on becomes purchasable. Required.""" + max_quantity: Optional[int] = rest_field(name="maxQuantity", visibility=["read", "create", "update"]) + """Max quantity of the add-on.""" + + @overload + def __init__( + self, + *, + from_plan_phase: str, + metadata: Optional["_models.Metadata"] = None, + max_quantity: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanCreate(_Model): + """Resource create operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar key: Key. Required. + :vartype key: str + :ivar alignment: Alignment configuration for the plan. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar currency: Currency. Required. + :vartype currency: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar settlement_mode: Settlement mode. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar phases: Plan phases. Required. + :vartype phases: list[~openmeter._generated.models.PlanPhase] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Key. Required.""" + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Alignment configuration for the plan.""" + currency: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency. Required.""" + billing_cadence: datetime.timedelta = rest_field( + name="billingCadence", visibility=["read", "create", "update", "delete", "query"] + ) + """Billing cadence. Required.""" + pro_rating_config: Optional["_models.ProRatingConfig"] = rest_field( + name="proRatingConfig", visibility=["read", "create", "update", "delete", "query"] + ) + """Pro-rating configuration.""" + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = rest_field( + name="settlementMode", visibility=["read", "create", "update", "delete", "query"] + ) + """Settlement mode. Known values are: \"credit_then_invoice\" and \"credit_only\".""" + phases: list["_models.PlanPhase"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Plan phases. Required.""" + + @overload + def __init__( + self, + *, + name: str, + key: str, + currency: str, + billing_cadence: datetime.timedelta, + phases: list["_models.PlanPhase"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + alignment: Optional["_models.Alignment"] = None, + pro_rating_config: Optional["_models.ProRatingConfig"] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanPhase(_Model): + """The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription + progresses. + + :ivar key: Key. Required. + :vartype key: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar duration: Duration. Required. + :vartype duration: ~datetime.timedelta + :ivar rate_cards: Rate cards. Required. + :vartype rate_cards: list[~openmeter._generated.models.RateCardFlatFee or + ~openmeter._generated.models.RateCardUsageBased] + """ + + key: str = rest_field(visibility=["read", "create"]) + """Key. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + duration: datetime.timedelta = rest_field(visibility=["read", "create", "update"]) + """Duration. Required.""" + rate_cards: list["_types.RateCard"] = rest_field(name="rateCards", visibility=["read", "create", "update"]) + """Rate cards. Required.""" + + @overload + def __init__( + self, + *, + key: str, + name: str, + duration: datetime.timedelta, + rate_cards: list["_types.RateCard"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanReference(_Model): + """References an exact plan. + + :ivar id: The plan ID. Required. + :vartype id: str + :ivar key: The plan key. Required. + :vartype key: str + :ivar version: The plan version. Required. + :vartype version: int + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan ID. Required.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan key. Required.""" + version: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan version. Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + key: str, + version: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanReferenceInput(_Model): + """References an exact plan defaulting to the current active version. + + :ivar key: The plan key. Required. + :vartype key: str + :ivar version: The plan version. + :vartype version: int + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan key. Required.""" + version: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan version.""" + + @overload + def __init__( + self, + *, + key: str, + version: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanReplaceUpdate(_Model): + """Resource update operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar alignment: Alignment configuration for the plan. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar settlement_mode: Settlement mode. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar phases: Plan phases. Required. + :vartype phases: list[~openmeter._generated.models.PlanPhase] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Alignment configuration for the plan.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read", "create", "update"]) + """Billing cadence. Required.""" + pro_rating_config: Optional["_models.ProRatingConfig"] = rest_field( + name="proRatingConfig", visibility=["read", "create", "update"] + ) + """Pro-rating configuration.""" + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = rest_field( + name="settlementMode", visibility=["read", "create", "update"] + ) + """Settlement mode. Known values are: \"credit_then_invoice\" and \"credit_only\".""" + phases: list["_models.PlanPhase"] = rest_field(visibility=["read", "create", "update"]) + """Plan phases. Required.""" + + @overload + def __init__( + self, + *, + name: str, + billing_cadence: datetime.timedelta, + phases: list["_models.PlanPhase"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + alignment: Optional["_models.Alignment"] = None, + pro_rating_config: Optional["_models.ProRatingConfig"] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanSubscriptionChange(_Model): + """Change subscription based on plan. + + :ivar timing: Timing configuration for the change, when the change should take effect. For + changing a subscription, the accepted values depend on the subscription configuration. + Required. Is either a Union[str, "_models.SubscriptionTimingEnum"] type or a datetime.datetime + type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar alignment: What alignment settings the subscription should have. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar metadata: Arbitrary metadata associated with the subscription. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar plan: The plan reference to change to. Required. + :vartype plan: ~openmeter._generated.models.PlanReferenceInput + :ivar starting_phase: The key of the phase to start the subscription in. If not provided, the + subscription will start in the first phase of the plan. + :vartype starting_phase: str + :ivar name: The name of the Subscription. If not provided the plan name is used. + :vartype name: str + :ivar description: Description for the Subscription. + :vartype description: str + :ivar billing_anchor: The billing anchor of the subscription. The provided date will be + normalized according to the billing cadence to the nearest recurrence before start time. If not + provided, the previous subscription billing anchor will be used. + :vartype billing_anchor: ~datetime.datetime + :ivar settlement_mode: The settlement mode of the subscription. Known values are: + "credit_then_invoice" and "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + """ + + timing: "_types.SubscriptionTiming" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Timing configuration for the change, when the change should take effect. For changing a + subscription, the accepted values depend on the subscription configuration. Required. Is either + a Union[str, \"_models.SubscriptionTimingEnum\"] type or a datetime.datetime type.""" + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """What alignment settings the subscription should have.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Arbitrary metadata associated with the subscription.""" + plan: "_models.PlanReferenceInput" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan reference to change to. Required.""" + starting_phase: Optional[str] = rest_field( + name="startingPhase", visibility=["read", "create", "update", "delete", "query"] + ) + """The key of the phase to start the subscription in. If not provided, the subscription will start + in the first phase of the plan.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the Subscription. If not provided the plan name is used.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description for the Subscription.""" + billing_anchor: Optional[datetime.datetime] = rest_field( + name="billingAnchor", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The billing anchor of the subscription. The provided date will be normalized according to the + billing cadence to the nearest recurrence before start time. If not provided, the previous + subscription billing anchor will be used.""" + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = rest_field( + name="settlementMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The settlement mode of the subscription. Known values are: \"credit_then_invoice\" and + \"credit_only\".""" + + @overload + def __init__( + self, + *, + timing: "_types.SubscriptionTiming", + plan: "_models.PlanReferenceInput", + alignment: Optional["_models.Alignment"] = None, + metadata: Optional["_models.Metadata"] = None, + starting_phase: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + billing_anchor: Optional[datetime.datetime] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PlanSubscriptionCreate(_Model): + """Create from plan. + + :ivar alignment: What alignment settings the subscription should have. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar metadata: Arbitrary metadata associated with the subscription. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar plan: The plan reference to change to. Required. + :vartype plan: ~openmeter._generated.models.PlanReferenceInput + :ivar starting_phase: The key of the phase to start the subscription in. If not provided, the + subscription will start in the first phase of the plan. + :vartype starting_phase: str + :ivar name: The name of the Subscription. If not provided the plan name is used. + :vartype name: str + :ivar description: Description for the Subscription. + :vartype description: str + :ivar settlement_mode: The settlement mode of the subscription. Known values are: + "credit_then_invoice" and "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar timing: Timing configuration for the change, when the change should take effect. The + default is immediate. Is either a Union[str, "_models.SubscriptionTimingEnum"] type or a + datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar customer_id: The ID of the customer. Provide either the key or ID. Has presedence over + the key. + :vartype customer_id: str + :ivar customer_key: The key of the customer. Provide either the key or ID. + :vartype customer_key: str + :ivar billing_anchor: The billing anchor of the subscription. The provided date will be + normalized according to the billing cadence to the nearest recurrence before start time. If not + provided, the subscription start time will be used. + :vartype billing_anchor: ~datetime.datetime + """ + + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """What alignment settings the subscription should have.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Arbitrary metadata associated with the subscription.""" + plan: "_models.PlanReferenceInput" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan reference to change to. Required.""" + starting_phase: Optional[str] = rest_field( + name="startingPhase", visibility=["read", "create", "update", "delete", "query"] + ) + """The key of the phase to start the subscription in. If not provided, the subscription will start + in the first phase of the plan.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the Subscription. If not provided the plan name is used.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description for the Subscription.""" + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = rest_field( + name="settlementMode", visibility=["read", "create", "update", "delete", "query"] + ) + """The settlement mode of the subscription. Known values are: \"credit_then_invoice\" and + \"credit_only\".""" + timing: Optional["_types.SubscriptionTiming"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Timing configuration for the change, when the change should take effect. The default is + immediate. Is either a Union[str, \"_models.SubscriptionTimingEnum\"] type or a + datetime.datetime type.""" + customer_id: Optional[str] = rest_field( + name="customerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The ID of the customer. Provide either the key or ID. Has presedence over the key.""" + customer_key: Optional[str] = rest_field( + name="customerKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The key of the customer. Provide either the key or ID.""" + billing_anchor: Optional[datetime.datetime] = rest_field( + name="billingAnchor", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The billing anchor of the subscription. The provided date will be normalized according to the + billing cadence to the nearest recurrence before start time. If not provided, the subscription + start time will be used.""" + + @overload + def __init__( + self, + *, + plan: "_models.PlanReferenceInput", + alignment: Optional["_models.Alignment"] = None, + metadata: Optional["_models.Metadata"] = None, + starting_phase: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + settlement_mode: Optional[Union[str, "_models.BillingSettlementMode"]] = None, + timing: Optional["_types.SubscriptionTiming"] = None, + customer_id: Optional[str] = None, + customer_key: Optional[str] = None, + billing_anchor: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PortalToken(_Model): + """A consumer portal token. + + Validator doesn't obey required for readOnly properties + See: `https://github.com/stoplightio/spectral/issues/1274 + `_. + + :ivar id: + :vartype id: str + :ivar subject: Required. + :vartype subject: str + :ivar expires_at: + :vartype expires_at: ~datetime.datetime + :ivar expired: + :vartype expired: bool + :ivar created_at: + :vartype created_at: ~datetime.datetime + :ivar token: The token is only returned at creation. + :vartype token: str + :ivar allowed_meter_slugs: Optional, if defined only the specified meters will be allowed. + :vartype allowed_meter_slugs: list[str] + """ + + id: Optional[str] = rest_field(visibility=["read"]) + subject: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + expires_at: Optional[datetime.datetime] = rest_field(name="expiresAt", visibility=["read"], format="rfc3339") + expired: Optional[bool] = rest_field(visibility=["read"]) + created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + token: Optional[str] = rest_field(visibility=["read"]) + """The token is only returned at creation.""" + allowed_meter_slugs: Optional[list[str]] = rest_field( + name="allowedMeterSlugs", visibility=["read", "create", "update", "delete", "query"] + ) + """Optional, if defined only the specified meters will be allowed.""" + + @overload + def __init__( + self, + *, + subject: str, + allowed_meter_slugs: Optional[list[str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PreconditionFailedProblemResponse(UnexpectedProblemResponse): + """One or more conditions given in the request header fields evaluated to false when tested on the + server. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class PriceTier(_Model): + """A price tier. At least one price component is required in each tier. + + :ivar up_to_amount: Up to quantity. + :vartype up_to_amount: str + :ivar flat_price: Flat price component. Required. + :vartype flat_price: ~openmeter._generated.models.FlatPrice + :ivar unit_price: Unit price component. Required. + :vartype unit_price: ~openmeter._generated.models.UnitPrice + """ + + up_to_amount: Optional[str] = rest_field(name="upToAmount", visibility=["read", "create", "update"]) + """Up to quantity.""" + flat_price: "_models.FlatPrice" = rest_field(name="flatPrice", visibility=["read", "create", "update"]) + """Flat price component. Required.""" + unit_price: "_models.UnitPrice" = rest_field(name="unitPrice", visibility=["read", "create", "update"]) + """Unit price component. Required.""" + + @overload + def __init__( + self, + *, + flat_price: "_models.FlatPrice", + unit_price: "_models.UnitPrice", + up_to_amount: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Progress(_Model): + """Progress describes a progress of a task. + + :ivar success: Success is the number of items that succeeded. Required. + :vartype success: int + :ivar failed: Failed is the number of items that failed. Required. + :vartype failed: int + :ivar total: The total number of items to process. Required. + :vartype total: int + :ivar updated_at: The time the progress was last updated. Required. + :vartype updated_at: ~datetime.datetime + """ + + success: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Success is the number of items that succeeded. Required.""" + failed: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Failed is the number of items that failed. Required.""" + total: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The total number of items to process. Required.""" + updated_at: datetime.datetime = rest_field( + name="updatedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time the progress was last updated. Required.""" + + @overload + def __init__( + self, + *, + success: int, + failed: int, + total: int, + updated_at: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ProRatingConfig(_Model): + """Configuration for pro-rating behavior. + + :ivar enabled: Enable pro-rating. Required. + :vartype enabled: bool + :ivar mode: Pro-rating mode. Required. "prorate_prices" + :vartype mode: str or ~openmeter.models.ProRatingMode + """ + + enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Enable pro-rating. Required.""" + mode: Union[str, "_models.ProRatingMode"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Pro-rating mode. Required. \"prorate_prices\"""" + + @overload + def __init__( + self, + *, + enabled: bool, + mode: Union[str, "_models.ProRatingMode"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RateCardBooleanEntitlement(_Model): + """Entitlement template of a boolean entitlement. + + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: Required. BOOLEAN. + :vartype type: str or ~openmeter._generated.models.BOOLEAN + """ + + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + type: Literal[EntitlementType.BOOLEAN] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. BOOLEAN.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.BOOLEAN], + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RateCardFlatFee(_Model): + """A flat fee rate card defines a one-time purchase or a recurring fee. + + :ivar type: RateCard type. Required. FLAT_FEE. + :vartype type: str or ~openmeter._generated.models.FLAT_FEE + :ivar key: Key. Required. + :vartype key: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar feature_key: Feature key. + :vartype feature_key: str + :ivar entitlement_template: The entitlement of the rate card. Only available when featureKey is + set. Is one of the following types: RateCardMeteredEntitlement, RateCardStaticEntitlement, + RateCardBooleanEntitlement + :vartype entitlement_template: ~openmeter._generated.models.RateCardMeteredEntitlement or + ~openmeter._generated.models.RateCardStaticEntitlement or + ~openmeter._generated.models.RateCardBooleanEntitlement + :ivar tax_config: Tax config. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar price: Price. Required. + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm + :ivar discounts: Discounts. + :vartype discounts: ~openmeter._generated.models.Discounts + """ + + type: Literal[RateCardType.FLAT_FEE] = rest_field(visibility=["read", "create", "update"]) + """RateCard type. Required. FLAT_FEE.""" + key: str = rest_field(visibility=["read", "create"]) + """Key. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """Feature key.""" + entitlement_template: Optional["_types.RateCardEntitlement"] = rest_field( + name="entitlementTemplate", visibility=["read", "create", "update"] + ) + """The entitlement of the rate card. Only available when featureKey is set. Is one of the + following types: RateCardMeteredEntitlement, RateCardStaticEntitlement, + RateCardBooleanEntitlement""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read", "create", "update"]) + """Billing cadence. Required.""" + price: "_models.FlatPriceWithPaymentTerm" = rest_field(visibility=["read", "create", "update"]) + """Price. Required.""" + discounts: Optional["_models.Discounts"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Discounts.""" + + @overload + def __init__( + self, + *, + type: Literal[RateCardType.FLAT_FEE], + key: str, + name: str, + billing_cadence: datetime.timedelta, + price: "_models.FlatPriceWithPaymentTerm", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + feature_key: Optional[str] = None, + entitlement_template: Optional["_types.RateCardEntitlement"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + discounts: Optional["_models.Discounts"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RateCardMeteredEntitlement(_Model): + """The entitlement template with a metered entitlement. + + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: Required. METERED. + :vartype type: str or ~openmeter._generated.models.METERED + :ivar is_soft_limit: Soft limit. + :vartype is_soft_limit: bool + :ivar issue_after_reset: Initial grant amount. + :vartype issue_after_reset: float + :ivar issue_after_reset_priority: Issue grant after reset priority. + :vartype issue_after_reset_priority: int + :ivar preserve_overage_at_reset: Preserve overage at reset. + :vartype preserve_overage_at_reset: bool + :ivar usage_period: Usage Period. + :vartype usage_period: ~datetime.timedelta + """ + + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + type: Literal[EntitlementType.METERED] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. METERED.""" + is_soft_limit: Optional[bool] = rest_field( + name="isSoftLimit", visibility=["read", "create", "update", "delete", "query"] + ) + """Soft limit.""" + issue_after_reset: Optional[float] = rest_field( + name="issueAfterReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Initial grant amount.""" + issue_after_reset_priority: Optional[int] = rest_field( + name="issueAfterResetPriority", visibility=["read", "create", "update", "delete", "query"] + ) + """Issue grant after reset priority.""" + preserve_overage_at_reset: Optional[bool] = rest_field( + name="preserveOverageAtReset", visibility=["read", "create", "update", "delete", "query"] + ) + """Preserve overage at reset.""" + usage_period: Optional[datetime.timedelta] = rest_field(name="usagePeriod", visibility=["read", "create", "update"]) + """Usage Period.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.METERED], + metadata: Optional["_models.Metadata"] = None, + is_soft_limit: Optional[bool] = None, + issue_after_reset: Optional[float] = None, + issue_after_reset_priority: Optional[int] = None, + preserve_overage_at_reset: Optional[bool] = None, + usage_period: Optional[datetime.timedelta] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RateCardStaticEntitlement(_Model): + """Entitlement template of a static entitlement. + + :ivar metadata: Additional metadata for the feature. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: Required. STATIC. + :vartype type: str or ~openmeter._generated.models.STATIC + :ivar config: The JSON parsable config of the entitlement. This value is also returned when + checking entitlement access and it is useful for configuring fine-grained access settings to + the feature, implemented in your own system. Has to be an object. Required. + :vartype config: str + """ + + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional metadata for the feature.""" + type: Literal[EntitlementType.STATIC] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required. STATIC.""" + config: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The JSON parsable config of the entitlement. This value is also returned when checking + entitlement access and it is useful for configuring fine-grained access settings to the + feature, implemented in your own system. Has to be an object. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[EntitlementType.STATIC], + config: str, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RateCardUsageBased(_Model): + """A usage-based rate card defines a price based on usage. + + :ivar type: RateCard type. Required. USAGE_BASED. + :vartype type: str or ~openmeter._generated.models.USAGE_BASED + :ivar key: Key. Required. + :vartype key: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar feature_key: Feature key. + :vartype feature_key: str + :ivar entitlement_template: The entitlement of the rate card. Only available when featureKey is + set. Is one of the following types: RateCardMeteredEntitlement, RateCardStaticEntitlement, + RateCardBooleanEntitlement + :vartype entitlement_template: ~openmeter._generated.models.RateCardMeteredEntitlement or + ~openmeter._generated.models.RateCardStaticEntitlement or + ~openmeter._generated.models.RateCardBooleanEntitlement + :ivar tax_config: Tax config. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar price: The price of the rate card. When null, the feature or service is free. Required. + Is one of the following types: FlatPriceWithPaymentTerm, UnitPriceWithCommitments, + TieredPriceWithCommitments, DynamicPriceWithCommitments, PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar discounts: Discounts. + :vartype discounts: ~openmeter._generated.models.Discounts + """ + + type: Literal[RateCardType.USAGE_BASED] = rest_field(visibility=["read", "create", "update"]) + """RateCard type. Required. USAGE_BASED.""" + key: str = rest_field(visibility=["read", "create"]) + """Key. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + feature_key: Optional[str] = rest_field(name="featureKey", visibility=["read", "create", "update"]) + """Feature key.""" + entitlement_template: Optional["_types.RateCardEntitlement"] = rest_field( + name="entitlementTemplate", visibility=["read", "create", "update"] + ) + """The entitlement of the rate card. Only available when featureKey is set. Is one of the + following types: RateCardMeteredEntitlement, RateCardStaticEntitlement, + RateCardBooleanEntitlement""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read", "create", "update"]) + """Billing cadence. Required.""" + price: "_types.RateCardUsageBasedPrice" = rest_field(visibility=["read", "create", "update"]) + """The price of the rate card. When null, the feature or service is free. Required. Is one of the + following types: FlatPriceWithPaymentTerm, UnitPriceWithCommitments, + TieredPriceWithCommitments, DynamicPriceWithCommitments, PackagePriceWithCommitments""" + discounts: Optional["_models.Discounts"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Discounts.""" + + @overload + def __init__( + self, + *, + type: Literal[RateCardType.USAGE_BASED], + key: str, + name: str, + billing_cadence: datetime.timedelta, + price: "_types.RateCardUsageBasedPrice", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + feature_key: Optional[str] = None, + entitlement_template: Optional["_types.RateCardEntitlement"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + discounts: Optional["_models.Discounts"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RecurringPeriod(_Model): + """Recurring period with an interval and an anchor. + + :ivar interval: Interval. Required. Is either a str type or a Union[str, + "_models.RecurringPeriodIntervalEnum"] type. + :vartype interval: str or str or ~openmeter.models.RecurringPeriodIntervalEnum + :ivar anchor: Anchor time. Required. + :vartype anchor: ~datetime.datetime + :ivar interval_iso: The unit of time for the interval in ISO8601 format. Required. + :vartype interval_iso: ~datetime.timedelta + """ + + interval: "_types.RecurringPeriodInterval" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Interval. Required. Is either a str type or a Union[str, + \"_models.RecurringPeriodIntervalEnum\"] type.""" + anchor: datetime.datetime = rest_field(visibility=["read", "create", "update", "delete", "query"], format="rfc3339") + """Anchor time. Required.""" + interval_iso: datetime.timedelta = rest_field( + name="intervalISO", visibility=["read", "create", "update", "delete", "query"] + ) + """The unit of time for the interval in ISO8601 format. Required.""" + + @overload + def __init__( + self, + *, + interval: "_types.RecurringPeriodInterval", + anchor: datetime.datetime, + interval_iso: datetime.timedelta, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RecurringPeriodCreateInput(_Model): + """Recurring period with an interval and an anchor. + + :ivar interval: Interval. Required. Is either a str type or a Union[str, + "_models.RecurringPeriodIntervalEnum"] type. + :vartype interval: str or str or ~openmeter.models.RecurringPeriodIntervalEnum + :ivar anchor: Anchor time. + :vartype anchor: ~datetime.datetime + """ + + interval: "_types.RecurringPeriodInterval" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Interval. Required. Is either a str type or a Union[str, + \"_models.RecurringPeriodIntervalEnum\"] type.""" + anchor: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Anchor time.""" + + @overload + def __init__( + self, + *, + interval: "_types.RecurringPeriodInterval", + anchor: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RecurringPeriodV2(_Model): + """Recurring period with an interval and an anchor. + + :ivar interval: Interval. Required. Is either a str type or a Union[str, + "_models.RecurringPeriodIntervalEnum"] type. + :vartype interval: str or str or ~openmeter.models.RecurringPeriodIntervalEnum + :ivar anchor: Anchor time. Required. + :vartype anchor: ~datetime.datetime + """ + + interval: "_types.RecurringPeriodInterval" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Interval. Required. Is either a str type or a Union[str, + \"_models.RecurringPeriodIntervalEnum\"] type.""" + anchor: datetime.datetime = rest_field(visibility=["read", "create", "update", "delete", "query"], format="rfc3339") + """Anchor time. Required.""" + + @overload + def __init__( + self, + *, + interval: "_types.RecurringPeriodInterval", + anchor: datetime.datetime, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ResetEntitlementUsageInput(_Model): + """Reset parameters. + + :ivar effective_at: The time at which the reset takes effect, defaults to now. The reset cannot + be in the future. The provided value is truncated to the minute due to how historical meter + data is stored. + :vartype effective_at: ~datetime.datetime + :ivar retain_anchor: Determines whether the usage period anchor is retained or reset to the + effectiveAt time. + + * If true, the usage period anchor is retained. + * If false, the usage period anchor is reset to the effectiveAt time. + :vartype retain_anchor: bool + :ivar preserve_overage: Determines whether the overage is preserved or forgiven, overriding the + entitlement's default behavior. + + * If true, the overage is preserved. + * If false, the overage is forgiven. + :vartype preserve_overage: bool + """ + + effective_at: Optional[datetime.datetime] = rest_field( + name="effectiveAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time at which the reset takes effect, defaults to now. The reset cannot be in the future. + The provided value is truncated to the minute due to how historical meter data is stored.""" + retain_anchor: Optional[bool] = rest_field( + name="retainAnchor", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether the usage period anchor is retained or reset to the effectiveAt time. + + * If true, the usage period anchor is retained. + * If false, the usage period anchor is reset to the effectiveAt time.""" + preserve_overage: Optional[bool] = rest_field( + name="preserveOverage", visibility=["read", "create", "update", "delete", "query"] + ) + """Determines whether the overage is preserved or forgiven, overriding the entitlement's default + behavior. + + * If true, the overage is preserved. + * If false, the overage is forgiven.""" + + @overload + def __init__( + self, + *, + effective_at: Optional[datetime.datetime] = None, + retain_anchor: Optional[bool] = None, + preserve_overage: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SandboxApp(_Model): + """Sandbox app can be used for testing OpenMeter features. + + The app is not creating anything in external systems, thus it is safe to use for + verifying OpenMeter features. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar listing: The marketplace listing that this installed app is based on. Required. + :vartype listing: ~openmeter._generated.models.MarketplaceListing + :ivar status: Status of the app connection. Required. Known values are: "ready" and + "unauthorized". + :vartype status: str or ~openmeter.models.AppStatus + :ivar type: The app's type is Sandbox. Required. SANDBOX. + :vartype type: str or ~openmeter._generated.models.SANDBOX + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + listing: "_models.MarketplaceListing" = rest_field(visibility=["read"]) + """The marketplace listing that this installed app is based on. Required.""" + status: Union[str, "_models.AppStatus"] = rest_field(visibility=["read"]) + """Status of the app connection. Required. Known values are: \"ready\" and \"unauthorized\".""" + type: Literal[AppType.SANDBOX] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type is Sandbox. Required. SANDBOX.""" + + @overload + def __init__( + self, + *, + name: str, + type: Literal[AppType.SANDBOX], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SandboxAppReplaceUpdate(_Model): + """Resource update operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: The app's type is Sandbox. Required. SANDBOX. + :vartype type: str or ~openmeter._generated.models.SANDBOX + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + type: Literal[AppType.SANDBOX] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type is Sandbox. Required. SANDBOX.""" + + @overload + def __init__( + self, + *, + name: str, + type: Literal[AppType.SANDBOX], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SandboxCustomerAppData(_Model): + """Sandbox Customer App Data. + + :ivar app: The installed sandbox app this data belongs to. + :vartype app: ~openmeter._generated.models.SandboxApp + :ivar id: App ID. + :vartype id: str + :ivar type: App Type. Required. SANDBOX. + :vartype type: str or ~openmeter._generated.models.SANDBOX + """ + + app: Optional["_models.SandboxApp"] = rest_field(visibility=["read"]) + """The installed sandbox app this data belongs to.""" + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """App ID.""" + type: Literal[AppType.SANDBOX] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """App Type. Required. SANDBOX.""" + + @overload + def __init__( + self, + *, + type: Literal[AppType.SANDBOX], + id: Optional[str] = None, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ServiceUnavailableProblemResponse(UnexpectedProblemResponse): + """The server is currently unable to handle the request due to a temporary overload or scheduled + maintenance, which will likely be alleviated after some delay. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeAPIKeyInput(_Model): + """The Stripe API key input. Used to authenticate with the Stripe API. + + :ivar secret_api_key: Required. + :vartype secret_api_key: str + """ + + secret_api_key: str = rest_field(name="secretAPIKey", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + secret_api_key: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeApp(_Model): + """A installed Stripe app object. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar listing: The marketplace listing that this installed app is based on. Required. + :vartype listing: ~openmeter._generated.models.MarketplaceListing + :ivar status: Status of the app connection. Required. Known values are: "ready" and + "unauthorized". + :vartype status: str or ~openmeter.models.AppStatus + :ivar type: The app's type is Stripe. Required. STRIPE. + :vartype type: str or ~openmeter._generated.models.STRIPE + :ivar stripe_account_id: The Stripe account ID. Required. + :vartype stripe_account_id: str + :ivar livemode: Livemode, true if the app is in production mode. Required. + :vartype livemode: bool + :ivar masked_api_key: The masked API key. Only shows the first 8 and last 3 characters. + Required. + :vartype masked_api_key: str + :ivar secret_api_key: The Stripe API key. + :vartype secret_api_key: str + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + listing: "_models.MarketplaceListing" = rest_field(visibility=["read"]) + """The marketplace listing that this installed app is based on. Required.""" + status: Union[str, "_models.AppStatus"] = rest_field(visibility=["read"]) + """Status of the app connection. Required. Known values are: \"ready\" and \"unauthorized\".""" + type: Literal[AppType.STRIPE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type is Stripe. Required. STRIPE.""" + stripe_account_id: str = rest_field(name="stripeAccountId", visibility=["read"]) + """The Stripe account ID. Required.""" + livemode: bool = rest_field(visibility=["read"]) + """Livemode, true if the app is in production mode. Required.""" + masked_api_key: str = rest_field(name="maskedAPIKey", visibility=["read"]) + """The masked API key. Only shows the first 8 and last 3 characters. Required.""" + secret_api_key: Optional[str] = rest_field(name="secretAPIKey", visibility=["create", "update"]) + """The Stripe API key.""" + + @overload + def __init__( + self, + *, + name: str, + type: Literal[AppType.STRIPE], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + secret_api_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeAppReplaceUpdate(_Model): + """Resource update operation model. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar type: The app's type is Stripe. Required. STRIPE. + :vartype type: str or ~openmeter._generated.models.STRIPE + :ivar secret_api_key: The Stripe API key. + :vartype secret_api_key: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + type: Literal[AppType.STRIPE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The app's type is Stripe. Required. STRIPE.""" + secret_api_key: Optional[str] = rest_field(name="secretAPIKey", visibility=["create", "update"]) + """The Stripe API key.""" + + @overload + def __init__( + self, + *, + name: str, + type: Literal[AppType.STRIPE], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + secret_api_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeCustomerAppData(_Model): + """Stripe Customer App Data. + + :ivar id: App ID. + :vartype id: str + :ivar type: App Type. Required. STRIPE. + :vartype type: str or ~openmeter._generated.models.STRIPE + :ivar stripe_customer_id: The Stripe customer ID. Required. + :vartype stripe_customer_id: str + :ivar stripe_default_payment_method_id: The Stripe default payment method ID. + :vartype stripe_default_payment_method_id: str + :ivar app: The installed stripe app this data belongs to. + :vartype app: ~openmeter._generated.models.StripeApp + """ + + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """App ID.""" + type: Literal[AppType.STRIPE] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """App Type. Required. STRIPE.""" + stripe_customer_id: str = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe customer ID. Required.""" + stripe_default_payment_method_id: Optional[str] = rest_field( + name="stripeDefaultPaymentMethodId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe default payment method ID.""" + app: Optional["_models.StripeApp"] = rest_field(visibility=["read"]) + """The installed stripe app this data belongs to.""" + + @overload + def __init__( + self, + *, + type: Literal[AppType.STRIPE], + stripe_customer_id: str, + id: Optional[str] = None, # pylint: disable=redefined-builtin + stripe_default_payment_method_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeCustomerAppDataBase(_Model): + """Stripe Customer App Data Base. + + :ivar stripe_customer_id: The Stripe customer ID. Required. + :vartype stripe_customer_id: str + :ivar stripe_default_payment_method_id: The Stripe default payment method ID. + :vartype stripe_default_payment_method_id: str + """ + + stripe_customer_id: str = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe customer ID. Required.""" + stripe_default_payment_method_id: Optional[str] = rest_field( + name="stripeDefaultPaymentMethodId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe default payment method ID.""" + + @overload + def __init__( + self, + *, + stripe_customer_id: str, + stripe_default_payment_method_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeCustomerPortalSession(_Model): + """Stripe customer portal session. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object + `_. + + :ivar id: The ID of the customer portal session. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + `_. + Required. + :vartype id: str + :ivar stripe_customer_id: The ID of the stripe customer. Required. + :vartype stripe_customer_id: str + :ivar configuration_id: Configuration used to customize the customer portal. + + See: + `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + `_. + Required. + :vartype configuration_id: str + :ivar livemode: Livemode. + + See: + `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + `_. + Required. + :vartype livemode: bool + :ivar created_at: Created at. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + `_. + Required. + :vartype created_at: ~datetime.datetime + :ivar return_url: Return URL. + + See: + `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + `_. + Required. + :vartype return_url: str + :ivar locale: Status. + /** + The IETF language tag of the locale customer portal is displayed in. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + `_. + Required. + :vartype locale: str + :ivar url: /** The ID of the customer.The URL to redirect the customer to after they have + completed their requested actions. Required. + :vartype url: str + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the customer portal session. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + `_. + Required.""" + stripe_customer_id: str = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The ID of the stripe customer. Required.""" + configuration_id: str = rest_field( + name="configurationId", visibility=["read", "create", "update", "delete", "query"] + ) + """Configuration used to customize the customer portal. + + See: + `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + `_. + Required.""" + livemode: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Livemode. + + See: + `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + `_. + Required.""" + created_at: datetime.datetime = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """Created at. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + `_. + Required.""" + return_url: str = rest_field(name="returnUrl", visibility=["read", "create", "update", "delete", "query"]) + """Return URL. + + See: + `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + `_. + Required.""" + locale: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Status. + /** + The IETF language tag of the locale customer portal is displayed in. + + See: `https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + `_. + Required.""" + url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """/** The ID of the customer.The URL to redirect the customer to after they have completed their + requested actions. Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + stripe_customer_id: str, + configuration_id: str, + livemode: bool, + created_at: datetime.datetime, + return_url: str, + locale: str, + url: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeTaxConfig(_Model): + """The tax config for Stripe. + + :ivar code: Tax code. Required. + :vartype code: str + """ + + code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tax code. Required.""" + + @overload + def __init__( + self, + *, + code: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeWebhookEvent(_Model): + """Stripe webhook event. + + :ivar id: The event ID. Required. + :vartype id: str + :ivar type: The event type. Required. + :vartype type: str + :ivar livemode: Live mode. Required. + :vartype livemode: bool + :ivar created: The event created timestamp. Required. + :vartype created: int + :ivar data: The event data. Required. + :vartype data: ~openmeter._generated.models.StripeWebhookEventData + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The event ID. Required.""" + type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The event type. Required.""" + livemode: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Live mode. Required.""" + created: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The event created timestamp. Required.""" + data: "_models.StripeWebhookEventData" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The event data. Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + type: str, + livemode: bool, + created: int, + data: "_models.StripeWebhookEventData", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeWebhookEventData(_Model): + """StripeWebhookEventData. + + :ivar object: Required. + :vartype object: any + """ + + object: Any = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + object: Any, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StripeWebhookResponse(_Model): + """Stripe webhook response. + + :ivar namespace_id: Required. + :vartype namespace_id: str + :ivar app_id: Required. + :vartype app_id: str + :ivar customer_id: + :vartype customer_id: str + :ivar message: + :vartype message: str + """ + + namespace_id: str = rest_field(name="namespaceId", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + app_id: str = rest_field(name="appId", visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + customer_id: Optional[str] = rest_field( + name="customerId", visibility=["read", "create", "update", "delete", "query"] + ) + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + namespace_id: str, + app_id: str, + customer_id: Optional[str] = None, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Subject(_Model): + """A subject is a unique identifier for a usage attribution by its key. + Subjects only exist in the concept of metering. + Subjects are optional to create and work as an enrichment for the subject key like displayName, + metadata, etc. + Subjects are useful when you are reporting usage events with your own database ID but want to + enrich the subject with a human-readable name or metadata. + For most use cases, a subject is equivalent to a customer. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: A unique identifier for the subject. Required. + :vartype id: str + :ivar key: A unique, human-readable identifier for the subject. This is typically a database ID + or a customer key. Required. + :vartype key: str + :ivar display_name: A human-readable display name for the subject. + :vartype display_name: str + :ivar metadata: Metadata for the subject. + :vartype metadata: dict[str, any] + :ivar current_period_start: The start of the current period for the subject. + :vartype current_period_start: ~datetime.datetime + :ivar current_period_end: The end of the current period for the subject. + :vartype current_period_end: ~datetime.datetime + :ivar stripe_customer_id: The Stripe customer ID for the subject. + :vartype stripe_customer_id: str + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """A unique identifier for the subject. Required.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A unique, human-readable identifier for the subject. This is typically a database ID or a + customer key. Required.""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """A human-readable display name for the subject.""" + metadata: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata for the subject.""" + current_period_start: Optional[datetime.datetime] = rest_field( + name="currentPeriodStart", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start of the current period for the subject.""" + current_period_end: Optional[datetime.datetime] = rest_field( + name="currentPeriodEnd", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end of the current period for the subject.""" + stripe_customer_id: Optional[str] = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe customer ID for the subject.""" + + @overload + def __init__( + self, + *, + key: str, + display_name: Optional[str] = None, + metadata: Optional[dict[str, Any]] = None, + current_period_start: Optional[datetime.datetime] = None, + current_period_end: Optional[datetime.datetime] = None, + stripe_customer_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubjectUpsert(_Model): + """A subject is a unique identifier for a user or entity. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :ivar key: A unique, human-readable identifier for the subject. This is typically a database ID + or a customer key. Required. + :vartype key: str + :ivar display_name: A human-readable display name for the subject. + :vartype display_name: str + :ivar metadata: Metadata for the subject. + :vartype metadata: dict[str, any] + :ivar current_period_start: The start of the current period for the subject. + :vartype current_period_start: ~datetime.datetime + :ivar current_period_end: The end of the current period for the subject. + :vartype current_period_end: ~datetime.datetime + :ivar stripe_customer_id: The Stripe customer ID for the subject. + :vartype stripe_customer_id: str + """ + + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A unique, human-readable identifier for the subject. This is typically a database ID or a + customer key. Required.""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """A human-readable display name for the subject.""" + metadata: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata for the subject.""" + current_period_start: Optional[datetime.datetime] = rest_field( + name="currentPeriodStart", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The start of the current period for the subject.""" + current_period_end: Optional[datetime.datetime] = rest_field( + name="currentPeriodEnd", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The end of the current period for the subject.""" + stripe_customer_id: Optional[str] = rest_field( + name="stripeCustomerId", visibility=["read", "create", "update", "delete", "query"] + ) + """The Stripe customer ID for the subject.""" + + @overload + def __init__( + self, + *, + key: str, + display_name: Optional[str] = None, + metadata: Optional[dict[str, Any]] = None, + current_period_start: Optional[datetime.datetime] = None, + current_period_end: Optional[datetime.datetime] = None, + stripe_customer_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Subscription(_Model): + """Subscription is an exact subscription instance. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar alignment: Alignment configuration for the plan. + :vartype alignment: ~openmeter._generated.models.Alignment + :ivar status: The status of the subscription. Required. Known values are: "active", "inactive", + "canceled", and "scheduled". + :vartype status: str or ~openmeter.models.SubscriptionStatus + :ivar customer_id: The customer ID of the subscription. Required. + :vartype customer_id: str + :ivar plan: The plan of the subscription. + :vartype plan: ~openmeter._generated.models.PlanReference + :ivar currency: Currency. Required. + :vartype currency: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar billing_anchor: Billing anchor. Required. + :vartype billing_anchor: ~datetime.datetime + :ivar settlement_mode: Settlement mode. Required. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + alignment: Optional["_models.Alignment"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Alignment configuration for the plan.""" + status: Union[str, "_models.SubscriptionStatus"] = rest_field(visibility=["read"]) + """The status of the subscription. Required. Known values are: \"active\", \"inactive\", + \"canceled\", and \"scheduled\".""" + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The customer ID of the subscription. Required.""" + plan: Optional["_models.PlanReference"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan of the subscription.""" + currency: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency. Required.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read"]) + """Billing cadence. Required.""" + pro_rating_config: Optional["_models.ProRatingConfig"] = rest_field(name="proRatingConfig", visibility=["read"]) + """Pro-rating configuration.""" + billing_anchor: datetime.datetime = rest_field(name="billingAnchor", visibility=["read"], format="rfc3339") + """Billing anchor. Required.""" + settlement_mode: Union[str, "_models.BillingSettlementMode"] = rest_field( + name="settlementMode", visibility=["read"] + ) + """Settlement mode. Required. Known values are: \"credit_then_invoice\" and \"credit_only\".""" + + @overload + def __init__( + self, + *, + name: str, + active_from: datetime.datetime, + customer_id: str, + currency: str, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + alignment: Optional["_models.Alignment"] = None, + plan: Optional["_models.PlanReference"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddon(_Model): + """A subscription add-on, represents concrete instances of an add-on for a given subscription. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar addon: Addon. Required. + :vartype addon: ~openmeter._generated.models.SubscriptionAddonAddon + :ivar quantity_at: QuantityAt. Required. + :vartype quantity_at: ~datetime.datetime + :ivar quantity: Quantity. Required. + :vartype quantity: int + :ivar timing: Timing. Required. Is either a Union[str, "_models.SubscriptionTimingEnum"] type + or a datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar timeline: Timeline. Required. + :vartype timeline: list[~openmeter._generated.models.SubscriptionAddonTimelineSegment] + :ivar subscription_id: SubscriptionID. Required. + :vartype subscription_id: str + :ivar rate_cards: Rate cards. Required. + :vartype rate_cards: list[~openmeter._generated.models.SubscriptionAddonRateCard] + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + active_from: datetime.datetime = rest_field(name="activeFrom", visibility=["read"], format="rfc3339") + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field(name="activeTo", visibility=["read"], format="rfc3339") + """The cadence end of the resource.""" + addon: "_models.SubscriptionAddonAddon" = rest_field(visibility=["read", "create"]) + """Addon. Required.""" + quantity_at: datetime.datetime = rest_field(name="quantityAt", visibility=["read"], format="rfc3339") + """QuantityAt. Required.""" + quantity: int = rest_field(visibility=["read", "create", "update"]) + """Quantity. Required.""" + timing: "_types.SubscriptionTiming" = rest_field(visibility=["create", "update"]) + """Timing. Required. Is either a Union[str, \"_models.SubscriptionTimingEnum\"] type or a + datetime.datetime type.""" + timeline: list["_models.SubscriptionAddonTimelineSegment"] = rest_field(visibility=["read"]) + """Timeline. Required.""" + subscription_id: str = rest_field(name="subscriptionId", visibility=["read"]) + """SubscriptionID. Required.""" + rate_cards: list["_models.SubscriptionAddonRateCard"] = rest_field(name="rateCards", visibility=["read"]) + """Rate cards. Required.""" + + @overload + def __init__( + self, + *, + name: str, + addon: "_models.SubscriptionAddonAddon", + quantity: int, + timing: "_types.SubscriptionTiming", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddonAddon(_Model): + """SubscriptionAddonAddon. + + :ivar id: ID. Required. + :vartype id: str + :ivar key: Key. Required. + :vartype key: str + :ivar version: Version. Required. + :vartype version: int + :ivar instance_type: InstanceType. Required. Known values are: "single" and "multiple". + :vartype instance_type: str or ~openmeter.models.AddonInstanceType + """ + + id: str = rest_field(visibility=["read", "create"]) + """ID. Required.""" + key: str = rest_field(visibility=["read"]) + """Key. Required.""" + version: int = rest_field(visibility=["read"]) + """Version. Required.""" + instance_type: Union[str, "_models.AddonInstanceType"] = rest_field(name="instanceType", visibility=["read"]) + """InstanceType. Required. Known values are: \"single\" and \"multiple\".""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddonCreate(_Model): + """A subscription add-on create body. + + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar quantity: Quantity. Required. + :vartype quantity: int + :ivar timing: Timing. Required. Is either a Union[str, "_models.SubscriptionTimingEnum"] type + or a datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + :ivar addon: Addon. Required. + :vartype addon: ~openmeter._generated.models.SubscriptionAddonCreateAddon + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + quantity: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Quantity. Required.""" + timing: "_types.SubscriptionTiming" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Timing. Required. Is either a Union[str, \"_models.SubscriptionTimingEnum\"] type or a + datetime.datetime type.""" + addon: "_models.SubscriptionAddonCreateAddon" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Addon. Required.""" + + @overload + def __init__( + self, + *, + name: str, + quantity: int, + timing: "_types.SubscriptionTiming", + addon: "_models.SubscriptionAddonCreateAddon", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddonCreateAddon(_Model): + """SubscriptionAddonCreateAddon. + + :ivar id: The ID of the add-on. Required. + :vartype id: str + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the add-on. Required.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddonRateCard(_Model): + """A rate card for a subscription add-on. + + :ivar rate_card: Rate card. Required. Is either a RateCardFlatFee type or a RateCardUsageBased + type. + :vartype rate_card: ~openmeter._generated.models.RateCardFlatFee or + ~openmeter._generated.models.RateCardUsageBased + :ivar affected_subscription_item_ids: Affected subscription item IDs. Required. + :vartype affected_subscription_item_ids: list[str] + """ + + rate_card: "_types.RateCard" = rest_field( + name="rateCard", visibility=["read", "create", "update", "delete", "query"] + ) + """Rate card. Required. Is either a RateCardFlatFee type or a RateCardUsageBased type.""" + affected_subscription_item_ids: list[str] = rest_field(name="affectedSubscriptionItemIds", visibility=["read"]) + """Affected subscription item IDs. Required.""" + + @overload + def __init__( + self, + *, + rate_card: "_types.RateCard", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddonTimelineSegment(_Model): + """A subscription add-on event. + + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar quantity: Quantity. Required. + :vartype quantity: int + """ + + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + quantity: int = rest_field(visibility=["read"]) + """Quantity. Required.""" + + @overload + def __init__( + self, + *, + active_from: datetime.datetime, + active_to: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAddonUpdate(_Model): + """Resource create or update operation model. + + :ivar name: Display name. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar quantity: Quantity. + :vartype quantity: int + :ivar timing: Timing. Is either a Union[str, "_models.SubscriptionTimingEnum"] type or a + datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + quantity: Optional[int] = rest_field(visibility=["read", "create", "update"]) + """Quantity.""" + timing: Optional["_types.SubscriptionTiming"] = rest_field(visibility=["create", "update"]) + """Timing. Is either a Union[str, \"_models.SubscriptionTimingEnum\"] type or a datetime.datetime + type.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + quantity: Optional[int] = None, + timing: Optional["_types.SubscriptionTiming"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionAlignment(_Model): + """Alignment details enriched with the current billing period. + + :ivar billables_must_align: Whether all Billable items and RateCards must align. Alignment + means the Price's BillingCadence must align for both duration and anchor time. + :vartype billables_must_align: bool + :ivar current_aligned_billing_period: The current billing period. Only has value if the + subscription is aligned and active. + :vartype current_aligned_billing_period: ~openmeter._generated.models.Period + """ + + billables_must_align: Optional[bool] = rest_field( + name="billablesMustAlign", visibility=["read", "create", "update"] + ) + """Whether all Billable items and RateCards must align. Alignment means the Price's BillingCadence + must align for both duration and anchor time.""" + current_aligned_billing_period: Optional["_models.Period"] = rest_field( + name="currentAlignedBillingPeriod", visibility=["read", "create", "update", "delete", "query"] + ) + """The current billing period. Only has value if the subscription is aligned and active.""" + + @overload + def __init__( + self, + *, + billables_must_align: Optional[bool] = None, + current_aligned_billing_period: Optional["_models.Period"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionBadRequestErrorResponse(_Model): + """The server cannot or will not process the request due to something that is perceived to be a + client error (e.g., malformed request syntax, invalid request message framing, or deceptive + request routing). Variants with ErrorExtensions specific to subscriptions. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. Is one of + the following types: SubscriptionBadRequestErrorResponseExtensions + :vartype extensions: ~openmeter._generated.models.SubscriptionBadRequestErrorResponseExtensions + """ + + type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type contains a URI that identifies the problem type. Required.""" + title: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A a short, human-readable summary of the problem type. Required.""" + status: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The HTTP status code generated by the origin server for this occurrence of the problem.""" + detail: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A human-readable explanation specific to this occurrence of the problem. Required.""" + instance: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A URI reference that identifies the specific occurrence of the problem. Required.""" + extensions: Optional["_types.SubscriptionErrorExtensions"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Additional properties specific to the problem type may be present. Is one of the following + types: SubscriptionBadRequestErrorResponseExtensions""" + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional["_types.SubscriptionErrorExtensions"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionBadRequestErrorResponseExtensions(_Model): # pylint: disable=name-too-long + """SubscriptionBadRequestErrorResponseExtensions. + + :ivar validation_errors: Required. + :vartype validation_errors: list[~openmeter._generated.models.ErrorExtension] + """ + + validation_errors: list["_models.ErrorExtension"] = rest_field( + name="validationErrors", visibility=["read", "create", "update", "delete", "query"] + ) + """Required.""" + + @overload + def __init__( + self, + *, + validation_errors: list["_models.ErrorExtension"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionChangeResponseBody(_Model): + """Response body for subscription change. + + :ivar current: Current subscription. Required. + :vartype current: ~openmeter._generated.models.Subscription + :ivar next: The subscription it will be changed to. Required. + :vartype next: ~openmeter._generated.models.SubscriptionExpanded + """ + + current: "_models.Subscription" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Current subscription. Required.""" + next: "_models.SubscriptionExpanded" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The subscription it will be changed to. Required.""" + + @overload + def __init__( + self, + *, + current: "_models.Subscription", + next: "_models.SubscriptionExpanded", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionConflictErrorResponse(_Model): + """The request could not be completed due to a conflict with the current state of the target + resource. Variants with ErrorExtensions specific to subscriptions. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. Is one of + the following types: SubscriptionBadRequestErrorResponseExtensions + :vartype extensions: ~openmeter._generated.models.SubscriptionBadRequestErrorResponseExtensions + """ + + type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Type contains a URI that identifies the problem type. Required.""" + title: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A a short, human-readable summary of the problem type. Required.""" + status: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The HTTP status code generated by the origin server for this occurrence of the problem.""" + detail: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A human-readable explanation specific to this occurrence of the problem. Required.""" + instance: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A URI reference that identifies the specific occurrence of the problem. Required.""" + extensions: Optional["_types.SubscriptionErrorExtensions"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Additional properties specific to the problem type may be present. Is one of the following + types: SubscriptionBadRequestErrorResponseExtensions""" + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional["_types.SubscriptionErrorExtensions"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionEdit(_Model): + """Subscription edit input. + + :ivar customizations: Batch processing commands for manipulating running subscriptions. The key + format is ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. Required. + :vartype customizations: list[~openmeter._generated.models.EditSubscriptionAddItem or + ~openmeter._generated.models.EditSubscriptionRemoveItem or + ~openmeter._generated.models.EditSubscriptionAddPhase or + ~openmeter._generated.models.EditSubscriptionRemovePhase or + ~openmeter._generated.models.EditSubscriptionStretchPhase or + ~openmeter._generated.models.EditSubscriptionUnscheduleEdit] + :ivar timing: Whether the billing period should be restarted.Timing configuration to allow for + the changes to take effect at different times. Is either a Union[str, + "_models.SubscriptionTimingEnum"] type or a datetime.datetime type. + :vartype timing: str or ~openmeter.models.SubscriptionTimingEnum or ~datetime.datetime + """ + + customizations: list["_types.SubscriptionEditOperation"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. Required.""" + timing: Optional["_types.SubscriptionTiming"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Whether the billing period should be restarted.Timing configuration to allow for the changes to + take effect at different times. Is either a Union[str, \"_models.SubscriptionTimingEnum\"] type + or a datetime.datetime type.""" + + @overload + def __init__( + self, + *, + customizations: list["_types.SubscriptionEditOperation"], + timing: Optional["_types.SubscriptionTiming"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionExpanded(_Model): + """Expanded subscription. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar annotations: Annotations. + :vartype annotations: ~openmeter._generated.models.Annotations + :ivar status: The status of the subscription. Required. Known values are: "active", "inactive", + "canceled", and "scheduled". + :vartype status: str or ~openmeter.models.SubscriptionStatus + :ivar customer_id: The customer ID of the subscription. Required. + :vartype customer_id: str + :ivar plan: The plan of the subscription. + :vartype plan: ~openmeter._generated.models.PlanReference + :ivar currency: Currency. Required. + :vartype currency: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar pro_rating_config: Pro-rating configuration. + :vartype pro_rating_config: ~openmeter._generated.models.ProRatingConfig + :ivar billing_anchor: Billing anchor. Required. + :vartype billing_anchor: ~datetime.datetime + :ivar settlement_mode: Settlement mode. Required. Known values are: "credit_then_invoice" and + "credit_only". + :vartype settlement_mode: str or ~openmeter.models.BillingSettlementMode + :ivar alignment: Alignment details enriched with the current billing period. + :vartype alignment: ~openmeter._generated.models.SubscriptionAlignment + :ivar phases: The phases of the subscription. Required. + :vartype phases: list[~openmeter._generated.models.SubscriptionPhaseExpanded] + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + annotations: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Annotations.""" + status: Union[str, "_models.SubscriptionStatus"] = rest_field(visibility=["read"]) + """The status of the subscription. Required. Known values are: \"active\", \"inactive\", + \"canceled\", and \"scheduled\".""" + customer_id: str = rest_field(name="customerId", visibility=["read", "create", "update", "delete", "query"]) + """The customer ID of the subscription. Required.""" + plan: Optional["_models.PlanReference"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The plan of the subscription.""" + currency: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Currency. Required.""" + billing_cadence: datetime.timedelta = rest_field(name="billingCadence", visibility=["read"]) + """Billing cadence. Required.""" + pro_rating_config: Optional["_models.ProRatingConfig"] = rest_field(name="proRatingConfig", visibility=["read"]) + """Pro-rating configuration.""" + billing_anchor: datetime.datetime = rest_field(name="billingAnchor", visibility=["read"], format="rfc3339") + """Billing anchor. Required.""" + settlement_mode: Union[str, "_models.BillingSettlementMode"] = rest_field( + name="settlementMode", visibility=["read"] + ) + """Settlement mode. Required. Known values are: \"credit_then_invoice\" and \"credit_only\".""" + alignment: Optional["_models.SubscriptionAlignment"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Alignment details enriched with the current billing period.""" + phases: list["_models.SubscriptionPhaseExpanded"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The phases of the subscription. Required.""" + + @overload + def __init__( + self, + *, + name: str, + active_from: datetime.datetime, + customer_id: str, + currency: str, + phases: list["_models.SubscriptionPhaseExpanded"], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + plan: Optional["_models.PlanReference"] = None, + alignment: Optional["_models.SubscriptionAlignment"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionItem(_Model): + """The actual contents of the Subscription, what the user gets, what they pay, etc... + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar active_from: The cadence start of the resource. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The cadence end of the resource. + :vartype active_to: ~datetime.datetime + :ivar key: The identifier of the RateCard. + SubscriptionItem/RateCard can be identified, it has a reference: + + + + 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across + versions) + 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version + of a Feature + + 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + + We say "referenced by the Price" regardless of how a price itself is referenced, it + colloquially makes sense to say "paying the same price for the same thing". In practice this + should be derived from what's printed on the invoice line-item. Required. + :vartype key: str + :ivar feature_key: The feature's key (if present). + :vartype feature_key: str + :ivar billing_cadence: Billing cadence. Required. + :vartype billing_cadence: ~datetime.timedelta + :ivar price: Price. Required. Is one of the following types: FlatPriceWithPaymentTerm, + UnitPriceWithCommitments, TieredPriceWithCommitments, DynamicPriceWithCommitments, + PackagePriceWithCommitments + :vartype price: ~openmeter._generated.models.FlatPriceWithPaymentTerm or + ~openmeter._generated.models.UnitPriceWithCommitments or + ~openmeter._generated.models.TieredPriceWithCommitments or + ~openmeter._generated.models.DynamicPriceWithCommitments or + ~openmeter._generated.models.PackagePriceWithCommitments + :ivar discounts: Discounts. + :vartype discounts: ~openmeter._generated.models.Discounts + :ivar included: Describes what access is gained via the SubscriptionItem. + :vartype included: ~openmeter._generated.models.SubscriptionItemIncluded + :ivar tax_config: Tax config. + :vartype tax_config: ~openmeter._generated.models.TaxConfig + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence start of the resource. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The cadence end of the resource.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The identifier of the RateCard. + SubscriptionItem/RateCard can be identified, it has a reference: + + + + 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across + versions) + 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version + of a Feature + + 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + + We say \"referenced by the Price\" regardless of how a price itself is referenced, it + colloquially makes sense to say \"paying the same price for the same thing\". In practice this + should be derived from what's printed on the invoice line-item. Required.""" + feature_key: Optional[str] = rest_field( + name="featureKey", visibility=["read", "create", "update", "delete", "query"] + ) + """The feature's key (if present).""" + billing_cadence: datetime.timedelta = rest_field( + name="billingCadence", visibility=["read", "create", "update", "delete", "query"] + ) + """Billing cadence. Required.""" + price: "_types.RateCardUsageBasedPrice" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Price. Required. Is one of the following types: FlatPriceWithPaymentTerm, + UnitPriceWithCommitments, TieredPriceWithCommitments, DynamicPriceWithCommitments, + PackagePriceWithCommitments""" + discounts: Optional["_models.Discounts"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Discounts.""" + included: Optional["_models.SubscriptionItemIncluded"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Describes what access is gained via the SubscriptionItem.""" + tax_config: Optional["_models.TaxConfig"] = rest_field(name="taxConfig", visibility=["read", "create", "update"]) + """Tax config.""" + + @overload + def __init__( + self, + *, + name: str, + active_from: datetime.datetime, + key: str, + billing_cadence: datetime.timedelta, + price: "_types.RateCardUsageBasedPrice", + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + active_to: Optional[datetime.datetime] = None, + feature_key: Optional[str] = None, + discounts: Optional["_models.Discounts"] = None, + included: Optional["_models.SubscriptionItemIncluded"] = None, + tax_config: Optional["_models.TaxConfig"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionItemIncluded(_Model): + """Included contents like Entitlement, or the Feature. + + :ivar feature: The feature the customer is entitled to use. Required. + :vartype feature: ~openmeter._generated.models.Feature + :ivar entitlement: The entitlement of the Subscription Item. Is one of the following types: + EntitlementMetered, EntitlementStatic, EntitlementBoolean + :vartype entitlement: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + """ + + feature: "_models.Feature" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The feature the customer is entitled to use. Required.""" + entitlement: Optional["_types.Entitlement"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The entitlement of the Subscription Item. Is one of the following types: EntitlementMetered, + EntitlementStatic, EntitlementBoolean""" + + @overload + def __init__( + self, + *, + feature: "_models.Feature", + entitlement: Optional["_types.Entitlement"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionPaginatedResponse(_Model): + """Paginated response. + + :ivar total_count: The total number of items. Required. + :vartype total_count: int + :ivar page: The page index. Required. + :vartype page: int + :ivar page_size: The maximum number of items per page. Required. + :vartype page_size: int + :ivar items_property: The items in the current page. Required. + :vartype items_property: list[~openmeter._generated.models.Subscription] + """ + + total_count: int = rest_field(name="totalCount", visibility=["read", "create", "update", "delete", "query"]) + """The total number of items. Required.""" + page: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The page index. Required.""" + page_size: int = rest_field(name="pageSize", visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of items per page. Required.""" + items_property: list["_models.Subscription"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items in the current page. Required.""" + + @overload + def __init__( + self, + *, + total_count: int, + page: int, + page_size: int, + items_property: list["_models.Subscription"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionPhaseCreate(_Model): + """Subscription phase create input. + + :ivar start_after: Start after. Required. + :vartype start_after: ~datetime.timedelta + :ivar duration: Duration. + :vartype duration: ~datetime.timedelta + :ivar discounts: Discounts. + :vartype discounts: ~openmeter._generated.models.Discounts + :ivar key: A locally unique identifier for the phase. Required. + :vartype key: str + :ivar name: The name of the phase. Required. + :vartype name: str + :ivar description: The description of the phase. + :vartype description: str + """ + + start_after: datetime.timedelta = rest_field( + name="startAfter", visibility=["read", "create", "update", "delete", "query"] + ) + """Start after. Required.""" + duration: Optional[datetime.timedelta] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Duration.""" + discounts: Optional["_models.Discounts"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Discounts.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A locally unique identifier for the phase. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the phase. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the phase.""" + + @overload + def __init__( + self, + *, + start_after: datetime.timedelta, + key: str, + name: str, + duration: Optional[datetime.timedelta] = None, + discounts: Optional["_models.Discounts"] = None, + description: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SubscriptionPhaseExpanded(_Model): + """Expanded subscription phase. + + :ivar id: ID. Required. + :vartype id: str + :ivar name: Display name. Required. + :vartype name: str + :ivar description: Description. + :vartype description: str + :ivar metadata: Metadata. + :vartype metadata: ~openmeter._generated.models.Metadata + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar key: A locally unique identifier for the resource. Required. + :vartype key: str + :ivar discounts: Discounts. + :vartype discounts: ~openmeter._generated.models.Discounts + :ivar active_from: The time from which the phase is active. Required. + :vartype active_from: ~datetime.datetime + :ivar active_to: The until which the Phase is active. + :vartype active_to: ~datetime.datetime + :ivar items_property: The items of the phase. The structure is flattened to better conform to + the Plan API. The timelines are flattened according to the following rules: + + * for the current phase, the `items` contains only the active item for each key + * for past phases, the `items` contains only the last item for each key + * for future phases, the `items` contains only the first version of the item for each key. + Required. + :vartype items_property: list[~openmeter._generated.models.SubscriptionItem] + :ivar item_timelines: Includes all versions of the items on each key, including all edits, + scheduled changes, etc... Required. + :vartype item_timelines: dict[str, list[~openmeter._generated.models.SubscriptionItem]] + """ + + id: str = rest_field(visibility=["read"]) + """ID. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Display name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Metadata.""" + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A locally unique identifier for the resource. Required.""" + discounts: Optional["_models.Discounts"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Discounts.""" + active_from: datetime.datetime = rest_field( + name="activeFrom", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The time from which the phase is active. Required.""" + active_to: Optional[datetime.datetime] = rest_field( + name="activeTo", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The until which the Phase is active.""" + items_property: list["_models.SubscriptionItem"] = rest_field( + name="items", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="items" + ) + """The items of the phase. The structure is flattened to better conform to the Plan API. The + timelines are flattened according to the following rules: + + * for the current phase, the `items` contains only the active item for each key + * for past phases, the `items` contains only the last item for each key + * for future phases, the `items` contains only the first version of the item for each key. + Required.""" + item_timelines: dict[str, list["_models.SubscriptionItem"]] = rest_field( + name="itemTimelines", visibility=["read", "create", "update", "delete", "query"] + ) + """Includes all versions of the items on each key, including all edits, scheduled changes, etc... + Required.""" + + @overload + def __init__( + self, + *, + name: str, + key: str, + active_from: datetime.datetime, + items_property: list["_models.SubscriptionItem"], + item_timelines: dict[str, list["_models.SubscriptionItem"]], + description: Optional[str] = None, + metadata: Optional["_models.Metadata"] = None, + discounts: Optional["_models.Discounts"] = None, + active_to: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TaxConfig(_Model): + """Set of provider specific tax configs. + + :ivar behavior: Tax behavior. Known values are: "inclusive" and "exclusive". + :vartype behavior: str or ~openmeter.models.TaxBehavior + :ivar stripe: Stripe tax config. + :vartype stripe: ~openmeter._generated.models.StripeTaxConfig + :ivar custom_invoicing: Custom invoicing tax config. + :vartype custom_invoicing: ~openmeter._generated.models.CustomInvoicingTaxConfig + :ivar tax_code_id: Tax code ID. + :vartype tax_code_id: str + """ + + behavior: Optional[Union[str, "_models.TaxBehavior"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Tax behavior. Known values are: \"inclusive\" and \"exclusive\".""" + stripe: Optional["_models.StripeTaxConfig"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Stripe tax config.""" + custom_invoicing: Optional["_models.CustomInvoicingTaxConfig"] = rest_field( + name="customInvoicing", visibility=["read", "create", "update", "delete", "query"] + ) + """Custom invoicing tax config.""" + tax_code_id: Optional[str] = rest_field( + name="taxCodeId", visibility=["read", "create", "update", "delete", "query"] + ) + """Tax code ID.""" + + @overload + def __init__( + self, + *, + behavior: Optional[Union[str, "_models.TaxBehavior"]] = None, + stripe: Optional["_models.StripeTaxConfig"] = None, + custom_invoicing: Optional["_models.CustomInvoicingTaxConfig"] = None, + tax_code_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class TieredPriceWithCommitments(_Model): + """Tiered price with spend commitments. + + :ivar type: The type of the price. + + One of: flat, unit, or tiered. Required. TIERED. + :vartype type: str or ~openmeter._generated.models.TIERED + :ivar mode: Mode. Required. Known values are: "volume" and "graduated". + :vartype mode: str or ~openmeter.models.TieredPriceMode + :ivar tiers: Tiers. Required. + :vartype tiers: list[~openmeter._generated.models.PriceTier] + :ivar minimum_amount: Minimum amount. + :vartype minimum_amount: str + :ivar maximum_amount: Maximum amount. + :vartype maximum_amount: str + """ + + type: Literal[PriceType.TIERED] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. + + One of: flat, unit, or tiered. Required. TIERED.""" + mode: Union[str, "_models.TieredPriceMode"] = rest_field(visibility=["read", "create", "update"]) + """Mode. Required. Known values are: \"volume\" and \"graduated\".""" + tiers: list["_models.PriceTier"] = rest_field(visibility=["read", "create", "update"]) + """Tiers. Required.""" + minimum_amount: Optional[str] = rest_field(name="minimumAmount", visibility=["read", "create", "update"]) + """Minimum amount.""" + maximum_amount: Optional[str] = rest_field(name="maximumAmount", visibility=["read", "create", "update"]) + """Maximum amount.""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.TIERED], + mode: Union[str, "_models.TieredPriceMode"], + tiers: list["_models.PriceTier"], + minimum_amount: Optional[str] = None, + maximum_amount: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UnauthorizedProblemResponse(UnexpectedProblemResponse): + """The request has not been applied because it lacks valid authentication credentials for the + target resource. + + :ivar type: Type contains a URI that identifies the problem type. Required. + :vartype type: str + :ivar title: A a short, human-readable summary of the problem type. Required. + :vartype title: str + :ivar status: The HTTP status code generated by the origin server for this occurrence of the + problem. + :vartype status: int + :ivar detail: A human-readable explanation specific to this occurrence of the problem. + Required. + :vartype detail: str + :ivar instance: A URI reference that identifies the specific occurrence of the problem. + Required. + :vartype instance: str + :ivar extensions: Additional properties specific to the problem type may be present. + :vartype extensions: dict[str, any] + """ + + @overload + def __init__( + self, + *, + type: str, + title: str, + detail: str, + instance: str, + status: Optional[int] = None, + extensions: Optional[dict[str, Any]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UnitPrice(_Model): + """Unit price. + + :ivar type: The type of the price. Required. UNIT. + :vartype type: str or ~openmeter._generated.models.UNIT + :ivar amount: The amount of the unit price. Required. + :vartype amount: str + """ + + type: Literal[PriceType.UNIT] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. Required. UNIT.""" + amount: str = rest_field(visibility=["read", "create", "update"]) + """The amount of the unit price. Required.""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.UNIT], + amount: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UnitPriceWithCommitments(_Model): + """Unit price with spend commitments. + + :ivar type: The type of the price. Required. UNIT. + :vartype type: str or ~openmeter._generated.models.UNIT + :ivar amount: The amount of the unit price. Required. + :vartype amount: str + :ivar minimum_amount: Minimum amount. + :vartype minimum_amount: str + :ivar maximum_amount: Maximum amount. + :vartype maximum_amount: str + """ + + type: Literal[PriceType.UNIT] = rest_field(visibility=["read", "create", "update"]) + """The type of the price. Required. UNIT.""" + amount: str = rest_field(visibility=["read", "create", "update"]) + """The amount of the unit price. Required.""" + minimum_amount: Optional[str] = rest_field(name="minimumAmount", visibility=["read", "create", "update"]) + """Minimum amount.""" + maximum_amount: Optional[str] = rest_field(name="maximumAmount", visibility=["read", "create", "update"]) + """Maximum amount.""" + + @overload + def __init__( + self, + *, + type: Literal[PriceType.UNIT], + amount: str, + minimum_amount: Optional[str] = None, + maximum_amount: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ValidationError(_Model): + """Validation errors providing detailed description of the issue. + + :ivar field: The path to the field. Required. + :vartype field: str + :ivar code: The machine readable description of the error. Required. + :vartype code: str + :ivar message: The human readable description of the error. Required. + :vartype message: str + :ivar attributes: Additional attributes. + :vartype attributes: ~openmeter._generated.models.Annotations + """ + + field: str = rest_field(visibility=["read"]) + """The path to the field. Required.""" + code: str = rest_field(visibility=["read"]) + """The machine readable description of the error. Required.""" + message: str = rest_field(visibility=["read"]) + """The human readable description of the error. Required.""" + attributes: Optional["_models.Annotations"] = rest_field(visibility=["read"]) + """Additional attributes.""" + + +class ValidationIssue(_Model): + """ValidationIssue captures any validation issues related to the invoice. + + Issues with severity "critical" will prevent the invoice from being issued. + + :ivar created_at: Creation Time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: Last Update Time. Required. + :vartype updated_at: ~datetime.datetime + :ivar deleted_at: Deletion Time. + :vartype deleted_at: ~datetime.datetime + :ivar id: ID of the charge or discount. Required. + :vartype id: str + :ivar severity: The severity of the issue. Required. Known values are: "critical" and + "warning". + :vartype severity: str or ~openmeter.models.ValidationIssueSeverity + :ivar field: The field that the issue is related to, if available in JSON path format. + :vartype field: str + :ivar code: Machine indentifiable code for the issue, if available. + :vartype code: str + :ivar component: Component reporting the issue. Required. + :vartype component: str + :ivar message: A human-readable description of the issue. Required. + :vartype message: str + :ivar metadata: Additional context for the issue. + :vartype metadata: ~openmeter._generated.models.Metadata + """ + + created_at: datetime.datetime = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """Creation Time. Required.""" + updated_at: datetime.datetime = rest_field(name="updatedAt", visibility=["read"], format="rfc3339") + """Last Update Time. Required.""" + deleted_at: Optional[datetime.datetime] = rest_field(name="deletedAt", visibility=["read"], format="rfc3339") + """Deletion Time.""" + id: str = rest_field(visibility=["read"]) + """ID of the charge or discount. Required.""" + severity: Union[str, "_models.ValidationIssueSeverity"] = rest_field(visibility=["read"]) + """The severity of the issue. Required. Known values are: \"critical\" and \"warning\".""" + field: Optional[str] = rest_field(visibility=["read"]) + """The field that the issue is related to, if available in JSON path format.""" + code: Optional[str] = rest_field(visibility=["read"]) + """Machine indentifiable code for the issue, if available.""" + component: str = rest_field(visibility=["read"]) + """Component reporting the issue. Required.""" + message: str = rest_field(visibility=["read"]) + """A human-readable description of the issue. Required.""" + metadata: Optional["_models.Metadata"] = rest_field(visibility=["read"]) + """Additional context for the issue.""" + + +class VoidInvoiceAction(_Model): + """InvoiceVoidAction describes how to handle the voided line items. + + :ivar percentage: How much of the total line items to be voided? (e.g. 100% means all charges + are voided). Required. + :vartype percentage: float + :ivar action: The action to take on the line items. Required. Is either a + VoidInvoiceLineDiscardAction type or a VoidInvoiceLinePendingAction type. + :vartype action: ~openmeter._generated.models.VoidInvoiceLineDiscardAction or + ~openmeter._generated.models.VoidInvoiceLinePendingAction + """ + + percentage: float = rest_field(visibility=["create"]) + """How much of the total line items to be voided? (e.g. 100% means all charges are voided). + Required.""" + action: "_types.VoidInvoiceLineAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The action to take on the line items. Required. Is either a VoidInvoiceLineDiscardAction type + or a VoidInvoiceLinePendingAction type.""" + + @overload + def __init__( + self, + *, + percentage: float, + action: "_types.VoidInvoiceLineAction", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VoidInvoiceActionInput(_Model): + """Request to void an invoice. + + :ivar action: The action to take on the voided line items. Required. + :vartype action: ~openmeter._generated.models.VoidInvoiceAction + :ivar reason: The reason for voiding the invoice. Required. + :vartype reason: str + :ivar overrides: Per line item overrides for the action. + + If not specified, the ``action`` will be applied to all line items. + :vartype overrides: list[~openmeter._generated.models.VoidInvoiceActionLineOverride] + """ + + action: "_models.VoidInvoiceAction" = rest_field(visibility=["create"]) + """The action to take on the voided line items. Required.""" + reason: str = rest_field(visibility=["create"]) + """The reason for voiding the invoice. Required.""" + overrides: Optional[list["_models.VoidInvoiceActionLineOverride"]] = rest_field(visibility=["create"]) + """Per line item overrides for the action. + + If not specified, the ``action`` will be applied to all line items.""" + + @overload + def __init__( + self, + *, + action: "_models.VoidInvoiceAction", + reason: str, + overrides: Optional[list["_models.VoidInvoiceActionLineOverride"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VoidInvoiceActionLineOverride(_Model): + """VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when + voiding. + + :ivar line_id: The line item ID to override. Required. + :vartype line_id: str + :ivar action: The action to take on the line item. Required. + :vartype action: ~openmeter._generated.models.VoidInvoiceAction + """ + + line_id: str = rest_field(name="lineId", visibility=["create"]) + """The line item ID to override. Required.""" + action: "_models.VoidInvoiceAction" = rest_field(visibility=["create"]) + """The action to take on the line item. Required.""" + + @overload + def __init__( + self, + *, + line_id: str, + action: "_models.VoidInvoiceAction", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VoidInvoiceLineDiscardAction(_Model): + """VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. + + :ivar type: The action to take on the line item. Required. The line items will never be charged + for again. + :vartype type: str or ~openmeter._generated.models.DISCARD + """ + + type: Literal[VoidInvoiceLineActionType.DISCARD] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The action to take on the line item. Required. The line items will never be charged for again.""" + + @overload + def __init__( + self, + *, + type: Literal[VoidInvoiceLineActionType.DISCARD], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VoidInvoiceLinePendingAction(_Model): + """VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. + + :ivar type: The action to take on the line item. Required. Queue the line items into the + pending state, they will be included in the next invoice. (We want to generate an invoice right + now). + :vartype type: str or ~openmeter._generated.models.PENDING + :ivar next_invoice_at: The time at which the line item should be invoiced again. + + If not provided, the line item will be re-invoiced now. + :vartype next_invoice_at: ~datetime.datetime + """ + + type: Literal[VoidInvoiceLineActionType.PENDING] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The action to take on the line item. Required. Queue the line items into the pending state, + they will be included in the next invoice. (We want to generate an invoice right now).""" + next_invoice_at: Optional[datetime.datetime] = rest_field( + name="nextInvoiceAt", visibility=["create"], format="rfc3339" + ) + """The time at which the line item should be invoiced again. + + If not provided, the line item will be re-invoiced now.""" + + @overload + def __init__( + self, + *, + type: Literal[VoidInvoiceLineActionType.PENDING], + next_invoice_at: Optional[datetime.datetime] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class WindowedBalanceHistory(_Model): + """The windowed balance history. + + :ivar windowed_history: The windowed balance history. + + * It only returns rows for windows where there was usage. + * The windows are inclusive at their start and exclusive at their end. + * The last window may be smaller than the window size and is inclusive at both ends. + Required. + :vartype windowed_history: list[~openmeter._generated.models.BalanceHistoryWindow] + :ivar burndown_history: Grant burndown history. Required. + :vartype burndown_history: list[~openmeter._generated.models.GrantBurnDownHistorySegment] + """ + + windowed_history: list["_models.BalanceHistoryWindow"] = rest_field( + name="windowedHistory", visibility=["read", "create", "update", "delete", "query"] + ) + """The windowed balance history. + + * It only returns rows for windows where there was usage. + * The windows are inclusive at their start and exclusive at their end. + * The last window may be smaller than the window size and is inclusive at both ends. + Required.""" + burndown_history: list["_models.GrantBurnDownHistorySegment"] = rest_field( + name="burndownHistory", visibility=["read", "create", "update", "delete", "query"] + ) + """Grant burndown history. Required.""" + + @overload + def __init__( + self, + *, + windowed_history: list["_models.BalanceHistoryWindow"], + burndown_history: list["_models.GrantBurnDownHistorySegment"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/api/client/python/openmeter/_generated/models/_patch.py b/api/client/python/openmeter/_generated/models/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b208fb11fbc2e1955c43275aa4e1482dec7e5d6f --- /dev/null +++ b/api/client/python/openmeter/_generated/models/_patch.py @@ -0,0 +1,17 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/api/client/python/openmeter/_generated/operations/__init__.py b/api/client/python/openmeter/_generated/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..291d5bb58714572fb0a528e2dd2de5b69e9865e7 --- /dev/null +++ b/api/client/python/openmeter/_generated/operations/__init__.py @@ -0,0 +1,93 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import PortalOperations # type: ignore +from ._operations import AppsOperations # type: ignore +from ._operations import AppStripeOperations # type: ignore +from ._operations import CustomerAppsOperations # type: ignore +from ._operations import CustomersOperations # type: ignore +from ._operations import FeaturesOperations # type: ignore +from ._operations import PlansOperations # type: ignore +from ._operations import PlanAddonsOperations # type: ignore +from ._operations import AddonsOperations # type: ignore +from ._operations import SubscriptionsOperations # type: ignore +from ._operations import SubscriptionAddonsOperations # type: ignore +from ._operations import EntitlementsOperations # type: ignore +from ._operations import GrantsOperations # type: ignore +from ._operations import SubjectsOperations # type: ignore +from ._operations import CustomerOperations # type: ignore +from ._operations import CustomerEntitlementOperations # type: ignore +from ._operations import CustomerStripeOperations # type: ignore +from ._operations import MarketplaceOperations # type: ignore +from ._operations import AppCustomInvoicingOperations # type: ignore +from ._operations import EventsOperations # type: ignore +from ._operations import EventsV2Operations # type: ignore +from ._operations import MetersOperations # type: ignore +from ._operations import SubjectsOperations # type: ignore +from ._operations import DebugOperations # type: ignore +from ._operations import NotificationChannelsOperations # type: ignore +from ._operations import NotificationRulesOperations # type: ignore +from ._operations import NotificationEventsOperations # type: ignore +from ._operations import EntitlementsV2Operations # type: ignore +from ._operations import CustomerEntitlementsV2Operations # type: ignore +from ._operations import CustomerEntitlementV2Operations # type: ignore +from ._operations import GrantsV2Operations # type: ignore +from ._operations import BillingProfilesOperations # type: ignore +from ._operations import CustomerOverridesOperations # type: ignore +from ._operations import InvoicesOperations # type: ignore +from ._operations import InvoiceOperations # type: ignore +from ._operations import CustomerInvoiceOperations # type: ignore +from ._operations import ProgressOperations # type: ignore +from ._operations import CurrenciesOperations # type: ignore + +from ._patch import __all__ as _patch_all +from ._patch import * +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "PortalOperations", + "AppsOperations", + "AppStripeOperations", + "CustomerAppsOperations", + "CustomersOperations", + "FeaturesOperations", + "PlansOperations", + "PlanAddonsOperations", + "AddonsOperations", + "SubscriptionsOperations", + "SubscriptionAddonsOperations", + "EntitlementsOperations", + "GrantsOperations", + "SubjectsOperations", + "CustomerOperations", + "CustomerEntitlementOperations", + "CustomerStripeOperations", + "MarketplaceOperations", + "AppCustomInvoicingOperations", + "EventsOperations", + "EventsV2Operations", + "MetersOperations", + "SubjectsOperations", + "DebugOperations", + "NotificationChannelsOperations", + "NotificationRulesOperations", + "NotificationEventsOperations", + "EntitlementsV2Operations", + "CustomerEntitlementsV2Operations", + "CustomerEntitlementV2Operations", + "GrantsV2Operations", + "BillingProfilesOperations", + "CustomerOverridesOperations", + "InvoicesOperations", + "InvoiceOperations", + "CustomerInvoiceOperations", + "ProgressOperations", + "CurrenciesOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore +_patch_sdk() diff --git a/api/client/python/openmeter/_generated/operations/_operations.py b/api/client/python/openmeter/_generated/operations/_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..04249b9fd8a80147f806b3ad81c1a29fc75e53bc --- /dev/null +++ b/api/client/python/openmeter/_generated/operations/_operations.py @@ -0,0 +1,24328 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +from collections.abc import MutableMapping +import datetime +from io import IOBase +import json +from typing import Any, Callable, IO, Optional, TYPE_CHECKING, TypeVar, Union, overload + +from corehttp.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from corehttp.paging import ItemPaged +from corehttp.rest import HttpRequest, HttpResponse +from corehttp.runtime import PipelineClient +from corehttp.runtime.pipeline import PipelineResponse +from corehttp.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import OpenMeterClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Deserializer, Serializer + +if TYPE_CHECKING: + from .. import _types +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] +_Unset: Any = object() +List = list + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_apps_list_request( + *, page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/apps" + + # Construct parameters + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_apps_get_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/apps/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_apps_update_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/apps/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_apps_uninstall_request(id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/apps/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_app_stripe_webhook_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/apps/{id}/stripe/webhook" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_app_stripe_update_stripe_api_key_request( # pylint: disable=name-too-long + id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/apps/{id}/stripe/api-key" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_app_stripe_create_checkout_session_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/stripe/checkout/sessions" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_customer_apps_list_app_data_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + type: Optional[Union[str, _models.AppType]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/apps" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if type is not None: + _params["type"] = _SERIALIZER.query("type", type, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_apps_upsert_app_data_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/apps" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_customer_apps_delete_app_data_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", app_id: str, **kwargs: Any +) -> HttpRequest: + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/apps/{appId}" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "appId": _SERIALIZER.url("app_id", app_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_customers_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_customers_list_request( + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.CustomerOrderBy]] = None, + include_deleted: Optional[bool] = None, + key: Optional[str] = None, + name: Optional[str] = None, + primary_email: Optional[str] = None, + subject: Optional[str] = None, + plan_key: Optional[str] = None, + expand: Optional[List[Union[str, _models.CustomerExpand]]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers" + + # Construct parameters + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if key is not None: + _params["key"] = _SERIALIZER.query("key", key, "str") + if name is not None: + _params["name"] = _SERIALIZER.query("name", name, "str") + if primary_email is not None: + _params["primaryEmail"] = _SERIALIZER.query("primary_email", primary_email, "str") + if subject is not None: + _params["subject"] = _SERIALIZER.query("subject", subject, "str") + if plan_key is not None: + _params["planKey"] = _SERIALIZER.query("plan_key", plan_key, "str") + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customers_get_request( + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + expand: Optional[List[Union[str, _models.CustomerExpand]]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customers_update_request(customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_customers_delete_request(customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_customers_list_customer_subscriptions_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + status: Optional[List[Union[str, _models.SubscriptionStatus]]] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.CustomerSubscriptionOrderBy]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/subscriptions" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if status is not None: + _params["status"] = [_SERIALIZER.query("status", q, "str") if q is not None else "" for q in status] + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_list_request( + *, + meter_slug: Optional[List[str]] = None, + include_archived: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.FeatureOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/features" + + # Construct parameters + if meter_slug is not None: + _params["meterSlug"] = [_SERIALIZER.query("meter_slug", q, "str") if q is not None else "" for q in meter_slug] + if include_archived is not None: + _params["includeArchived"] = _SERIALIZER.query("include_archived", include_archived, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if offset is not None: + _params["offset"] = _SERIALIZER.query("offset", offset, "int") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_features_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/features" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_features_get_request(feature_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/features/{featureId}" + path_format_arguments = { + "featureId": _SERIALIZER.url("feature_id", feature_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_features_delete_request(feature_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/features/{featureId}" + path_format_arguments = { + "featureId": _SERIALIZER.url("feature_id", feature_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_plans_list_request( + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + status: Optional[List[Union[str, _models.PlanStatus]]] = None, + currency: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.PlanOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans" + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if id is not None: + _params["id"] = [_SERIALIZER.query("id", q, "str") if q is not None else "" for q in id] + if key is not None: + _params["key"] = [_SERIALIZER.query("key", q, "str") if q is not None else "" for q in key] + if key_version is not None: + _params["keyVersion"] = _SERIALIZER.query("key_version", key_version, "{[int]}") + if status is not None: + _params["status"] = [_SERIALIZER.query("status", q, "str") if q is not None else "" for q in status] + if currency is not None: + _params["currency"] = [_SERIALIZER.query("currency", q, "str") if q is not None else "" for q in currency] + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_plans_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_plans_update_request(plan_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_plans_get_request(plan_id: str, *, include_latest: Optional[bool] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_latest is not None: + _params["includeLatest"] = _SERIALIZER.query("include_latest", include_latest, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_plans_delete_request(plan_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/plans/{planId}" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_plans_publish_request(plan_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}/publish" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_plans_archive_request(plan_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}/archive" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_plans_next_request(plan_id_or_key: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planIdOrKey}/next" + path_format_arguments = { + "planIdOrKey": _SERIALIZER.url("plan_id_or_key", plan_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_plan_addons_list_request( + plan_id: str, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.PlanAddonOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}/addons" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if id is not None: + _params["id"] = [_SERIALIZER.query("id", q, "str") if q is not None else "" for q in id] + if key is not None: + _params["key"] = [_SERIALIZER.query("key", q, "str") if q is not None else "" for q in key] + if key_version is not None: + _params["keyVersion"] = _SERIALIZER.query("key_version", key_version, "{[int]}") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_plan_addons_create_request(plan_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}/addons" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_plan_addons_update_request(plan_id: str, plan_addon_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}/addons/{planAddonId}" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + "planAddonId": _SERIALIZER.url("plan_addon_id", plan_addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_plan_addons_get_request(plan_id: str, plan_addon_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/plans/{planId}/addons/{planAddonId}" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + "planAddonId": _SERIALIZER.url("plan_addon_id", plan_addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_plan_addons_delete_request(plan_id: str, plan_addon_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/plans/{planId}/addons/{planAddonId}" + path_format_arguments = { + "planId": _SERIALIZER.url("plan_id", plan_id, "str"), + "planAddonId": _SERIALIZER.url("plan_addon_id", plan_addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_addons_list_request( + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + status: Optional[List[Union[str, _models.AddonStatus]]] = None, + currency: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.AddonOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/addons" + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if id is not None: + _params["id"] = [_SERIALIZER.query("id", q, "str") if q is not None else "" for q in id] + if key is not None: + _params["key"] = [_SERIALIZER.query("key", q, "str") if q is not None else "" for q in key] + if key_version is not None: + _params["keyVersion"] = _SERIALIZER.query("key_version", key_version, "{[int]}") + if status is not None: + _params["status"] = [_SERIALIZER.query("status", q, "str") if q is not None else "" for q in status] + if currency is not None: + _params["currency"] = [_SERIALIZER.query("currency", q, "str") if q is not None else "" for q in currency] + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_addons_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/addons" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_addons_update_request(addon_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/addons/{addonId}" + path_format_arguments = { + "addonId": _SERIALIZER.url("addon_id", addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_addons_get_request(addon_id: str, *, include_latest: Optional[bool] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/addons/{addonId}" + path_format_arguments = { + "addonId": _SERIALIZER.url("addon_id", addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_latest is not None: + _params["includeLatest"] = _SERIALIZER.query("include_latest", include_latest, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_addons_delete_request(addon_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/addons/{addonId}" + path_format_arguments = { + "addonId": _SERIALIZER.url("addon_id", addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_addons_publish_request(addon_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/addons/{addonId}/publish" + path_format_arguments = { + "addonId": _SERIALIZER.url("addon_id", addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_addons_archive_request(addon_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/addons/{addonId}/archive" + path_format_arguments = { + "addonId": _SERIALIZER.url("addon_id", addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_get_expanded_request( + subscription_id: str, *, at: Optional[datetime.datetime] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if at is not None: + _params["at"] = _SERIALIZER.query("at", at, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subscriptions_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_edit_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_change_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/change" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_migrate_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/migrate" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_restore_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/restore" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_cancel_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/cancel" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_unschedule_cancelation_request( # pylint: disable=name-too-long + subscription_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/unschedule-cancelation" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscriptions_delete_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_subscription_addons_create_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/addons" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subscription_addons_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/addons" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subscription_addons_get_request( + subscription_id: str, subscription_addon_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "subscriptionAddonId": _SERIALIZER.url("subscription_addon_id", subscription_addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subscription_addons_update_request( + subscription_id: str, subscription_addon_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}" + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "subscriptionAddonId": _SERIALIZER.url("subscription_addon_id", subscription_addon_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, headers=_headers, **kwargs) + + +def build_entitlements_list_request( + *, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + entitlement_type: Optional[List[Union[str, _models.EntitlementType]]] = None, + exclude_inactive: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/entitlements" + + # Construct parameters + if feature is not None: + _params["feature"] = [_SERIALIZER.query("feature", q, "str") if q is not None else "" for q in feature] + if subject is not None: + _params["subject"] = [_SERIALIZER.query("subject", q, "str") if q is not None else "" for q in subject] + if entitlement_type is not None: + _params["entitlementType"] = [ + _SERIALIZER.query("entitlement_type", q, "str") if q is not None else "" for q in entitlement_type + ] + if exclude_inactive is not None: + _params["excludeInactive"] = _SERIALIZER.query("exclude_inactive", exclude_inactive, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if offset is not None: + _params["offset"] = _SERIALIZER.query("offset", offset, "int") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_entitlements_get_request(entitlement_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/entitlements/{entitlementId}" + path_format_arguments = { + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_grants_list_request( + *, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json, application/json") + + # Construct URL + _url = "/api/v1/grants" + + # Construct parameters + if feature is not None: + _params["feature"] = [_SERIALIZER.query("feature", q, "str") if q is not None else "" for q in feature] + if subject is not None: + _params["subject"] = [_SERIALIZER.query("subject", q, "str") if q is not None else "" for q in subject] + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if offset is not None: + _params["offset"] = _SERIALIZER.query("offset", offset, "int") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_grants_delete_request(grant_id: str, *, at: Optional[datetime.datetime] = None, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/api/v1/grants/{grantId}" + path_format_arguments = { + "grantId": _SERIALIZER.url("grant_id", grant_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if at is not None: + _params["at"] = _SERIALIZER.query("at", at, "iso-8601") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_subjects_post_request(subject_id_or_key: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_list_request( + subject_id_or_key: str, *, include_deleted: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_get_request(subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subjects_delete_request(subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_subjects_override_request( + subject_id_or_key: str, entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_subjects_get_grants_request( + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_create_grant_request( + subject_id_or_key: str, entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_get_entitlement_value_request( # pylint: disable=name-too-long + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if time is not None: + _params["time"] = _SERIALIZER.query("time", time, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_get_entitlement_history_request( # pylint: disable=name-too-long + subject_id_or_key: str, + entitlement_id: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_reset_request(subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subjects_get_request(subject_id_or_key: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subjects_upsert_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_delete_request(subject_id_or_key: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_customer_get_customer_access_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/access" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_customer_entitlement_get_customer_entitlement_value_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "featureKey": _SERIALIZER.url("feature_key", feature_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if time is not None: + _params["time"] = _SERIALIZER.query("time", time, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_stripe_get_request(customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/stripe" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_customer_stripe_upsert_request(customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/stripe" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_customer_stripe_create_portal_session_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/customers/{customerIdOrKey}/stripe/portal" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_marketplace_list_request( + *, page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/marketplace/listings" + + # Construct parameters + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_marketplace_get_request(type: Union[str, _models.AppType], **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/marketplace/listings/{type}" + path_format_arguments = { + "type": _SERIALIZER.url("type", type, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_marketplace_get_o_auth2_install_url_request( # pylint: disable=name-too-long + type: Union[str, _models.AppType], **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/marketplace/listings/{type}/install/oauth2" + path_format_arguments = { + "type": _SERIALIZER.url("type", type, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_marketplace_authorize_o_auth2_install_request( # pylint: disable=name-too-long + type: Union[str, _models.AppType], + *, + state: Optional[str] = None, + code: Optional[str] = None, + error: Optional[Union[str, _models.OAuth2AuthorizationCodeGrantErrorType]] = None, + error_description: Optional[str] = None, + error_uri: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + # Construct URL + _url = "/api/v1/marketplace/listings/{type}/install/oauth2/authorize" + path_format_arguments = { + "type": _SERIALIZER.url("type", type, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if state is not None: + _params["state"] = _SERIALIZER.query("state", state, "str") + if code is not None: + _params["code"] = _SERIALIZER.query("code", code, "str") + if error is not None: + _params["error"] = _SERIALIZER.query("error", error, "str") + if error_description is not None: + _params["error_description"] = _SERIALIZER.query("error_description", error_description, "str") + if error_uri is not None: + _params["error_uri"] = _SERIALIZER.query("error_uri", error_uri, "str") + + return HttpRequest(method="GET", url=_url, params=_params, **kwargs) + + +def build_marketplace_install_with_api_key_request( # pylint: disable=name-too-long + type: Union[str, _models.AppType], **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/marketplace/listings/{type}/install/apikey" + path_format_arguments = { + "type": _SERIALIZER.url("type", type, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_marketplace_install_request(type: Union[str, _models.AppType], **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/marketplace/listings/{type}/install" + path_format_arguments = { + "type": _SERIALIZER.url("type", type, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_app_custom_invoicing_draft_syncronized_request( # pylint: disable=name-too-long + invoice_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_app_custom_invoicing_finalized_request( # pylint: disable=name-too-long + invoice_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_app_custom_invoicing_payment_status_request( # pylint: disable=name-too-long + invoice_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/apps/custom-invoicing/{invoiceId}/payment/status" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_events_list_request( + *, + client_id: Optional[str] = None, + ingested_at_from: Optional[datetime.datetime] = None, + ingested_at_to: Optional[datetime.datetime] = None, + id: Optional[str] = None, + subject: Optional[str] = None, + customer_id: Optional[List[str]] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + limit: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/events" + + # Construct parameters + if client_id is not None: + _params["clientId"] = _SERIALIZER.query("client_id", client_id, "str") + if ingested_at_from is not None: + _params["ingestedAtFrom"] = _SERIALIZER.query("ingested_at_from", ingested_at_from, "iso-8601") + if ingested_at_to is not None: + _params["ingestedAtTo"] = _SERIALIZER.query("ingested_at_to", ingested_at_to, "iso-8601") + if id is not None: + _params["id"] = _SERIALIZER.query("id", id, "str") + if subject is not None: + _params["subject"] = _SERIALIZER.query("subject", subject, "str") + if customer_id is not None: + _params["customerId"] = [ + _SERIALIZER.query("customer_id", q, "str") if q is not None else "" for q in customer_id + ] + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_events_ingest_event_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + # Construct URL + _url = "/api/v1/events" + + # Construct headers + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_events_ingest_events_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + # Construct URL + _url = "/api/v1/events" + + # Construct headers + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_events_ingest_events_json_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + # Construct URL + _url = "/api/v1/events" + + # Construct headers + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_events_v2_list_request( + *, + cursor: Optional[str] = None, + limit: Optional[int] = None, + client_id: Optional[str] = None, + filter: Optional[_models.ListRequestFilter] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/events" + + # Construct parameters + if cursor is not None: + _params["cursor"] = _SERIALIZER.query("cursor", cursor, "str") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if client_id is not None: + _params["clientId"] = _SERIALIZER.query("client_id", client_id, "str") + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", json.dumps(filter), "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_meters_list_request( + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.MeterOrderBy]] = None, + include_deleted: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters" + + # Construct parameters + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_meters_get_request(meter_id_or_slug: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_meters_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_meters_update_request(meter_id_or_slug: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_meters_delete_request(meter_id_or_slug: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_meters_query_json_request( + meter_id_or_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[List[str]] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}/query" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if client_id is not None: + _params["clientId"] = _SERIALIZER.query("client_id", client_id, "str") + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + if window_size is not None: + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + if subject is not None: + _params["subject"] = [_SERIALIZER.query("subject", q, "str") if q is not None else "" for q in subject] + if filter_customer_id is not None: + _params["filterCustomerId"] = [ + _SERIALIZER.query("filter_customer_id", q, "str") if q is not None else "" for q in filter_customer_id + ] + if filter_group_by is not None: + _params["filterGroupBy"] = _SERIALIZER.query("filter_group_by", filter_group_by, "{str}") + if advanced_meter_group_by_filters is not None: + _params["advancedMeterGroupByFilters"] = _SERIALIZER.query( + "advanced_meter_group_by_filters", json.dumps(advanced_meter_group_by_filters), "str" + ) + if group_by is not None: + _params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_meters_query_csv_request( + meter_id_or_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[List[str]] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "text/csv") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}/query" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if client_id is not None: + _params["clientId"] = _SERIALIZER.query("client_id", client_id, "str") + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + if window_size is not None: + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + if subject is not None: + _params["subject"] = [_SERIALIZER.query("subject", q, "str") if q is not None else "" for q in subject] + if filter_customer_id is not None: + _params["filterCustomerId"] = [ + _SERIALIZER.query("filter_customer_id", q, "str") if q is not None else "" for q in filter_customer_id + ] + if filter_group_by is not None: + _params["filterGroupBy"] = _SERIALIZER.query("filter_group_by", filter_group_by, "{str}") + if advanced_meter_group_by_filters is not None: + _params["advancedMeterGroupByFilters"] = _SERIALIZER.query( + "advanced_meter_group_by_filters", json.dumps(advanced_meter_group_by_filters), "str" + ) + if group_by is not None: + _params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_meters_query_request(meter_id_or_slug: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}/query" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_meters_query_csv_post_request(meter_id_or_slug: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "text/csv") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}/query" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_meters_list_subjects_request( + meter_id_or_slug: str, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}/subjects" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_meters_list_group_by_values_request( # pylint: disable=name-too-long + meter_id_or_slug: str, + group_by_key: str, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values" + path_format_arguments = { + "meterIdOrSlug": _SERIALIZER.url("meter_id_or_slug", meter_id_or_slug, "str"), + "groupByKey": _SERIALIZER.url("group_by_key", group_by_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_post_request(subject_id_or_key: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_list_request( + subject_id_or_key: str, *, include_deleted: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_get_request(subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subjects_delete_request(subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_subjects_override_request( + subject_id_or_key: str, entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_subjects_get_grants_request( + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_create_grant_request( + subject_id_or_key: str, entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_get_entitlement_value_request( # pylint: disable=name-too-long + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if time is not None: + _params["time"] = _SERIALIZER.query("time", time, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_get_entitlement_history_request( # pylint: disable=name-too-long + subject_id_or_key: str, + entitlement_id: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_subjects_reset_request(subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subjects_get_request(subject_id_or_key: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_subjects_upsert_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/subjects" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_subjects_delete_request(subject_id_or_key: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/subjects/{subjectIdOrKey}" + path_format_arguments = { + "subjectIdOrKey": _SERIALIZER.url("subject_id_or_key", subject_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_debug_metrics_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "text/plain") + + # Construct URL + _url = "/api/v1/debug/metrics" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_notification_channels_list_request( + *, + include_deleted: Optional[bool] = None, + include_disabled: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationChannelOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/channels" + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if include_disabled is not None: + _params["includeDisabled"] = _SERIALIZER.query("include_disabled", include_disabled, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_notification_channels_create_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/channels" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_notification_channels_update_request( # pylint: disable=name-too-long + channel_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/channels/{channelId}" + path_format_arguments = { + "channelId": _SERIALIZER.url("channel_id", channel_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_notification_channels_get_request(channel_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/channels/{channelId}" + path_format_arguments = { + "channelId": _SERIALIZER.url("channel_id", channel_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_notification_channels_delete_request( # pylint: disable=name-too-long + channel_id: str, **kwargs: Any +) -> HttpRequest: + # Construct URL + _url = "/api/v1/notification/channels/{channelId}" + path_format_arguments = { + "channelId": _SERIALIZER.url("channel_id", channel_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_notification_rules_list_request( + *, + include_deleted: Optional[bool] = None, + include_disabled: Optional[bool] = None, + feature: Optional[List[str]] = None, + channel: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationRuleOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/rules" + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if include_disabled is not None: + _params["includeDisabled"] = _SERIALIZER.query("include_disabled", include_disabled, "bool") + if feature is not None: + _params["feature"] = [_SERIALIZER.query("feature", q, "str") if q is not None else "" for q in feature] + if channel is not None: + _params["channel"] = [_SERIALIZER.query("channel", q, "str") if q is not None else "" for q in channel] + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_notification_rules_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/rules" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_notification_rules_update_request(rule_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/rules/{ruleId}" + path_format_arguments = { + "ruleId": _SERIALIZER.url("rule_id", rule_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_notification_rules_get_request(rule_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/rules/{ruleId}" + path_format_arguments = { + "ruleId": _SERIALIZER.url("rule_id", rule_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_notification_rules_delete_request(rule_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/notification/rules/{ruleId}" + path_format_arguments = { + "ruleId": _SERIALIZER.url("rule_id", rule_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_notification_rules_test_request(rule_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/rules/{ruleId}/test" + path_format_arguments = { + "ruleId": _SERIALIZER.url("rule_id", rule_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_notification_events_list_request( + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + rule: Optional[List[str]] = None, + channel: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationEventOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/events" + + # Construct parameters + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + if feature is not None: + _params["feature"] = [_SERIALIZER.query("feature", q, "str") if q is not None else "" for q in feature] + if subject is not None: + _params["subject"] = [_SERIALIZER.query("subject", q, "str") if q is not None else "" for q in subject] + if rule is not None: + _params["rule"] = [_SERIALIZER.query("rule", q, "str") if q is not None else "" for q in rule] + if channel is not None: + _params["channel"] = [_SERIALIZER.query("channel", q, "str") if q is not None else "" for q in channel] + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_notification_events_get_request(event_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/notification/events/{eventId}" + path_format_arguments = { + "eventId": _SERIALIZER.url("event_id", event_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_notification_events_resend_request(event_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/notification/events/{eventId}/resend" + path_format_arguments = { + "eventId": _SERIALIZER.url("event_id", event_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_entitlements_v2_list_request( + *, + feature: Optional[List[str]] = None, + customer_keys: Optional[List[str]] = None, + customer_ids: Optional[List[str]] = None, + entitlement_type: Optional[List[Union[str, _models.EntitlementType]]] = None, + exclude_inactive: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/entitlements" + + # Construct parameters + if feature is not None: + _params["feature"] = [_SERIALIZER.query("feature", q, "str") if q is not None else "" for q in feature] + if customer_keys is not None: + _params["customerKeys"] = [ + _SERIALIZER.query("customer_keys", q, "str") if q is not None else "" for q in customer_keys + ] + if customer_ids is not None: + _params["customerIds"] = [ + _SERIALIZER.query("customer_ids", q, "str") if q is not None else "" for q in customer_ids + ] + if entitlement_type is not None: + _params["entitlementType"] = [ + _SERIALIZER.query("entitlement_type", q, "str") if q is not None else "" for q in entitlement_type + ] + if exclude_inactive is not None: + _params["excludeInactive"] = _SERIALIZER.query("exclude_inactive", exclude_inactive, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if offset is not None: + _params["offset"] = _SERIALIZER.query("offset", offset, "int") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_entitlements_v2_get_request(entitlement_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/entitlements/{entitlementId}" + path_format_arguments = { + "entitlementId": _SERIALIZER.url("entitlement_id", entitlement_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_customer_entitlements_v2_post_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_customer_entitlements_v2_list_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_entitlements_v2_get_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_customer_entitlements_v2_delete_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_customer_entitlements_v2_override_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_customer_entitlement_v2_get_grants_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if offset is not None: + _params["offset"] = _SERIALIZER.query("offset", offset, "int") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_entitlement_v2_create_customer_entitlement_grant_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_customer_entitlement_v2_get_customer_entitlement_value_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if time is not None: + _params["time"] = _SERIALIZER.query("time", time, "iso-8601") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_entitlement_v2_get_customer_entitlement_history_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_entitlement_v2_reset_customer_entitlement_request( # pylint: disable=name-too-long + customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset" + path_format_arguments = { + "customerIdOrKey": _SERIALIZER.url("customer_id_or_key", customer_id_or_key, "str"), + "entitlementIdOrFeatureKey": _SERIALIZER.url( + "entitlement_id_or_feature_key", entitlement_id_or_feature_key, "str" + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_grants_v2_list_request( + *, + feature: Optional[List[str]] = None, + customer: Optional[List["_types.ULIDOrExternalKey"]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v2/grants" + + # Construct parameters + if feature is not None: + _params["feature"] = [_SERIALIZER.query("feature", q, "str") if q is not None else "" for q in feature] + if customer is not None: + _params["customer"] = [_SERIALIZER.query("customer", q, "str") if q is not None else "" for q in customer] + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if offset is not None: + _params["offset"] = _SERIALIZER.query("offset", offset, "int") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_billing_profiles_list_request( + *, + include_archived: Optional[bool] = None, + expand: Optional[List[Union[str, _models.BillingProfileExpand]]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.BillingProfileOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/profiles" + + # Construct parameters + if include_archived is not None: + _params["includeArchived"] = _SERIALIZER.query("include_archived", include_archived, "bool") + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_billing_profiles_create_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/profiles" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_billing_profiles_delete_request(id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/billing/profiles/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_billing_profiles_get_request( + id: str, *, expand: Optional[List[Union[str, _models.BillingProfileExpand]]] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/profiles/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_billing_profiles_update_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/profiles/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_customer_overrides_list_request( + *, + billing_profile: Optional[List[str]] = None, + customers_without_pinned_profile: Optional[bool] = None, + include_all_customers: Optional[bool] = None, + customer_id: Optional[List[str]] = None, + customer_name: Optional[str] = None, + customer_key: Optional[str] = None, + customer_primary_email: Optional[str] = None, + expand: Optional[List[Union[str, _models.BillingProfileCustomerOverrideExpand]]] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.BillingProfileCustomerOverrideOrderBy]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/customers" + + # Construct parameters + if billing_profile is not None: + _params["billingProfile"] = [ + _SERIALIZER.query("billing_profile", q, "str") if q is not None else "" for q in billing_profile + ] + if customers_without_pinned_profile is not None: + _params["customersWithoutPinnedProfile"] = _SERIALIZER.query( + "customers_without_pinned_profile", customers_without_pinned_profile, "bool" + ) + if include_all_customers is not None: + _params["includeAllCustomers"] = _SERIALIZER.query("include_all_customers", include_all_customers, "bool") + if customer_id is not None: + _params["customerId"] = [ + _SERIALIZER.query("customer_id", q, "str") if q is not None else "" for q in customer_id + ] + if customer_name is not None: + _params["customerName"] = _SERIALIZER.query("customer_name", customer_name, "str") + if customer_key is not None: + _params["customerKey"] = _SERIALIZER.query("customer_key", customer_key, "str") + if customer_primary_email is not None: + _params["customerPrimaryEmail"] = _SERIALIZER.query("customer_primary_email", customer_primary_email, "str") + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_overrides_upsert_request(customer_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/customers/{customerId}" + path_format_arguments = { + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_customer_overrides_get_request( + customer_id: str, + *, + expand: Optional[List[Union[str, _models.BillingProfileCustomerOverrideExpand]]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/customers/{customerId}" + path_format_arguments = { + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_customer_overrides_delete_request(customer_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/billing/customers/{customerId}" + path_format_arguments = { + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_invoices_invoice_pending_lines_action_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/invoice" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_invoices_list_request( + *, + statuses: Optional[List[Union[str, _models.InvoiceStatus]]] = None, + extended_statuses: Optional[List[str]] = None, + issued_after: Optional[datetime.datetime] = None, + issued_before: Optional[datetime.datetime] = None, + period_start_after: Optional[datetime.datetime] = None, + period_start_before: Optional[datetime.datetime] = None, + created_after: Optional[datetime.datetime] = None, + created_before: Optional[datetime.datetime] = None, + expand: Optional[List[Union[str, _models.InvoiceExpand]]] = None, + customers: Optional[List[str]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.InvoiceOrderBy]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices" + + # Construct parameters + if statuses is not None: + _params["statuses"] = [_SERIALIZER.query("statuses", q, "str") if q is not None else "" for q in statuses] + if extended_statuses is not None: + _params["extendedStatuses"] = [ + _SERIALIZER.query("extended_statuses", q, "str") if q is not None else "" for q in extended_statuses + ] + if issued_after is not None: + _params["issuedAfter"] = _SERIALIZER.query("issued_after", issued_after, "iso-8601") + if issued_before is not None: + _params["issuedBefore"] = _SERIALIZER.query("issued_before", issued_before, "iso-8601") + if period_start_after is not None: + _params["periodStartAfter"] = _SERIALIZER.query("period_start_after", period_start_after, "iso-8601") + if period_start_before is not None: + _params["periodStartBefore"] = _SERIALIZER.query("period_start_before", period_start_before, "iso-8601") + if created_after is not None: + _params["createdAfter"] = _SERIALIZER.query("created_after", created_after, "iso-8601") + if created_before is not None: + _params["createdBefore"] = _SERIALIZER.query("created_before", created_before, "iso-8601") + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + if customers is not None: + _params["customers"] = [_SERIALIZER.query("customers", q, "str") if q is not None else "" for q in customers] + if include_deleted is not None: + _params["includeDeleted"] = _SERIALIZER.query("include_deleted", include_deleted, "bool") + if page is not None: + _params["page"] = _SERIALIZER.query("page", page, "int") + if page_size is not None: + _params["pageSize"] = _SERIALIZER.query("page_size", page_size, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if order_by is not None: + _params["orderBy"] = _SERIALIZER.query("order_by", order_by, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoice_get_invoice_request( + invoice_id: str, + *, + expand: Optional[List[Union[str, _models.InvoiceExpand]]] = None, + include_deleted_lines: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if expand is not None: + _params["expand"] = [_SERIALIZER.query("expand", q, "str") if q is not None else "" for q in expand] + if include_deleted_lines is not None: + _params["includeDeletedLines"] = _SERIALIZER.query("include_deleted_lines", include_deleted_lines, "bool") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_invoice_delete_invoice_request(invoice_id: str, **kwargs: Any) -> HttpRequest: + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + return HttpRequest(method="DELETE", url=_url, **kwargs) + + +def build_invoice_update_invoice_request(invoice_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) + + +def build_invoice_recalculate_tax_action_request( # pylint: disable=name-too-long + invoice_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}/taxes/recalculate" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_invoice_approve_action_request(invoice_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}/approve" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_invoice_void_invoice_action_request( # pylint: disable=name-too-long + invoice_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}/void" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_invoice_advance_action_request(invoice_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}/advance" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_invoice_retry_action_request(invoice_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}/retry" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_invoice_snapshot_quantities_action_request( # pylint: disable=name-too-long + invoice_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/invoices/{invoiceId}/snapshot-quantities" + path_format_arguments = { + "invoiceId": _SERIALIZER.url("invoice_id", invoice_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_customer_invoice_simulate_invoice_request( # pylint: disable=name-too-long + customer_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/customers/{customerId}/invoices/simulate" + path_format_arguments = { + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_customer_invoice_create_pending_invoice_line_request( # pylint: disable=name-too-long + customer_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/billing/customers/{customerId}/invoices/pending-lines" + path_format_arguments = { + "customerId": _SERIALIZER.url("customer_id", customer_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_progress_get_progress_request(id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/info/progress/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("id", id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_currencies_list_currencies_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/info/currencies" + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) + + +def build_portal_portal_tokens_create_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/portal/tokens" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_portal_portal_tokens_list_request(*, limit: Optional[int] = None, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/portal/tokens" + + # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_portal_portal_tokens_invalidate_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + # Construct URL + _url = "/api/v1/portal/tokens/invalidate" + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + + return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) + + +def build_portal_portal_meters_query_json_request( # pylint: disable=name-too-long + meter_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/api/v1/portal/meters/{meterSlug}/query" + path_format_arguments = { + "meterSlug": _SERIALIZER.url("meter_slug", meter_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if client_id is not None: + _params["clientId"] = _SERIALIZER.query("client_id", client_id, "str") + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + if window_size is not None: + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + if filter_customer_id is not None: + _params["filterCustomerId"] = [ + _SERIALIZER.query("filter_customer_id", q, "str") if q is not None else "" for q in filter_customer_id + ] + if filter_group_by is not None: + _params["filterGroupBy"] = _SERIALIZER.query("filter_group_by", filter_group_by, "{str}") + if advanced_meter_group_by_filters is not None: + _params["advancedMeterGroupByFilters"] = _SERIALIZER.query( + "advanced_meter_group_by_filters", json.dumps(advanced_meter_group_by_filters), "str" + ) + if group_by is not None: + _params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_portal_portal_meters_query_csv_request( # pylint: disable=name-too-long + meter_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + accept = _headers.pop("Accept", "text/csv") + + # Construct URL + _url = "/api/v1/portal/meters/{meterSlug}/query" + path_format_arguments = { + "meterSlug": _SERIALIZER.url("meter_slug", meter_slug, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if client_id is not None: + _params["clientId"] = _SERIALIZER.query("client_id", client_id, "str") + if from_parameter is not None: + _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "iso-8601") + if to is not None: + _params["to"] = _SERIALIZER.query("to", to, "iso-8601") + if window_size is not None: + _params["windowSize"] = _SERIALIZER.query("window_size", window_size, "str") + if window_time_zone is not None: + _params["windowTimeZone"] = _SERIALIZER.query("window_time_zone", window_time_zone, "str") + if filter_customer_id is not None: + _params["filterCustomerId"] = [ + _SERIALIZER.query("filter_customer_id", q, "str") if q is not None else "" for q in filter_customer_id + ] + if filter_group_by is not None: + _params["filterGroupBy"] = _SERIALIZER.query("filter_group_by", filter_group_by, "{str}") + if advanced_meter_group_by_filters is not None: + _params["advancedMeterGroupByFilters"] = _SERIALIZER.query( + "advanced_meter_group_by_filters", json.dumps(advanced_meter_group_by_filters), "str" + ) + if group_by is not None: + _params["groupBy"] = [_SERIALIZER.query("group_by", q, "str") if q is not None else "" for q in group_by] + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class PortalOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`portal` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + self.portal_tokens = PortalPortalTokensOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.portal_meters = PortalPortalMetersOperations( + self._client, self._config, self._serialize, self._deserialize + ) + + +class AppsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`apps` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, *, page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any + ) -> _models.AppPaginatedResponse: + """List apps. + + List apps. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: AppPaginatedResponse. The AppPaginatedResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.AppPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.AppPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_apps_list_request( + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AppPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, id: str, **kwargs: Any) -> "_types.App": + """Get app. + + Get the app. + + :param id: Required. + :type id: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.App"] = kwargs.pop("cls", None) + + _request = build_apps_get_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.App", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, id: str, app: _models.StripeAppReplaceUpdate, *, content_type: str = "application/json", **kwargs: Any + ) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Required. + :type app: ~openmeter._generated.models.StripeAppReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, id: str, app: _models.SandboxAppReplaceUpdate, *, content_type: str = "application/json", **kwargs: Any + ) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Required. + :type app: ~openmeter._generated.models.SandboxAppReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + id: str, + app: _models.CustomInvoicingAppReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Required. + :type app: ~openmeter._generated.models.CustomInvoicingAppReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update(self, id: str, app: "_types.AppReplaceUpdate", **kwargs: Any) -> "_types.App": + """Update app. + + Update an app. + + :param id: Required. + :type id: str + :param app: Is one of the following types: StripeAppReplaceUpdate, SandboxAppReplaceUpdate, + CustomInvoicingAppReplaceUpdate Required. + :type app: ~openmeter._generated.models.StripeAppReplaceUpdate or + ~openmeter._generated.models.SandboxAppReplaceUpdate or + ~openmeter._generated.models.CustomInvoicingAppReplaceUpdate + :return: StripeApp or SandboxApp or CustomInvoicingApp + :rtype: ~openmeter._generated.models.StripeApp or ~openmeter._generated.models.SandboxApp or + ~openmeter._generated.models.CustomInvoicingApp + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.App"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(app, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_apps_update_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.App", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def uninstall(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Uninstall app. + + Uninstall an app. + + :param id: Required. + :type id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_apps_uninstall_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class AppStripeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`app_stripe` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def webhook( + self, id: str, body: _models.StripeWebhookEvent, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Required. + :type body: ~openmeter._generated.models.StripeWebhookEvent + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def webhook( + self, id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def webhook( + self, id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def webhook( + self, id: str, body: Union[_models.StripeWebhookEvent, JSON, IO[bytes]], **kwargs: Any + ) -> _models.StripeWebhookResponse: + """Stripe webhook. + + Handle stripe webhooks for apps. + + :param id: Required. + :type id: str + :param body: Is one of the following types: StripeWebhookEvent, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.StripeWebhookEvent or JSON or IO[bytes] + :return: StripeWebhookResponse. The StripeWebhookResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeWebhookResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.StripeWebhookResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_stripe_webhook_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeWebhookResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update_stripe_api_key( + self, id: str, request: _models.StripeAPIKeyInput, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Required. + :type request: ~openmeter._generated.models.StripeAPIKeyInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update_stripe_api_key( + self, id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update_stripe_api_key( + self, id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update_stripe_api_key( # pylint: disable=inconsistent-return-statements + self, id: str, request: Union[_models.StripeAPIKeyInput, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Update Stripe API key. + + Update the Stripe API key. + + ⚠️ **Deprecated**: Use ``PUT /api/v1/apps/{id}` <#tag/apps/put/api/v1/apps/{id}>`_ instead. + + :param id: Required. + :type id: str + :param request: Is one of the following types: StripeAPIKeyInput, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.StripeAPIKeyInput or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_stripe_update_stripe_api_key_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_checkout_session( + self, body: _models.CreateStripeCheckoutSessionRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Required. + :type body: ~openmeter._generated.models.CreateStripeCheckoutSessionRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_checkout_session( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_checkout_session( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create_checkout_session( + self, body: Union[_models.CreateStripeCheckoutSessionRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CreateStripeCheckoutSessionResult: + """Create checkout session. + + Create checkout session. + + :param body: Is one of the following types: CreateStripeCheckoutSessionRequest, JSON, IO[bytes] + Required. + :type body: ~openmeter._generated.models.CreateStripeCheckoutSessionRequest or JSON or + IO[bytes] + :return: CreateStripeCheckoutSessionResult. The CreateStripeCheckoutSessionResult is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CreateStripeCheckoutSessionResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.CreateStripeCheckoutSessionResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_stripe_create_checkout_session_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CreateStripeCheckoutSessionResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerAppsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_apps` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + type: Optional[Union[str, _models.AppType]] = None, + **kwargs: Any + ) -> _models.CustomerAppDataPaginatedResponse: + """List customer app data. + + List customers app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword type: Filter customer data by app type. Known values are: "stripe", "sandbox", and + "custom_invoicing". Default value is None. + :paramtype type: str or ~openmeter.models.AppType + :return: CustomerAppDataPaginatedResponse. The CustomerAppDataPaginatedResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.CustomerAppDataPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.CustomerAppDataPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_apps_list_app_data_request( + customer_id_or_key=customer_id_or_key, + page=page, + page_size=page_size, + type=type, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CustomerAppDataPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def upsert_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: List["_types.CustomerAppData"], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> List["_types.CustomerAppData"]: + """Upsert customer app data. + + Upsert customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of StripeCustomerAppData or SandboxCustomerAppData or + CustomInvoicingCustomerAppData + :rtype: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> List["_types.CustomerAppData"]: + """Upsert customer app data. + + Upsert customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of StripeCustomerAppData or SandboxCustomerAppData or + CustomInvoicingCustomerAppData + :rtype: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def upsert_app_data( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: Union[List["_types.CustomerAppData"], IO[bytes]], + **kwargs: Any + ) -> List["_types.CustomerAppData"]: + """Upsert customer app data. + + Upsert customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Is either a ["_types.CustomerAppData"] type or a IO[bytes] type. Required. + :type app_data: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] or IO[bytes] + :return: list of StripeCustomerAppData or SandboxCustomerAppData or + CustomInvoicingCustomerAppData + :rtype: list[~openmeter._generated.models.StripeCustomerAppData or + ~openmeter._generated.models.SandboxCustomerAppData or + ~openmeter._generated.models.CustomInvoicingCustomerAppData] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List["_types.CustomerAppData"]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(app_data, (IOBase, bytes)): + _content = app_data + else: + _content = json.dumps(app_data, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_apps_upsert_app_data_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List["_types.CustomerAppData"], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete_app_data( # pylint: disable=inconsistent-return-statements + self, customer_id_or_key: "_types.ULIDOrExternalKey", app_id: str, **kwargs: Any + ) -> None: + """Delete customer app data. + + Delete customer app data. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_id: Required. + :type app_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customer_apps_delete_app_data_request( + customer_id_or_key=customer_id_or_key, + app_id=app_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class CustomersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customers` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, customer: _models.CustomerCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Required. + :type customer: ~openmeter._generated.models.CustomerCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, customer: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Required. + :type customer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, customer: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Required. + :type customer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, customer: Union[_models.CustomerCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Customer: + """Create customer. + + Create a new customer. + + :param customer: Is one of the following types: CustomerCreate, JSON, IO[bytes] Required. + :type customer: ~openmeter._generated.models.CustomerCreate or JSON or IO[bytes] + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Customer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(customer, (IOBase, bytes)): + _content = customer + else: + _content = json.dumps(customer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customers_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Customer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list( + self, + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.CustomerOrderBy]] = None, + include_deleted: Optional[bool] = None, + key: Optional[str] = None, + name: Optional[str] = None, + primary_email: Optional[str] = None, + subject: Optional[str] = None, + plan_key: Optional[str] = None, + expand: Optional[List[Union[str, _models.CustomerExpand]]] = None, + **kwargs: Any + ) -> _models.CustomerPaginatedResponse: + """List customers. + + List customers. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "name", and "createdAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.CustomerOrderBy + :keyword include_deleted: Include deleted customers. Default value is None. + :paramtype include_deleted: bool + :keyword key: Filter customers by key. + Case-insensitive partial match. Default value is None. + :paramtype key: str + :keyword name: Filter customers by name. + Case-insensitive partial match. Default value is None. + :paramtype name: str + :keyword primary_email: Filter customers by primary email. + Case-insensitive partial match. Default value is None. + :paramtype primary_email: str + :keyword subject: Filter customers by usage attribution subject. + Case-insensitive partial match. Default value is None. + :paramtype subject: str + :keyword plan_key: Filter customers by the plan key of their susbcription. Default value is + None. + :paramtype plan_key: str + :keyword expand: What parts of the list output to expand in listings. Default value is None. + :paramtype expand: list[str or ~openmeter.models.CustomerExpand] + :return: CustomerPaginatedResponse. The CustomerPaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.CustomerPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.CustomerPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customers_list_request( + page=page, + page_size=page_size, + order=order, + order_by=order_by, + include_deleted=include_deleted, + key=key, + name=name, + primary_email=primary_email, + subject=subject, + plan_key=plan_key, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CustomerPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + expand: Optional[List[Union[str, _models.CustomerExpand]]] = None, + **kwargs: Any + ) -> _models.Customer: + """Get customer. + + Get a customer by ID or key. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword expand: What parts of the customer output to expand. Default value is None. + :paramtype expand: list[str or ~openmeter.models.CustomerExpand] + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Customer] = kwargs.pop("cls", None) + + _request = build_customers_get_request( + customer_id_or_key=customer_id_or_key, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Customer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: _models.CustomerReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Required. + :type customer: ~openmeter._generated.models.CustomerReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Required. + :type customer: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Required. + :type customer: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + customer: Union[_models.CustomerReplaceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.Customer: + """Update customer. + + Update a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param customer: Is one of the following types: CustomerReplaceUpdate, JSON, IO[bytes] + Required. + :type customer: ~openmeter._generated.models.CustomerReplaceUpdate or JSON or IO[bytes] + :return: Customer. The Customer is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Customer + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Customer] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(customer, (IOBase, bytes)): + _content = customer + else: + _content = json.dumps(customer, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customers_update_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Customer, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete( # pylint: disable=inconsistent-return-statements + self, customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any + ) -> None: + """Delete customer. + + Delete a customer by ID. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customers_delete_request( + customer_id_or_key=customer_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def list_customer_subscriptions( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + status: Optional[List[Union[str, _models.SubscriptionStatus]]] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.CustomerSubscriptionOrderBy]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + **kwargs: Any + ) -> _models.SubscriptionPaginatedResponse: + """List customer subscriptions. + + Lists all subscriptions for a customer. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword status: Default value is None. + :paramtype status: list[str or ~openmeter.models.SubscriptionStatus] + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "activeFrom" and "activeTo". Default + value is None. + :paramtype order_by: str or ~openmeter.models.CustomerSubscriptionOrderBy + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: SubscriptionPaginatedResponse. The SubscriptionPaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SubscriptionPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customers_list_customer_subscriptions_request( + customer_id_or_key=customer_id_or_key, + status=status, + order=order, + order_by=order_by, + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class FeaturesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`features` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + meter_slug: Optional[List[str]] = None, + include_archived: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.FeatureOrderBy]] = None, + **kwargs: Any + ) -> "_types.ListFeaturesResult": + """List features. + + List features. + + :keyword meter_slug: Filter by meterSlug. Default value is None. + :paramtype meter_slug: list[str] + :keyword include_archived: Include archived features in response. Default value is None. + :paramtype include_archived: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "name", "createdAt", and + "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.FeatureOrderBy + :return: list of Feature or FeaturePaginatedResponse + :rtype: list[~openmeter._generated.models.Feature] or + ~openmeter._generated.models.FeaturePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.ListFeaturesResult"] = kwargs.pop("cls", None) + + _request = build_features_list_request( + meter_slug=meter_slug, + include_archived=include_archived, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.ListFeaturesResult", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, feature: _models.FeatureCreateInputs, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Required. + :type feature: ~openmeter._generated.models.FeatureCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, feature: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Required. + :type feature: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, feature: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Required. + :type feature: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, feature: Union[_models.FeatureCreateInputs, JSON, IO[bytes]], **kwargs: Any) -> _models.Feature: + """Create feature. + + Features are either metered or static. A feature is metered if meterSlug is provided at + creation. For metered features you can pass additional filters that will be applied when + calculating feature usage, based on the meter's groupBy fields. Meters with SUM, COUNT, + UNIQUE_COUNT and LATEST aggregations are supported for features. + + :param feature: Is one of the following types: FeatureCreateInputs, JSON, IO[bytes] Required. + :type feature: ~openmeter._generated.models.FeatureCreateInputs or JSON or IO[bytes] + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Feature] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(feature, (IOBase, bytes)): + _content = feature + else: + _content = json.dumps(feature, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_features_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Feature, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, feature_id: str, **kwargs: Any) -> _models.Feature: + """Get feature. + + Get a feature by ID. + + :param feature_id: Required. + :type feature_id: str + :return: Feature. The Feature is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Feature + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Feature] = kwargs.pop("cls", None) + + _request = build_features_get_request( + feature_id=feature_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Feature, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, feature_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete feature. + + Archive a feature by ID. + + Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements + cannot be created for it, but archiving the feature does not affect existing entitlements. + This means, if you want to create a new feature with the same key, and then create entitlements + for it, the previous entitlements have to be deleted first on a per subject basis. + + :param feature_id: Required. + :type feature_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_features_delete_request( + feature_id=feature_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class PlansOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`plans` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + status: Optional[List[Union[str, _models.PlanStatus]]] = None, + currency: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.PlanOrderBy]] = None, + **kwargs: Any + ) -> ItemPaged["_models.Plan"]: + """List plans. + + List all plans. + + :keyword include_deleted: Include deleted plans in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword id: Filter by plan.id attribute. Default value is None. + :paramtype id: list[str] + :keyword key: Filter by plan.key attribute. Default value is None. + :paramtype key: list[str] + :keyword key_version: Filter by plan.key and plan.version attributes. Default value is None. + :paramtype key_version: dict[str, list[int]] + :keyword status: Only return plans with the given status. + + Usage: + + * `?status=active`: return only the currently active plan + * `?status=draft`: return only the draft plan + * `?status=archived`: return only the archived plans. Default value is None. + :paramtype status: list[str or ~openmeter.models.PlanStatus] + :keyword currency: Filter by plan.currency attribute. Default value is None. + :paramtype currency: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "version", "created_at", + and "updated_at". Default value is None. + :paramtype order_by: str or ~openmeter.models.PlanOrderBy + :return: An iterator like instance of Plan + :rtype: ~corehttp.paging.ItemPaged[~openmeter._generated.models.Plan] + :raises ~corehttp.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Plan]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_plans_list_request( + include_deleted=include_deleted, + id=id, + key=key, + key_version=key_version, + status=status, + currency=currency, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + _request = HttpRequest("GET", next_link, headers=_headers) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Plan], + deserialized.get("items", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create( + self, request: _models.PlanCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Required. + :type request: ~openmeter._generated.models.PlanCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, request: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, request: Union[_models.PlanCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Plan: + """Create a plan. + + Create a new plan. + + :param request: Is one of the following types: PlanCreate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.PlanCreate or JSON or IO[bytes] + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plans_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, plan_id: str, body: _models.PlanReplaceUpdate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, plan_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, plan_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, plan_id: str, body: Union[_models.PlanReplaceUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Plan: + """Update a plan. + + Update plan by id. + + :param plan_id: Required. + :type plan_id: str + :param body: Is one of the following types: PlanReplaceUpdate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.PlanReplaceUpdate or JSON or IO[bytes] + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plans_update_request( + plan_id=plan_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, plan_id: str, *, include_latest: Optional[bool] = None, **kwargs: Any) -> _models.Plan: + """Get plan. + + Get a plan by id or key. The latest published version is returned if latter is used. + + :param plan_id: Required. + :type plan_id: str + :keyword include_latest: Include latest version of the Plan instead of the version in active + state. + + Usage: ``?includeLatest=true``. Default value is None. + :paramtype include_latest: bool + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_get_request( + plan_id=plan_id, + include_latest=include_latest, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, plan_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete plan. + + Soft delete plan by plan.id. + + Once a plan is deleted it cannot be undeleted. + + :param plan_id: Required. + :type plan_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_plans_delete_request( + plan_id=plan_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def publish(self, plan_id: str, **kwargs: Any) -> _models.Plan: + """Publish plan. + + Publish a plan version. + + :param plan_id: Required. + :type plan_id: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_publish_request( + plan_id=plan_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def archive(self, plan_id: str, **kwargs: Any) -> _models.Plan: + """Archive plan version. + + Archive a plan version. + + :param plan_id: Required. + :type plan_id: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_archive_request( + plan_id=plan_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def next(self, plan_id_or_key: str, **kwargs: Any) -> _models.Plan: + """New draft plan. + + Create a new draft version from plan. It returns error if there is already a plan in draft or + planId does not reference the latest published version. + + :param plan_id_or_key: Required. + :type plan_id_or_key: str + :return: Plan. The Plan is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Plan + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Plan] = kwargs.pop("cls", None) + + _request = build_plans_next_request( + plan_id_or_key=plan_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Plan, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PlanAddonsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`plan_addons` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + plan_id: str, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.PlanAddonOrderBy]] = None, + **kwargs: Any + ) -> _models.PlanAddonPaginatedResponse: + """List all available add-ons for plan. + + List all available add-ons for plan. + + :param plan_id: Required. + :type plan_id: str + :keyword include_deleted: Include deleted plan add-on assignments. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword id: Filter by addon.id attribute. Default value is None. + :paramtype id: list[str] + :keyword key: Filter by addon.key attribute. Default value is None. + :paramtype key: list[str] + :keyword key_version: Filter by addon.key and addon.version attributes. Default value is None. + :paramtype key_version: dict[str, list[int]] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "version", "created_at", + and "updated_at". Default value is None. + :paramtype order_by: str or ~openmeter.models.PlanAddonOrderBy + :return: PlanAddonPaginatedResponse. The PlanAddonPaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.PlanAddonPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PlanAddonPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_plan_addons_list_request( + plan_id=plan_id, + include_deleted=include_deleted, + id=id, + key=key, + key_version=key_version, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddonPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, plan_id: str, body: _models.PlanAddonCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanAddonCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, plan_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, plan_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create( + self, plan_id: str, body: Union[_models.PlanAddonCreate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.PlanAddon: + """Create new add-on assignment for plan. + + Create new add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param body: Is one of the following types: PlanAddonCreate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.PlanAddonCreate or JSON or IO[bytes] + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PlanAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plan_addons_create_request( + plan_id=plan_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + plan_id: str, + plan_addon_id: str, + body: _models.PlanAddonReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanAddonReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, plan_id: str, plan_addon_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + plan_id: str, + plan_addon_id: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, + plan_id: str, + plan_addon_id: str, + body: Union[_models.PlanAddonReplaceUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.PlanAddon: + """Update add-on assignment for plan. + + Update add-on assignment for plan. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :param body: Is one of the following types: PlanAddonReplaceUpdate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.PlanAddonReplaceUpdate or JSON or IO[bytes] + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PlanAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_plan_addons_update_request( + plan_id=plan_id, + plan_addon_id=plan_addon_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, plan_id: str, plan_addon_id: str, **kwargs: Any) -> _models.PlanAddon: + """Get add-on assignment for plan. + + Get add-on assignment for plan by id. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :return: PlanAddon. The PlanAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PlanAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.PlanAddon] = kwargs.pop("cls", None) + + _request = build_plan_addons_get_request( + plan_id=plan_id, + plan_addon_id=plan_addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PlanAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete( # pylint: disable=inconsistent-return-statements + self, plan_id: str, plan_addon_id: str, **kwargs: Any + ) -> None: + """Delete add-on assignment for plan. + + Delete add-on assignment for plan. + + Once a plan is deleted it cannot be undeleted. + + :param plan_id: Required. + :type plan_id: str + :param plan_addon_id: Required. + :type plan_addon_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_plan_addons_delete_request( + plan_id=plan_id, + plan_addon_id=plan_addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class AddonsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`addons` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_deleted: Optional[bool] = None, + id: Optional[List[str]] = None, + key: Optional[List[str]] = None, + key_version: Optional[dict[str, List[int]]] = None, + status: Optional[List[Union[str, _models.AddonStatus]]] = None, + currency: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.AddonOrderBy]] = None, + **kwargs: Any + ) -> ItemPaged["_models.Addon"]: + """List add-ons. + + List all add-ons. + + :keyword include_deleted: Include deleted add-ons in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword id: Filter by addon.id attribute. Default value is None. + :paramtype id: list[str] + :keyword key: Filter by addon.key attribute. Default value is None. + :paramtype key: list[str] + :keyword key_version: Filter by addon.key and addon.version attributes. Default value is None. + :paramtype key_version: dict[str, list[int]] + :keyword status: Only return add-ons with the given status. + + Usage: + + * `?status=active`: return only the currently active add-ons + * `?status=draft`: return only the draft add-ons + * `?status=archived`: return only the archived add-ons. Default value is None. + :paramtype status: list[str or ~openmeter.models.AddonStatus] + :keyword currency: Filter by addon.currency attribute. Default value is None. + :paramtype currency: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "key", "version", "created_at", + and "updated_at". Default value is None. + :paramtype order_by: str or ~openmeter.models.AddonOrderBy + :return: An iterator like instance of Addon + :rtype: ~corehttp.paging.ItemPaged[~openmeter._generated.models.Addon] + :raises ~corehttp.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Addon]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_addons_list_request( + include_deleted=include_deleted, + id=id, + key=key, + key_version=key_version, + status=status, + currency=currency, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + _request = HttpRequest("GET", next_link, headers=_headers) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Addon], + deserialized.get("items", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create( + self, request: _models.AddonCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Required. + :type request: ~openmeter._generated.models.AddonCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, request: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, request: Union[_models.AddonCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Addon: + """Create an add-on. + + Create a new add-on. + + :param request: Is one of the following types: AddonCreate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.AddonCreate or JSON or IO[bytes] + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_addons_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + addon_id: str, + request: _models.AddonReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Required. + :type request: ~openmeter._generated.models.AddonReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, addon_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, addon_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, addon_id: str, request: Union[_models.AddonReplaceUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Addon: + """Update add-on. + + Update add-on by id. + + :param addon_id: Required. + :type addon_id: str + :param request: Is one of the following types: AddonReplaceUpdate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.AddonReplaceUpdate or JSON or IO[bytes] + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_addons_update_request( + addon_id=addon_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, addon_id: str, *, include_latest: Optional[bool] = None, **kwargs: Any) -> _models.Addon: + """Get add-on. + + Get add-on by id or key. The latest published version is returned if latter is used. + + :param addon_id: Required. + :type addon_id: str + :keyword include_latest: Include latest version of the add-on instead of the version in active + state. + + Usage: ``?includeLatest=true``. Default value is None. + :paramtype include_latest: bool + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + _request = build_addons_get_request( + addon_id=addon_id, + include_latest=include_latest, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, addon_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete add-on. + + Soft delete add-on by id. + + Once a add-on is deleted it cannot be undeleted. + + :param addon_id: Required. + :type addon_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_addons_delete_request( + addon_id=addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def publish(self, addon_id: str, **kwargs: Any) -> _models.Addon: + """Publish add-on. + + Publish a add-on version. + + :param addon_id: Required. + :type addon_id: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + _request = build_addons_publish_request( + addon_id=addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def archive(self, addon_id: str, **kwargs: Any) -> _models.Addon: + """Archive add-on version. + + Archive a add-on version. + + :param addon_id: Required. + :type addon_id: str + :return: Addon. The Addon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Addon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Addon] = kwargs.pop("cls", None) + + _request = build_addons_archive_request( + addon_id=addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Addon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SubscriptionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`subscriptions` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get_expanded( + self, subscription_id: str, *, at: Optional[datetime.datetime] = None, **kwargs: Any + ) -> _models.SubscriptionExpanded: + """Get subscription. + + get_expanded. + + :param subscription_id: Required. + :type subscription_id: str + :keyword at: The time at which the subscription should be queried. If not provided the current + time is used. Default value is None. + :paramtype at: ~datetime.datetime + :return: SubscriptionExpanded. The SubscriptionExpanded is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionExpanded + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SubscriptionExpanded] = kwargs.pop("cls", None) + + _request = build_subscriptions_get_expanded_request( + subscription_id=subscription_id, + at=at, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionExpanded, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, body: _models.PlanSubscriptionCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Create subscription. + + create. + + :param body: Required. + :type body: ~openmeter._generated.models.PlanSubscriptionCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, body: _models.CustomSubscriptionCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Create subscription. + + create. + + :param body: Required. + :type body: ~openmeter._generated.models.CustomSubscriptionCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, body: "_types.SubscriptionCreate", **kwargs: Any) -> _models.Subscription: + """Create subscription. + + create. + + :param body: Is either a PlanSubscriptionCreate type or a CustomSubscriptionCreate type. + Required. + :type body: ~openmeter._generated.models.PlanSubscriptionCreate or + ~openmeter._generated.models.CustomSubscriptionCreate + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def edit( + self, + subscription_id: str, + body: _models.SubscriptionEdit, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.SubscriptionEdit + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def edit( + self, subscription_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def edit( + self, subscription_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def edit( + self, subscription_id: str, body: Union[_models.SubscriptionEdit, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Subscription: + """Edit subscription. + + Batch processing commands for manipulating running subscriptions. The key format is + ``/phases/{phaseKey}`` or ``/phases/{phaseKey}/items/{itemKey}``. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is one of the following types: SubscriptionEdit, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.SubscriptionEdit or JSON or IO[bytes] + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_edit_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def change( + self, + subscription_id: str, + body: _models.PlanSubscriptionChange, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Change subscription. + + Closes a running subscription and starts a new one according to the specification. Can be used + for upgrades, downgrades, and plan changes. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.PlanSubscriptionChange + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def change( + self, + subscription_id: str, + body: _models.CustomSubscriptionChange, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Change subscription. + + Closes a running subscription and starts a new one according to the specification. Can be used + for upgrades, downgrades, and plan changes. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomSubscriptionChange + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def change( + self, subscription_id: str, body: "_types.SubscriptionChange", **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Change subscription. + + Closes a running subscription and starts a new one according to the specification. Can be used + for upgrades, downgrades, and plan changes. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is either a PlanSubscriptionChange type or a CustomSubscriptionChange type. + Required. + :type body: ~openmeter._generated.models.PlanSubscriptionChange or + ~openmeter._generated.models.CustomSubscriptionChange + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionChangeResponseBody] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_change_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionChangeResponseBody, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def migrate( + self, + subscription_id: str, + body: _models.MigrateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.MigrateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def migrate( + self, subscription_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def migrate( + self, subscription_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def migrate( + self, subscription_id: str, body: Union[_models.MigrateRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.SubscriptionChangeResponseBody: + """Migrate subscription. + + Migrates the subscripiton to the provided version of the current plan. If possible, the + migration will be done immediately. If not, the migration will be scheduled to the end of the + current billing period. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is one of the following types: MigrateRequest, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.MigrateRequest or JSON or IO[bytes] + :return: SubscriptionChangeResponseBody. The SubscriptionChangeResponseBody is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionChangeResponseBody + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionChangeResponseBody] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_migrate_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionChangeResponseBody, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def restore(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: + """Restore subscription. + + Restores a canceled subscription. Any subscription scheduled to start later will be deleted and + this subscription will be continued indefinitely. + + :param subscription_id: Required. + :type subscription_id: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + _request = build_subscriptions_restore_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def cancel( + self, + subscription_id: str, + body: _models.CancelRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CancelRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def cancel( + self, subscription_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def cancel( + self, subscription_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def cancel( + self, subscription_id: str, body: Union[_models.CancelRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Subscription: + """Cancel subscription. + + Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions + scheduled to start after the cancellation time. + + :param subscription_id: Required. + :type subscription_id: str + :param body: Is one of the following types: CancelRequest, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.CancelRequest or JSON or IO[bytes] + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscriptions_cancel_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def unschedule_cancelation(self, subscription_id: str, **kwargs: Any) -> _models.Subscription: + """Unschedule cancelation. + + Cancels the scheduled cancelation. + + :param subscription_id: Required. + :type subscription_id: str + :return: Subscription. The Subscription is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subscription + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Subscription] = kwargs.pop("cls", None) + + _request = build_subscriptions_unschedule_cancelation_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subscription, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, subscription_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete subscription. + + Deletes a subscription. Only scheduled subscriptions can be deleted. + + :param subscription_id: Required. + :type subscription_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subscriptions_delete_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.SubscriptionBadRequestErrorResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.SubscriptionConflictErrorResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class SubscriptionAddonsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`subscription_addons` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, + subscription_id: str, + request: _models.SubscriptionAddonCreate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Required. + :type request: ~openmeter._generated.models.SubscriptionAddonCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, subscription_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, subscription_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create( + self, subscription_id: str, request: Union[_models.SubscriptionAddonCreate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.SubscriptionAddon: + """Create subscription addon. + + Create a new subscription addon, either providing the key or the id of the addon. + + :param subscription_id: Required. + :type subscription_id: str + :param request: Is one of the following types: SubscriptionAddonCreate, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.SubscriptionAddonCreate or JSON or IO[bytes] + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscription_addons_create_request( + subscription_id=subscription_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list(self, subscription_id: str, **kwargs: Any) -> List[_models.SubscriptionAddon]: + """List subscription addons. + + List all addons of a subscription. In the returned list will match to a set unique by addonId. + + :param subscription_id: Required. + :type subscription_id: str + :return: list of SubscriptionAddon + :rtype: list[~openmeter._generated.models.SubscriptionAddon] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.SubscriptionAddon]] = kwargs.pop("cls", None) + + _request = build_subscription_addons_list_request( + subscription_id=subscription_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.SubscriptionAddon], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, subscription_id: str, subscription_addon_id: str, **kwargs: Any) -> _models.SubscriptionAddon: + """Get subscription addon. + + Get a subscription addon by id. + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SubscriptionAddon] = kwargs.pop("cls", None) + + _request = build_subscription_addons_get_request( + subscription_id=subscription_id, + subscription_addon_id=subscription_addon_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: _models.SubscriptionAddonUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Required. + :type body: ~openmeter._generated.models.SubscriptionAddonUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, + subscription_id: str, + subscription_addon_id: str, + body: Union[_models.SubscriptionAddonUpdate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.SubscriptionAddon: + """Update subscription addon. + + Updates a subscription addon (allows changing the quantity: purchasing more instances or + cancelling the current instances). + + :param subscription_id: Required. + :type subscription_id: str + :param subscription_addon_id: Required. + :type subscription_addon_id: str + :param body: Is one of the following types: SubscriptionAddonUpdate, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.SubscriptionAddonUpdate or JSON or IO[bytes] + :return: SubscriptionAddon. The SubscriptionAddon is compatible with MutableMapping + :rtype: ~openmeter._generated.models.SubscriptionAddon + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SubscriptionAddon] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subscription_addons_update_request( + subscription_id=subscription_id, + subscription_addon_id=subscription_addon_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SubscriptionAddon, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class EntitlementsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`entitlements` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + entitlement_type: Optional[List[Union[str, _models.EntitlementType]]] = None, + exclude_inactive: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any + ) -> "_types.ListEntitlementsResult": + """List all entitlements. + + List all entitlements for all the subjects and features. This endpoint is intended for + administrative purposes only. + To fetch the entitlements of a specific subject please use the + /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ **Deprecated**: Use ``GET /api/v2/entitlements` + <#tag/entitlements/get/api/v2/entitlements>`_ instead. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword subject: Filtering by multiple subjects. + + Usage: ``?subject=customer-1&subject=customer-2``. Default value is None. + :paramtype subject: list[str] + :keyword entitlement_type: Filtering by multiple entitlement types. + + Usage: ``?entitlementType=metered&entitlementType=boolean``. Default value is None. + :paramtype entitlement_type: list[str or ~openmeter.models.EntitlementType] + :keyword exclude_inactive: Exclude inactive entitlements in the response (those scheduled for + later or earlier). Default value is None. + :paramtype exclude_inactive: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt" and "updatedAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.EntitlementOrderBy + :return: list of EntitlementMetered or EntitlementStatic or EntitlementBoolean or + EntitlementPaginatedResponse + :rtype: list[~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean] or + ~openmeter._generated.models.EntitlementPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.ListEntitlementsResult"] = kwargs.pop("cls", None) + + _request = build_entitlements_list_request( + feature=feature, + subject=subject, + entitlement_type=entitlement_type, + exclude_inactive=exclude_inactive, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.ListEntitlementsResult", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, entitlement_id: str, **kwargs: Any) -> "_types.Entitlement": + """Get entitlement by ID. + + Get entitlement by ID. + + ⚠️ **Deprecated**: Use ``GET /api/v2/entitlements/{entitlementId}` + <#tag/entitlements/get/api/v2/entitlements/{entitlementId}>`_ instead. + + :param entitlement_id: Required. + :type entitlement_id: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + _request = build_entitlements_get_request( + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class GrantsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`grants` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> Union[List[_models.EntitlementGrant], _models.GrantPaginatedResponse]: + """List grants. + + List all grants for all the subjects and entitlements. This endpoint is intended for + administrative purposes only. + To fetch the grants of a specific entitlement please use the + /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ **Deprecated**: Use ``GET /api/v2/grants` <#tag/entitlements/get/api/v2/grants>`_ instead. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword subject: Filtering by multiple subjects. + + Usage: ``?subject=customer-1&subject=customer-2``. Default value is None. + :paramtype subject: list[str] + :keyword include_deleted: Include deleted. Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "createdAt", and "updatedAt". + Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: list of EntitlementGrant or GrantPaginatedResponse + :rtype: list[~openmeter._generated.models.EntitlementGrant] or + ~openmeter._generated.models.GrantPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Union[List[_models.EntitlementGrant], _models.GrantPaginatedResponse]] = kwargs.pop("cls", None) + + _request = build_grants_list_request( + feature=feature, + subject=subject, + include_deleted=include_deleted, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize( + Union[List[_models.EntitlementGrant], _models.GrantPaginatedResponse], response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete( # pylint: disable=inconsistent-return-statements + self, grant_id: str, *, at: Optional[datetime.datetime] = None, **kwargs: Any + ) -> None: + """Void grant. + + Voiding a grant means it is no longer valid, it doesn't take part in further balance + calculations. Voiding a grant does not retroactively take effect, meaning any usage that has + already been attributed to the grant will remain, but future usage cannot be burnt down from + the grant. For example, if you have a single grant for your metered entitlement with an initial + amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) + would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous + usage will not be affected. + + :param grant_id: Required. + :type grant_id: str + :keyword at: The time at which the grant should be voided. + Must not be in the future and must be within the current usage period of the entitlement. + Defaults to the current time if not specified. Default value is None. + :paramtype at: ~datetime.datetime + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_grants_delete_request( + grant_id=grant_id, + at=at, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class SubjectsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`subjects` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def post( + self, + subject_id_or_key: str, + entitlement: _models.EntitlementMeteredCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def post( + self, + subject_id_or_key: str, + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def post( + self, + subject_id_or_key: str, + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def post( + self, subject_id_or_key: str, entitlement: "_types.EntitlementCreateInputs", **kwargs: Any + ) -> "_types.Entitlement": + """Create a subject entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ **Deprecated**: Use ``POST /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement: Is one of the following types: EntitlementMeteredCreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_post_request( + subject_id_or_key=subject_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list( + self, subject_id_or_key: str, *, include_deleted: Optional[bool] = None, **kwargs: Any + ) -> List["_types.Entitlement"]: + """List subject entitlements. + + List all entitlements for a subject. For checking entitlement access, use the /value endpoint + instead. + + ⚠️ **Deprecated**: Use ``GET /api/v2/customers/{customerIdOrKey}/entitlements` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements>`_ instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :return: list of EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: list[~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List["_types.Entitlement"]] = kwargs.pop("cls", None) + + _request = build_subjects_list_request( + subject_id_or_key=subject_id_or_key, + include_deleted=include_deleted, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List["_types.Entitlement"], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, subject_id_or_key: str, entitlement_id: str, **kwargs: Any) -> "_types.Entitlement": + """Get subject entitlement. + + Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + _request = build_subjects_get_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete( # pylint: disable=inconsistent-return-statements + self, subject_id_or_key: str, entitlement_id: str, **kwargs: Any + ) -> None: + """Delete subject entitlement. + + Deleting an entitlement revokes access to the associated feature. As a single subject can only + have one entitlement per featureKey, when "migrating" features you have to delete the old + entitlements as well. + As access and status checks can be historical queries, deleting an entitlement populates the + deletedAt timestamp. When queried for a time before that, the entitlement is still considered + active, you cannot have retroactive changes to access, which is important for, among other + things, auditing. + + ⚠️ **Deprecated**: Use ``DELETE + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}` + <#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subjects_delete_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: _models.EntitlementMeteredCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def override( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + entitlement: "_types.EntitlementCreateInputs", + **kwargs: Any + ) -> "_types.Entitlement": + """Override subject entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided subject-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + ⚠️ **Deprecated**: Use ``PUT + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` + <#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param entitlement: Is one of the following types: EntitlementMeteredCreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredCreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMetered or EntitlementStatic or EntitlementBoolean + :rtype: ~openmeter._generated.models.EntitlementMetered or + ~openmeter._generated.models.EntitlementStatic or + ~openmeter._generated.models.EntitlementBoolean + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.Entitlement"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_override_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.Entitlement", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get_grants( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> List[_models.EntitlementGrant]: + """List subject entitlement grants. + + List all grants issued for an entitlement. The entitlement can be defined either by its id or + featureKey. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :keyword order_by: Known values are: "id", "createdAt", and "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: list of EntitlementGrant + :rtype: list[~openmeter._generated.models.EntitlementGrant] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EntitlementGrant]] = kwargs.pop("cls", None) + + _request = build_subjects_get_grants_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + include_deleted=include_deleted, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.EntitlementGrant], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: _models.EntitlementGrantCreateInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create_grant( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + grant: Union[_models.EntitlementGrantCreateInput, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.EntitlementGrant: + """Create subject entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Is one of the following types: EntitlementGrantCreateInput, JSON, IO[bytes] + Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInput or JSON or IO[bytes] + :return: EntitlementGrant. The EntitlementGrant is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrant + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EntitlementGrant] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(grant, (IOBase, bytes)): + _content = grant + else: + _content = json.dumps(grant, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_create_grant_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementGrant, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get_entitlement_value( + self, + subject_id_or_key: str, + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> _models.EntitlementValue: + """Get subject entitlement value. + + This endpoint should be used for access checks and enforcement. All entitlement types share the + hasAccess property in their value response, but multiple other properties are returned based on + the entitlement type. + + For convenience reasons, /value works with both entitlementId and featureKey. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword time: Default value is None. + :paramtype time: ~datetime.datetime + :return: EntitlementValue. The EntitlementValue is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementValue + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementValue] = kwargs.pop("cls", None) + + _request = build_subjects_get_entitlement_value_request( + subject_id_or_key=subject_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + time=time, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementValue, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get_entitlement_history( + self, + subject_id_or_key: str, + entitlement_id: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any + ) -> _models.WindowedBalanceHistory: + """Get subject entitlement history. + + Returns historical balance and usage data for the entitlement. The queried history can span + accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by + events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information + and the list of grants that were being burnt down in that window. + + ⚠️ **Deprecated**: Use ``GET + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history` + <#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :keyword window_size: Windowsize. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". + Required. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword from_parameter: Start of time range to query entitlement: date-time in RFC 3339 + format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End of time range to query entitlement: date-time in RFC 3339 format. Defaults to + now. + If not now then gets truncated to the granularity of the underlying meter. Default value is + None. + :paramtype to: ~datetime.datetime + :keyword window_time_zone: The timezone used when calculating the windows. Default value is + None. + :paramtype window_time_zone: str + :return: WindowedBalanceHistory. The WindowedBalanceHistory is compatible with MutableMapping + :rtype: ~openmeter._generated.models.WindowedBalanceHistory + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.WindowedBalanceHistory] = kwargs.pop("cls", None) + + _request = build_subjects_get_entitlement_history_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + window_size=window_size, + from_parameter=from_parameter, + to=to, + window_time_zone=window_time_zone, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.WindowedBalanceHistory, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: _models.ResetEntitlementUsageInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Required. + :type reset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def reset( + self, + subject_id_or_key: str, + entitlement_id: str, + reset: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Required. + :type reset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def reset( # pylint: disable=inconsistent-return-statements + self, + subject_id_or_key: str, + entitlement_id: str, + reset: Union[_models.ResetEntitlementUsageInput, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Reset subject entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the subjects billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + ⚠️ **Deprecated**: Use ``POST + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` + <#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset>`_ + instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :param entitlement_id: Required. + :type entitlement_id: str + :param reset: Is one of the following types: ResetEntitlementUsageInput, JSON, IO[bytes] + Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(reset, (IOBase, bytes)): + _content = reset + else: + _content = json.dumps(reset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_reset_request( + subject_id_or_key=subject_id_or_key, + entitlement_id=entitlement_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class CustomerOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get_customer_access( + self, customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any + ) -> _models.CustomerAccess: + """Get customer access. + + Get the overall access of a customer. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :return: CustomerAccess. The CustomerAccess is compatible with MutableMapping + :rtype: ~openmeter._generated.models.CustomerAccess + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.CustomerAccess] = kwargs.pop("cls", None) + + _request = build_customer_get_customer_access_request( + customer_id_or_key=customer_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CustomerAccess, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerEntitlementOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_entitlement` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get_customer_entitlement_value( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> _models.EntitlementValue: + """Get customer entitlement value. + + Checks customer access to a given feature (by key). All entitlement types share the hasAccess + property in their value response, but multiple other properties are returned based on the + entitlement type. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param feature_key: Required. + :type feature_key: str + :keyword time: Default value is None. + :paramtype time: ~datetime.datetime + :return: EntitlementValue. The EntitlementValue is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementValue + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementValue] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_get_customer_entitlement_value_request( + customer_id_or_key=customer_id_or_key, + feature_key=feature_key, + time=time, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementValue, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerStripeOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_stripe` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get(self, customer_id_or_key: "_types.ULIDOrExternalKey", **kwargs: Any) -> _models.StripeCustomerAppData: + """Get customer stripe app data. + + Get stripe app data for a customer. Only returns data if the customer billing profile is linked + to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.StripeCustomerAppData] = kwargs.pop("cls", None) + + _request = build_customer_stripe_get_request( + customer_id_or_key=customer_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeCustomerAppData, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: _models.StripeCustomerAppDataBase, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: ~openmeter._generated.models.StripeCustomerAppDataBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Required. + :type app_data: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def upsert( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + app_data: Union[_models.StripeCustomerAppDataBase, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.StripeCustomerAppData: + """Upsert customer stripe app data. + + Upsert stripe app data for a customer. Only updates data if the customer billing profile is + linked to a stripe app. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param app_data: Is one of the following types: StripeCustomerAppDataBase, JSON, IO[bytes] + Required. + :type app_data: ~openmeter._generated.models.StripeCustomerAppDataBase or JSON or IO[bytes] + :return: StripeCustomerAppData. The StripeCustomerAppData is compatible with MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerAppData + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.StripeCustomerAppData] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(app_data, (IOBase, bytes)): + _content = app_data + else: + _content = json.dumps(app_data, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_stripe_upsert_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeCustomerAppData, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: _models.CreateStripeCustomerPortalSessionParams, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Required. + :type params: ~openmeter._generated.models.CreateStripeCustomerPortalSessionParams + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Required. + :type params: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Required. + :type params: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create_portal_session( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + params: Union[_models.CreateStripeCustomerPortalSessionParams, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.StripeCustomerPortalSession: + """Create Stripe customer portal session. + + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param params: Is one of the following types: CreateStripeCustomerPortalSessionParams, JSON, + IO[bytes] Required. + :type params: ~openmeter._generated.models.CreateStripeCustomerPortalSessionParams or JSON or + IO[bytes] + :return: StripeCustomerPortalSession. The StripeCustomerPortalSession is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.StripeCustomerPortalSession + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.StripeCustomerPortalSession] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(params, (IOBase, bytes)): + _content = params + else: + _content = json.dumps(params, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_stripe_create_portal_session_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.StripeCustomerPortalSession, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class MarketplaceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`marketplace` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, *, page: Optional[int] = None, page_size: Optional[int] = None, **kwargs: Any + ) -> _models.MarketplaceListingPaginatedResponse: + """List available apps. + + List available apps of the app marketplace. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: MarketplaceListingPaginatedResponse. The MarketplaceListingPaginatedResponse is + compatible with MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceListingPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MarketplaceListingPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_marketplace_list_request( + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceListingPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, type: Union[str, _models.AppType], **kwargs: Any) -> _models.MarketplaceListing: + """Get app details by type. + + Get a marketplace listing by type. + + :param type: Known values are: "stripe", "sandbox", and "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :return: MarketplaceListing. The MarketplaceListing is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceListing + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MarketplaceListing] = kwargs.pop("cls", None) + + _request = build_marketplace_get_request( + type=type, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceListing, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get_o_auth2_install_url( + self, type: Union[str, _models.AppType], **kwargs: Any + ) -> _models.ClientAppStartResponse: + """Get OAuth2 install URL. + + Install an app via OAuth. Returns a URL to start the OAuth 2.0 flow. + + :param type: Known values are: "stripe", "sandbox", and "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :return: ClientAppStartResponse. The ClientAppStartResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.ClientAppStartResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ClientAppStartResponse] = kwargs.pop("cls", None) + + _request = build_marketplace_get_o_auth2_install_url_request( + type=type, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.ClientAppStartResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def authorize_o_auth2_install( # pylint: disable=inconsistent-return-statements + self, + type: Union[str, _models.AppType], + *, + state: Optional[str] = None, + code: Optional[str] = None, + error: Optional[Union[str, _models.OAuth2AuthorizationCodeGrantErrorType]] = None, + error_description: Optional[str] = None, + error_uri: Optional[str] = None, + **kwargs: Any + ) -> None: + """Install app via OAuth2. + + Authorize OAuth2 code. Verifies the OAuth code and exchanges it for a token and refresh token. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :keyword state: Required if the "state" parameter was present in the client authorization + request. + The exact value received from the client: + + Unique, randomly generated, opaque, and non-guessable string that is sent + when starting an authentication request and validated when processing the response. Default + value is None. + :paramtype state: str + :keyword code: Authorization code which the client will later exchange for an access token. + Required with the success response. Default value is None. + :paramtype code: str + :keyword error: Error code. + Required with the error response. Known values are: "invalid_request", "unauthorized_client", + "access_denied", "unsupported_response_type", "invalid_scope", "server_error", and + "temporarily_unavailable". Default value is None. + :paramtype error: str or ~openmeter.models.OAuth2AuthorizationCodeGrantErrorType + :keyword error_description: Optional human-readable text providing additional information, + used to assist the client developer in understanding the error that occurred. Default value is + None. + :paramtype error_description: str + :keyword error_uri: Optional uri identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error. Default value is None. + :paramtype error_uri: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_marketplace_authorize_o_auth2_install_request( + type=type, + state=state, + code=code, + error=error, + error_description=error_description, + error_uri=error_uri, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [303]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def install_with_api_key( + self, + type: Union[str, _models.AppType], + _: _models.InstallWithApiKeyRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: ~openmeter._generated.models.InstallWithApiKeyRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def install_with_api_key( + self, type: Union[str, _models.AppType], _: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def install_with_api_key( + self, type: Union[str, _models.AppType], _: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def install_with_api_key( + self, + type: Union[str, _models.AppType], + _: Union[_models.InstallWithApiKeyRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app via API key. + + Install an marketplace app via API Key. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Is one of the following types: InstallWithApiKeyRequest, JSON, IO[bytes] Required. + :type _: ~openmeter._generated.models.InstallWithApiKeyRequest or JSON or IO[bytes] + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MarketplaceInstallResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(_, (IOBase, bytes)): + _content = _ + else: + _content = json.dumps(_, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_marketplace_install_with_api_key_request( + type=type, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceInstallResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def install( + self, + type: Union[str, _models.AppType], + _: _models.MarketplaceInstallRequestPayload, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: ~openmeter._generated.models.MarketplaceInstallRequestPayload + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def install( + self, type: Union[str, _models.AppType], _: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def install( + self, type: Union[str, _models.AppType], _: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Required. + :type _: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def install( + self, + type: Union[str, _models.AppType], + _: Union[_models.MarketplaceInstallRequestPayload, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.MarketplaceInstallResponse: + """Install app. + + Install an app from the marketplace. + + :param type: The type of the app to install. Known values are: "stripe", "sandbox", and + "custom_invoicing". Required. + :type type: str or ~openmeter.models.AppType + :param _: Is one of the following types: MarketplaceInstallRequestPayload, JSON, IO[bytes] + Required. + :type _: ~openmeter._generated.models.MarketplaceInstallRequestPayload or JSON or IO[bytes] + :return: MarketplaceInstallResponse. The MarketplaceInstallResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.MarketplaceInstallResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MarketplaceInstallResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(_, (IOBase, bytes)): + _content = _ + else: + _content = json.dumps(_, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_marketplace_install_request( + type=type, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MarketplaceInstallResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class AppCustomInvoicingOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`app_custom_invoicing` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def draft_syncronized( + self, + invoice_id: str, + body: _models.CustomInvoicingDraftSynchronizedRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomInvoicingDraftSynchronizedRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def draft_syncronized( + self, invoice_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def draft_syncronized( + self, invoice_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def draft_syncronized( # pylint: disable=inconsistent-return-statements + self, + invoice_id: str, + body: Union[_models.CustomInvoicingDraftSynchronizedRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Submit draft synchronization results. + + draft_syncronized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Is one of the following types: CustomInvoicingDraftSynchronizedRequest, JSON, + IO[bytes] Required. + :type body: ~openmeter._generated.models.CustomInvoicingDraftSynchronizedRequest or JSON or + IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_custom_invoicing_draft_syncronized_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def finalized( + self, + invoice_id: str, + body: _models.CustomInvoicingFinalizedRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomInvoicingFinalizedRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def finalized(self, invoice_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def finalized( + self, invoice_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def finalized( # pylint: disable=inconsistent-return-statements + self, invoice_id: str, body: Union[_models.CustomInvoicingFinalizedRequest, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Submit issuing synchronization results. + + finalized. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Is one of the following types: CustomInvoicingFinalizedRequest, JSON, IO[bytes] + Required. + :type body: ~openmeter._generated.models.CustomInvoicingFinalizedRequest or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_custom_invoicing_finalized_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def payment_status( + self, + invoice_id: str, + body: _models.CustomInvoicingUpdatePaymentStatusRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: ~openmeter._generated.models.CustomInvoicingUpdatePaymentStatusRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def payment_status( + self, invoice_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def payment_status( + self, invoice_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def payment_status( # pylint: disable=inconsistent-return-statements + self, + invoice_id: str, + body: Union[_models.CustomInvoicingUpdatePaymentStatusRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Update payment status. + + payment_status. + + :param invoice_id: Required. + :type invoice_id: str + :param body: Is one of the following types: CustomInvoicingUpdatePaymentStatusRequest, JSON, + IO[bytes] Required. + :type body: ~openmeter._generated.models.CustomInvoicingUpdatePaymentStatusRequest or JSON or + IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_app_custom_invoicing_payment_status_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class EventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`events` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + client_id: Optional[str] = None, + ingested_at_from: Optional[datetime.datetime] = None, + ingested_at_to: Optional[datetime.datetime] = None, + id: Optional[str] = None, + subject: Optional[str] = None, + customer_id: Optional[List[str]] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + limit: Optional[int] = None, + **kwargs: Any + ) -> List[_models.IngestedEvent]: + """List ingested events. + + List ingested events within a time range. + + If the from query param is not provided it defaults to last 72 hours. + + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword ingested_at_from: Start date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype ingested_at_from: ~datetime.datetime + :keyword ingested_at_to: End date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype ingested_at_to: ~datetime.datetime + :keyword id: The event ID. + + Accepts partial ID. Default value is None. + :paramtype id: str + :keyword subject: The event subject. + + Accepts partial subject. Default value is None. + :paramtype subject: str + :keyword customer_id: The event customer ID. Default value is None. + :paramtype customer_id: list[str] + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. Default value is None. + :paramtype to: ~datetime.datetime + :keyword limit: Number of events to return. Default value is None. + :paramtype limit: int + :return: list of IngestedEvent + :rtype: list[~openmeter._generated.models.IngestedEvent] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.IngestedEvent]] = kwargs.pop("cls", None) + + _request = build_events_list_request( + client_id=client_id, + ingested_at_from=ingested_at_from, + ingested_at_to=ingested_at_to, + id=id, + subject=subject, + customer_id=customer_id, + from_parameter=from_parameter, + to=to, + limit=limit, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.IngestedEvent], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def ingest_event( + self, body: _models.Event, *, content_type: str = "application/cloudevents+json", **kwargs: Any + ) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Required. + :type body: ~openmeter._generated.models.Event + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def ingest_event(self, body: JSON, *, content_type: str = "application/cloudevents+json", **kwargs: Any) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def ingest_event( + self, body: IO[bytes], *, content_type: str = "application/cloudevents+json", **kwargs: Any + ) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/cloudevents+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def ingest_event( # pylint: disable=inconsistent-return-statements + self, body: Union[_models.Event, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Ingest events. + + Ingests an event or batch of events following the CloudEvents specification. + + :param body: Is one of the following types: Event, JSON, IO[bytes] Required. + :type body: ~openmeter._generated.models.Event or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/cloudevents+json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_events_ingest_event_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def ingest_events( + self, body: List[_models.Event], *, content_type: str = "application/cloudevents-batch+json", **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Required. + :type body: list[~openmeter._generated.models.Event] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents-batch+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def ingest_events( + self, body: List[JSON], *, content_type: str = "application/cloudevents-batch+json", **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Required. + :type body: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/cloudevents-batch+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def ingest_events( + self, body: IO[bytes], *, content_type: str = "application/cloudevents-batch+json", **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/cloudevents-batch+json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def ingest_events( # pylint: disable=inconsistent-return-statements + self, body: Union[List[_models.Event], List[JSON], IO[bytes]], **kwargs: Any + ) -> None: + """ingest_events. + + :param body: Is one of the following types: [Event], [JSON], IO[bytes] Required. + :type body: list[~openmeter._generated.models.Event] or list[JSON] or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/cloudevents-batch+json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_events_ingest_events_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def ingest_events_json(self, body: _models.Event, *, content_type: str = "application/json", **kwargs: Any) -> None: + """ingest_events_json. + + :param body: Required. + :type body: ~openmeter._generated.models.Event + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def ingest_events_json( + self, body: List[_models.Event], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """ingest_events_json. + + :param body: Required. + :type body: list[~openmeter._generated.models.Event] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def ingest_events_json( # pylint: disable=inconsistent-return-statements + self, body: "_types.IngestEventsBody", **kwargs: Any + ) -> None: + """ingest_events_json. + + :param body: Is either a Event type or a [Event] type. Required. + :type body: ~openmeter._generated.models.Event or list[~openmeter._generated.models.Event] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, _models.Event): + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + elif isinstance(body, list): + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_events_ingest_events_json_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class EventsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`events_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + limit: Optional[int] = None, + client_id: Optional[str] = None, + filter: Optional[_models.ListRequestFilter] = None, + **kwargs: Any + ) -> ItemPaged["_models.IngestedEvent"]: + """List ingested events. + + List ingested events with advanced filtering and cursor pagination. + + :keyword limit: The limit of the pagination. Default value is None. + :paramtype limit: int + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword filter: The filter for the events encoded as JSON string. Default value is None. + :paramtype filter: ~openmeter._generated.models.ListRequestFilter + :return: An iterator like instance of IngestedEvent + :rtype: ~corehttp.paging.ItemPaged[~openmeter._generated.models.IngestedEvent] + :raises ~corehttp.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.IngestedEvent]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(_continuation_token=None): + + _request = build_events_v2_list_request( + cursor=_continuation_token, + limit=limit, + client_id=client_id, + filter=filter, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.IngestedEvent], + deserialized.get("items", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextCursor") or None, iter(list_of_elem) + + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class MetersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`meters` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.MeterOrderBy]] = None, + include_deleted: Optional[bool] = None, + **kwargs: Any + ) -> List[_models.Meter]: + """List meters. + + List meters. + + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "key", "name", "aggregation", + "createdAt", and "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.MeterOrderBy + :keyword include_deleted: Include deleted meters. Default value is None. + :paramtype include_deleted: bool + :return: list of Meter + :rtype: list[~openmeter._generated.models.Meter] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Meter]] = kwargs.pop("cls", None) + + _request = build_meters_list_request( + page=page, + page_size=page_size, + order=order, + order_by=order_by, + include_deleted=include_deleted, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Meter], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, meter_id_or_slug: str, **kwargs: Any) -> _models.Meter: + """Get meter. + + Get a meter by ID or slug. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Meter] = kwargs.pop("cls", None) + + _request = build_meters_get_request( + meter_id_or_slug=meter_id_or_slug, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Meter, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, meter: _models.MeterCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Required. + :type meter: ~openmeter._generated.models.MeterCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, meter: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Required. + :type meter: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, meter: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Required. + :type meter: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, meter: Union[_models.MeterCreate, JSON, IO[bytes]], **kwargs: Any) -> _models.Meter: + """Create meter. + + Create a meter. + + :param meter: Is one of the following types: MeterCreate, JSON, IO[bytes] Required. + :type meter: ~openmeter._generated.models.MeterCreate or JSON or IO[bytes] + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Meter] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(meter, (IOBase, bytes)): + _content = meter + else: + _content = json.dumps(meter, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_meters_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Meter, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + meter_id_or_slug: str, + meter: _models.MeterUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Required. + :type meter: ~openmeter._generated.models.MeterUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, meter_id_or_slug: str, meter: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Required. + :type meter: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, meter_id_or_slug: str, meter: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Required. + :type meter: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, meter_id_or_slug: str, meter: Union[_models.MeterUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Meter: + """Update meter. + + Update a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param meter: Is one of the following types: MeterUpdate, JSON, IO[bytes] Required. + :type meter: ~openmeter._generated.models.MeterUpdate or JSON or IO[bytes] + :return: Meter. The Meter is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Meter + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Meter] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(meter, (IOBase, bytes)): + _content = meter + else: + _content = json.dumps(meter, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_meters_update_request( + meter_id_or_slug=meter_id_or_slug, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Meter, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, meter_id_or_slug: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete meter. + + Delete a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_meters_delete_request( + meter_id_or_slug=meter_id_or_slug, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def query_json( + self, + meter_id_or_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[List[str]] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + Query meter for usage. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword subject: Filtering by multiple subjects. + + For example: ?subject=subject-1&subject=subject-2. Default value is None. + :paramtype subject: list[str] + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MeterQueryResult] = kwargs.pop("cls", None) + + _request = build_meters_query_json_request( + meter_id_or_slug=meter_id_or_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + subject=subject, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MeterQueryResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + def query_csv( + self, + meter_id_or_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + subject: Optional[List[str]] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> str: + """query_csv. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword subject: Filtering by multiple subjects. + + For example: ?subject=subject-1&subject=subject-2. Default value is None. + :paramtype subject: list[str] + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_meters_query_csv_request( + meter_id_or_slug=meter_id_or_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + subject=subject, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def query( + self, + meter_id_or_slug: str, + request: _models.MeterQueryRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Required. + :type request: ~openmeter._generated.models.MeterQueryRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def query( + self, meter_id_or_slug: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def query( + self, meter_id_or_slug: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def query( + self, meter_id_or_slug: str, request: Union[_models.MeterQueryRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + query. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param request: Is one of the following types: MeterQueryRequest, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.MeterQueryRequest or JSON or IO[bytes] + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MeterQueryResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_meters_query_request( + meter_id_or_slug=meter_id_or_slug, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MeterQueryResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + def query_csv_post(self, meter_id_or_slug: str, **kwargs: Any) -> str: + """query_csv_post. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_meters_query_csv_post_request( + meter_id_or_slug=meter_id_or_slug, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + def list_subjects( + self, + meter_id_or_slug: str, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> List[str]: + """List meter subjects. + + List subjects for a meter. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. Defaults to the beginning of time. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :return: list of str + :rtype: list[str] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[str]] = kwargs.pop("cls", None) + + _request = build_meters_list_subjects_request( + meter_id_or_slug=meter_id_or_slug, + from_parameter=from_parameter, + to=to, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[str], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list_group_by_values( + self, + meter_id_or_slug: str, + group_by_key: str, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> List[str]: + """List meter group by values. + + List meter group by values. + + :param meter_id_or_slug: Required. + :type meter_id_or_slug: str + :param group_by_key: Required. + :type group_by_key: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. Defaults to 24 hours ago. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :return: list of str + :rtype: list[str] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[str]] = kwargs.pop("cls", None) + + _request = build_meters_list_group_by_values_request( + meter_id_or_slug=meter_id_or_slug, + group_by_key=group_by_key, + from_parameter=from_parameter, + to=to, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[str], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class SubjectsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`subjects` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list(self, **kwargs: Any) -> List[_models.Subject]: + """List subjects. + + List subjects. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Subject]] = kwargs.pop("cls", None) + + _request = build_subjects_list_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Subject], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, subject_id_or_key: str, **kwargs: Any) -> _models.Subject: + """Get subject. + + Get subject by ID or key. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :return: Subject. The Subject is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Subject + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Subject] = kwargs.pop("cls", None) + + _request = build_subjects_get_request( + subject_id_or_key=subject_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Subject, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def upsert( + self, subject: List[_models.SubjectUpsert], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Required. + :type subject: list[~openmeter._generated.models.SubjectUpsert] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert( + self, subject: List[JSON], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Required. + :type subject: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert( + self, subject: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Required. + :type subject: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def upsert( + self, subject: Union[List[_models.SubjectUpsert], List[JSON], IO[bytes]], **kwargs: Any + ) -> List[_models.Subject]: + """Upsert subject. + + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject: Is one of the following types: [SubjectUpsert], [JSON], IO[bytes] Required. + :type subject: list[~openmeter._generated.models.SubjectUpsert] or list[JSON] or IO[bytes] + :return: list of Subject + :rtype: list[~openmeter._generated.models.Subject] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.Subject]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(subject, (IOBase, bytes)): + _content = subject + else: + _content = json.dumps(subject, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_subjects_upsert_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Subject], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, subject_id_or_key: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete subject. + + Delete subject by ID or key. + + ⚠️ **Deprecated**: Subjects as managable entities are being depracated, use customers with + subject key usage attribution instead. + + :param subject_id_or_key: Required. + :type subject_id_or_key: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_subjects_delete_request( + subject_id_or_key=subject_id_or_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class DebugOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`debug` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def metrics(self, **kwargs: Any) -> str: + """Get event metrics. + + Returns debug metrics (in OpenMetrics format) like the number of ingested events since + mindnight UTC. + + The OpenMetrics Counter(s) reset every day at midnight UTC. + + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_debug_metrics_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class NotificationChannelsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`notification_channels` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_deleted: Optional[bool] = None, + include_disabled: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationChannelOrderBy]] = None, + **kwargs: Any + ) -> _models.NotificationChannelPaginatedResponse: + """List notification channels. + + List all notification channels. + + :keyword include_deleted: Include deleted notification channels in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword include_disabled: Include disabled notification channels in response. + + Usage: ``?includeDisabled=false``. Default value is None. + :paramtype include_disabled: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "type", "createdAt", and + "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.NotificationChannelOrderBy + :return: NotificationChannelPaginatedResponse. The NotificationChannelPaginatedResponse is + compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationChannelPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationChannelPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_notification_channels_list_request( + include_deleted=include_deleted, + include_disabled=include_disabled, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationChannelPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, + request: _models.NotificationChannelWebhookCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationChannel": + """Create a notification channel. + + Create a new notification channel. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, request: "_types.NotificationChannelCreateRequest", **kwargs: Any) -> "_types.NotificationChannel": + """Create a notification channel. + + Create a new notification channel. + + :param request: Is one of the following types: NotificationChannelWebhookCreateRequest + Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationChannel"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_channels_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationChannel", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + channel_id: str, + request: _models.NotificationChannelWebhookCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationChannel": + """Update a notification channel. + + Update notification channel. + + :param channel_id: Required. + :type channel_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, channel_id: str, request: "_types.NotificationChannelCreateRequest", **kwargs: Any + ) -> "_types.NotificationChannel": + """Update a notification channel. + + Update notification channel. + + :param channel_id: Required. + :type channel_id: str + :param request: Is one of the following types: NotificationChannelWebhookCreateRequest + Required. + :type request: ~openmeter._generated.models.NotificationChannelWebhookCreateRequest + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationChannel"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_channels_update_request( + channel_id=channel_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationChannel", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, channel_id: str, **kwargs: Any) -> "_types.NotificationChannel": + """Get notification channel. + + Get a notification channel by id. + + :param channel_id: Required. + :type channel_id: str + :return: NotificationChannelWebhook + :rtype: ~openmeter._generated.models.NotificationChannelWebhook + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.NotificationChannel"] = kwargs.pop("cls", None) + + _request = build_notification_channels_get_request( + channel_id=channel_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationChannel", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, channel_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a notification channel. + + Soft delete notification channel by id. + + Once a notification channel is deleted it cannot be undeleted. + + :param channel_id: Required. + :type channel_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_notification_channels_delete_request( + channel_id=channel_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class NotificationRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`notification_rules` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_deleted: Optional[bool] = None, + include_disabled: Optional[bool] = None, + feature: Optional[List[str]] = None, + channel: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationRuleOrderBy]] = None, + **kwargs: Any + ) -> _models.NotificationRulePaginatedResponse: + """List notification rules. + + List all notification rules. + + :keyword include_deleted: Include deleted notification rules in response. + + Usage: ``?includeDeleted=true``. Default value is None. + :paramtype include_deleted: bool + :keyword include_disabled: Include disabled notification rules in response. + + Usage: ``?includeDisabled=false``. Default value is None. + :paramtype include_disabled: bool + :keyword feature: Filtering by multiple feature ids/keys. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword channel: Filtering by multiple notifiaction channel ids. + + Usage: ``?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3``. Default + value is None. + :paramtype channel: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "type", "createdAt", and + "updatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.NotificationRuleOrderBy + :return: NotificationRulePaginatedResponse. The NotificationRulePaginatedResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.NotificationRulePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationRulePaginatedResponse] = kwargs.pop("cls", None) + + _request = build_notification_rules_list_request( + include_deleted=include_deleted, + include_disabled=include_disabled, + feature=feature, + channel=channel, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationRulePaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, + request: _models.NotificationRuleBalanceThresholdCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + request: _models.NotificationRuleEntitlementResetCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + request: _models.NotificationRuleInvoiceCreatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, + request: _models.NotificationRuleInvoiceUpdatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, request: "_types.NotificationRuleCreateRequest", **kwargs: Any) -> "_types.NotificationRule": + """Create a notification rule. + + Create a new notification rule. + + :param request: Is one of the following types: NotificationRuleBalanceThresholdCreateRequest, + NotificationRuleEntitlementResetCreateRequest, NotificationRuleInvoiceCreatedCreateRequest, + NotificationRuleInvoiceUpdatedCreateRequest Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest or + ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationRule"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_rules_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationRule", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + rule_id: str, + request: _models.NotificationRuleBalanceThresholdCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + rule_id: str, + request: _models.NotificationRuleEntitlementResetCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + rule_id: str, + request: _models.NotificationRuleInvoiceCreatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, + rule_id: str, + request: _models.NotificationRuleInvoiceUpdatedCreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, rule_id: str, request: "_types.NotificationRuleCreateRequest", **kwargs: Any + ) -> "_types.NotificationRule": + """Update a notification rule. + + Update notification rule. + + :param rule_id: Required. + :type rule_id: str + :param request: Is one of the following types: NotificationRuleBalanceThresholdCreateRequest, + NotificationRuleEntitlementResetCreateRequest, NotificationRuleInvoiceCreatedCreateRequest, + NotificationRuleInvoiceUpdatedCreateRequest Required. + :type request: ~openmeter._generated.models.NotificationRuleBalanceThresholdCreateRequest or + ~openmeter._generated.models.NotificationRuleEntitlementResetCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceCreatedCreateRequest or + ~openmeter._generated.models.NotificationRuleInvoiceUpdatedCreateRequest + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.NotificationRule"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_rules_update_request( + rule_id=rule_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationRule", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, rule_id: str, **kwargs: Any) -> "_types.NotificationRule": + """Get notification rule. + + Get a notification rule by id. + + :param rule_id: Required. + :type rule_id: str + :return: NotificationRuleBalanceThreshold or NotificationRuleEntitlementReset or + NotificationRuleInvoiceCreated or NotificationRuleInvoiceUpdated + :rtype: ~openmeter._generated.models.NotificationRuleBalanceThreshold or + ~openmeter._generated.models.NotificationRuleEntitlementReset or + ~openmeter._generated.models.NotificationRuleInvoiceCreated or + ~openmeter._generated.models.NotificationRuleInvoiceUpdated + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.NotificationRule"] = kwargs.pop("cls", None) + + _request = build_notification_rules_get_request( + rule_id=rule_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.NotificationRule", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, rule_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a notification rule. + + Soft delete notification rule by id. + + Once a notification rule is deleted it cannot be undeleted. + + :param rule_id: Required. + :type rule_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_notification_rules_delete_request( + rule_id=rule_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def test(self, rule_id: str, **kwargs: Any) -> _models.NotificationEvent: + """Test notification rule. + + Test a notification rule by sending a test event with random data. + + :param rule_id: Required. + :type rule_id: str + :return: NotificationEvent. The NotificationEvent is compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationEvent + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationEvent] = kwargs.pop("cls", None) + + _request = build_notification_rules_test_request( + rule_id=rule_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationEvent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class NotificationEventsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`notification_events` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + feature: Optional[List[str]] = None, + subject: Optional[List[str]] = None, + rule: Optional[List[str]] = None, + channel: Optional[List[str]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.NotificationEventOrderBy]] = None, + **kwargs: Any + ) -> _models.NotificationEventPaginatedResponse: + """List notification events. + + List all notification events. + + :keyword from_parameter: Start date-time in RFC 3339 format. + Inclusive. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + Inclusive. Default value is None. + :paramtype to: ~datetime.datetime + :keyword feature: Filtering by multiple feature ids or keys. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword subject: Filtering by multiple subject ids or keys. + + Usage: ``?subject=subject-1&subject=subject-2``. Default value is None. + :paramtype subject: list[str] + :keyword rule: Filtering by multiple rule ids. + + Usage: ``?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5``. Default value is + None. + :paramtype rule: list[str] + :keyword channel: Filtering by multiple channel ids. + + Usage: ``?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J``. Default + value is None. + :paramtype channel: list[str] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id" and "createdAt". Default value is + None. + :paramtype order_by: str or ~openmeter.models.NotificationEventOrderBy + :return: NotificationEventPaginatedResponse. The NotificationEventPaginatedResponse is + compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationEventPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationEventPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_notification_events_list_request( + from_parameter=from_parameter, + to=to, + feature=feature, + subject=subject, + rule=rule, + channel=channel, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationEventPaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, event_id: str, **kwargs: Any) -> _models.NotificationEvent: + """Get notification event. + + Get a notification event by id. + + :param event_id: Required. + :type event_id: str + :return: NotificationEvent. The NotificationEvent is compatible with MutableMapping + :rtype: ~openmeter._generated.models.NotificationEvent + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.NotificationEvent] = kwargs.pop("cls", None) + + _request = build_notification_events_get_request( + event_id=event_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.NotificationEvent, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def resend( + self, + event_id: str, + request: _models.NotificationEventResendRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Required. + :type request: ~openmeter._generated.models.NotificationEventResendRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def resend(self, event_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def resend( + self, event_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def resend( # pylint: disable=inconsistent-return-statements + self, event_id: str, request: Union[_models.NotificationEventResendRequest, JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Re-send notification event. + + resend. + + :param event_id: Required. + :type event_id: str + :param request: Is one of the following types: NotificationEventResendRequest, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.NotificationEventResendRequest or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_notification_events_resend_request( + event_id=event_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class EntitlementsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`entitlements_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + feature: Optional[List[str]] = None, + customer_keys: Optional[List[str]] = None, + customer_ids: Optional[List[str]] = None, + entitlement_type: Optional[List[Union[str, _models.EntitlementType]]] = None, + exclude_inactive: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any + ) -> _models.EntitlementV2PaginatedResponse: + """List all entitlements. + + List all entitlements for all the customers and features. This endpoint is intended for + administrative purposes only. To fetch the entitlements of a specific subject please use the + /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword customer_keys: Filtering by multiple customers. + + Usage: ``?customerKeys=customer-1&customerKeys=customer-3``. Default value is None. + :paramtype customer_keys: list[str] + :keyword customer_ids: Filtering by multiple customers. + + Usage: ``?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9``. + Default value is None. + :paramtype customer_ids: list[str] + :keyword entitlement_type: Filtering by multiple entitlement types. + + Usage: ``?entitlementType=metered&entitlementType=boolean``. Default value is None. + :paramtype entitlement_type: list[str or ~openmeter.models.EntitlementType] + :keyword exclude_inactive: Exclude inactive entitlements in the response (those scheduled for + later or earlier). Default value is None. + :paramtype exclude_inactive: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt" and "updatedAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.EntitlementOrderBy + :return: EntitlementV2PaginatedResponse. The EntitlementV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.EntitlementV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_entitlements_v2_list_request( + feature=feature, + customer_keys=customer_keys, + customer_ids=customer_ids, + entitlement_type=entitlement_type, + exclude_inactive=exclude_inactive, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get(self, entitlement_id: str, **kwargs: Any) -> "_types.EntitlementV2": + """Get entitlement by ID. + + Get entitlement by ID. + + :param entitlement_id: Required. + :type entitlement_id: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + _request = build_entitlements_v2_get_request( + entitlement_id=entitlement_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerEntitlementsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_entitlements_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementMeteredV2CreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def post( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement: "_types.EntitlementV2CreateInputs", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Create a customer entitlement. + + OpenMeter has three types of entitlements: metered, boolean, and static. The type property + determines the type of entitlement. The underlying feature has to be compatible with the + entitlement type specified in the request (e.g., a metered entitlement needs a feature + associated with a meter). + + + + * Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * Static entitlements let you pass along a configuration while granting access, e.g. "Using + this feature with X Y settings" (passed in the config). + * Metered entitlements have many use cases, from setting up usage-based access to implementing + complex credit systems. Example: The customer can use 10000 AI tokens during the usage period + of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try + to create a new entitlement for a featureKey that already has an active entitlement, the + request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement: Is one of the following types: EntitlementMeteredV2CreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlements_v2_post_request( + customer_id_or_key=customer_id_or_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + *, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.EntitlementOrderBy]] = None, + **kwargs: Any + ) -> _models.EntitlementV2PaginatedResponse: + """List customer entitlements. + + List all entitlements for a customer. For checking entitlement access, use the /value endpoint + instead. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt" and "updatedAt". Default + value is None. + :paramtype order_by: str or ~openmeter.models.EntitlementOrderBy + :return: EntitlementV2PaginatedResponse. The EntitlementV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.EntitlementV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_entitlements_v2_list_request( + customer_id_or_key=customer_id_or_key, + include_deleted=include_deleted, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get( + self, customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any + ) -> "_types.EntitlementV2": + """Get customer entitlement. + + Get entitlement by feature key. For checking entitlement access, use the /value endpoint + instead. If featureKey is used, the entitlement is resolved for the current timestamp. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + _request = build_customer_entitlements_v2_get_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete( # pylint: disable=inconsistent-return-statements + self, customer_id_or_key: "_types.ULIDOrExternalKey", entitlement_id_or_feature_key: str, **kwargs: Any + ) -> None: + """Delete customer entitlement. + + Deleting an entitlement revokes access to the associated feature. As a single customer can only + have one entitlement per featureKey, when "migrating" features you have to delete the old + entitlements as well. As access and status checks can be historical queries, deleting an + entitlement populates the deletedAt timestamp. When queried for a time before that, the + entitlement is still considered active, you cannot have retroactive changes to access, which is + important for, among other things, auditing. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customer_entitlements_v2_delete_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementMeteredV2CreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementStaticCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementStaticCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: _models.EntitlementBooleanCreateInputs, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Required. + :type entitlement: ~openmeter._generated.models.EntitlementBooleanCreateInputs + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def override( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: "_types.ULIDOrExternalKey", + entitlement: "_types.EntitlementV2CreateInputs", + **kwargs: Any + ) -> "_types.EntitlementV2": + """Override customer entitlement. + + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes + the previous entitlement for the provided customer-feature pair. If the previous entitlement is + already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require + a new entitlement to be created with zero downtime. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Is one of the following types: str Required. + :type entitlement_id_or_feature_key: str or str + :param entitlement: Is one of the following types: EntitlementMeteredV2CreateInputs, + EntitlementStaticCreateInputs, EntitlementBooleanCreateInputs Required. + :type entitlement: ~openmeter._generated.models.EntitlementMeteredV2CreateInputs or + ~openmeter._generated.models.EntitlementStaticCreateInputs or + ~openmeter._generated.models.EntitlementBooleanCreateInputs + :return: EntitlementMeteredV2 or EntitlementStaticV2 or EntitlementBooleanV2 + :rtype: ~openmeter._generated.models.EntitlementMeteredV2 or + ~openmeter._generated.models.EntitlementStaticV2 or + ~openmeter._generated.models.EntitlementBooleanV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType["_types.EntitlementV2"] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = json.dumps(entitlement, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlements_v2_override_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize("_types.EntitlementV2", response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerEntitlementV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_entitlement_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get_grants( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> _models.GrantV2PaginatedResponse: + """List customer entitlement grants. + + List all grants issued for an entitlement. The entitlement can be defined either by its id or + featureKey. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword include_deleted: Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "createdAt", and "updatedAt". + Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: GrantV2PaginatedResponse. The GrantV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.GrantV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.GrantV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_v2_get_grants_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + include_deleted=include_deleted, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.GrantV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: _models.EntitlementGrantCreateInputV2, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInputV2 + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Required. + :type grant: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create_customer_entitlement_grant( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + grant: Union[_models.EntitlementGrantCreateInputV2, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.EntitlementGrantV2: + """Create customer entitlement grant. + + Grants define a behavior of granting usage for a metered entitlement. They can have complicated + recurrence and rollover rules, thanks to which you can define a wide range of access patterns + with a single grant, in most cases you don't have to periodically create new grants. You can + only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is + in effect between its effective date and its expiration date. Specifying both is mandatory for + new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher + priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For + example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover + settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. + Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is + deterministic regardless of when it is queried. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param grant: Is one of the following types: EntitlementGrantCreateInputV2, JSON, IO[bytes] + Required. + :type grant: ~openmeter._generated.models.EntitlementGrantCreateInputV2 or JSON or IO[bytes] + :return: EntitlementGrantV2. The EntitlementGrantV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementGrantV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EntitlementGrantV2] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(grant, (IOBase, bytes)): + _content = grant + else: + _content = json.dumps(grant, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlement_v2_create_customer_entitlement_grant_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 409: + error = _failsafe_deserialize(_models.ConflictProblemResponse, response) + raise ResourceExistsError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementGrantV2, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get_customer_entitlement_value( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + time: Optional[datetime.datetime] = None, + **kwargs: Any + ) -> _models.EntitlementValueV2: + """Get customer entitlement value. + + Checks customer access to a given feature (by key). All entitlement types share the hasAccess + property in their value response, but multiple other properties are returned based on the + entitlement type. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword time: Default value is None. + :paramtype time: ~datetime.datetime + :return: EntitlementValueV2. The EntitlementValueV2 is compatible with MutableMapping + :rtype: ~openmeter._generated.models.EntitlementValueV2 + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.EntitlementValueV2] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_v2_get_customer_entitlement_value_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + time=time, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EntitlementValueV2, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get_customer_entitlement_history( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + *, + window_size: Union[str, _models.WindowSize], + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_time_zone: Optional[str] = None, + **kwargs: Any + ) -> _models.WindowedBalanceHistory: + """Get customer entitlement history. + + Returns historical balance and usage data for the entitlement. The queried history can span + accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by + events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information + and the list of grants that were being burnt down in that window. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :keyword window_size: Windowsize. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". + Required. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword from_parameter: Start of time range to query entitlement: date-time in RFC 3339 + format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End of time range to query entitlement: date-time in RFC 3339 format. Defaults to + now. + If not now then gets truncated to the granularity of the underlying meter. Default value is + None. + :paramtype to: ~datetime.datetime + :keyword window_time_zone: The timezone used when calculating the windows. Default value is + None. + :paramtype window_time_zone: str + :return: WindowedBalanceHistory. The WindowedBalanceHistory is compatible with MutableMapping + :rtype: ~openmeter._generated.models.WindowedBalanceHistory + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.WindowedBalanceHistory] = kwargs.pop("cls", None) + + _request = build_customer_entitlement_v2_get_customer_entitlement_history_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + window_size=window_size, + from_parameter=from_parameter, + to=to, + window_time_zone=window_time_zone, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.WindowedBalanceHistory, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: _models.ResetEntitlementUsageInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Required. + :type reset: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def reset_customer_entitlement( + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Required. + :type reset: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def reset_customer_entitlement( # pylint: disable=inconsistent-return-statements + self, + customer_id_or_key: "_types.ULIDOrExternalKey", + entitlement_id_or_feature_key: str, + reset: Union[_models.ResetEntitlementUsageInput, JSON, IO[bytes]], + **kwargs: Any + ) -> None: + """Reset customer entitlement. + + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. + At the start of a period usage is zerod out and grants are rolled over based on their rollover + settings. It would typically be synced with the customers billing period to enforce usage based + on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this + endpoint allows to manually reset it at any time. When doing so the period anchor of the + entitlement can be changed if needed. + + :param customer_id_or_key: Is one of the following types: str Required. + :type customer_id_or_key: str or str + :param entitlement_id_or_feature_key: Required. + :type entitlement_id_or_feature_key: str + :param reset: Is one of the following types: ResetEntitlementUsageInput, JSON, IO[bytes] + Required. + :type reset: ~openmeter._generated.models.ResetEntitlementUsageInput or JSON or IO[bytes] + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(reset, (IOBase, bytes)): + _content = reset + else: + _content = json.dumps(reset, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_entitlement_v2_reset_customer_entitlement_request( + customer_id_or_key=customer_id_or_key, + entitlement_id_or_feature_key=entitlement_id_or_feature_key, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + elif response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class GrantsV2Operations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`grants_v2` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + feature: Optional[List[str]] = None, + customer: Optional[List["_types.ULIDOrExternalKey"]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + offset: Optional[int] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.GrantOrderBy]] = None, + **kwargs: Any + ) -> _models.GrantV2PaginatedResponse: + """List grants. + + List all grants for all the customers and entitlements. This endpoint is intended for + administrative purposes only. To fetch the grants of a specific entitlement please use the + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + + :keyword feature: Filtering by multiple features. + + Usage: ``?feature=feature-1&feature=feature-2``. Default value is None. + :paramtype feature: list[str] + :keyword customer: Filtering by multiple customers (either by ID or key). + + Usage: ``?customer=customer-1&customer=customer-2``. Default value is None. + :paramtype customer: list[str or str] + :keyword include_deleted: Include deleted. Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword offset: Number of items to skip. + + Default is 0. Default value is None. + :paramtype offset: int + :keyword limit: Number of items to return. + + Default is 100. Default value is None. + :paramtype limit: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "id", "createdAt", and "updatedAt". + Default value is None. + :paramtype order_by: str or ~openmeter.models.GrantOrderBy + :return: GrantV2PaginatedResponse. The GrantV2PaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.GrantV2PaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.GrantV2PaginatedResponse] = kwargs.pop("cls", None) + + _request = build_grants_v2_list_request( + feature=feature, + customer=customer, + include_deleted=include_deleted, + page=page, + page_size=page_size, + offset=offset, + limit=limit, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.GrantV2PaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BillingProfilesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`billing_profiles` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( + self, + *, + include_archived: Optional[bool] = None, + expand: Optional[List[Union[str, _models.BillingProfileExpand]]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.BillingProfileOrderBy]] = None, + **kwargs: Any + ) -> _models.BillingProfilePaginatedResponse: + """List billing profiles. + + List all billing profiles matching the specified filters. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing + profile + will be included in the response. + + :keyword include_archived: Default value is None. + :paramtype include_archived: bool + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileExpand] + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "createdAt", "updatedAt", "default", + and "name". Default value is None. + :paramtype order_by: str or ~openmeter.models.BillingProfileOrderBy + :return: BillingProfilePaginatedResponse. The BillingProfilePaginatedResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfilePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfilePaginatedResponse] = kwargs.pop("cls", None) + + _request = build_billing_profiles_list_request( + include_archived=include_archived, + expand=expand, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfilePaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, profile: _models.BillingProfileCreate, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Required. + :type profile: ~openmeter._generated.models.BillingProfileCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, profile: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Required. + :type profile: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create( + self, profile: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Required. + :type profile: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create( + self, profile: Union[_models.BillingProfileCreate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.BillingProfile: + """Create a new billing profile. + + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + + :param profile: Is one of the following types: BillingProfileCreate, JSON, IO[bytes] Required. + :type profile: ~openmeter._generated.models.BillingProfileCreate or JSON or IO[bytes] + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(profile, (IOBase, bytes)): + _content = profile + else: + _content = json.dumps(profile, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_billing_profiles_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfile, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a billing profile. + + Delete a billing profile by id. + + Only such billing profiles can be deleted that are: + + * not the default one + * not pinned to any customer using customer overrides + * only have finalized invoices. + + :param id: Required. + :type id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_billing_profiles_delete_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + def get( + self, id: str, *, expand: Optional[List[Union[str, _models.BillingProfileExpand]]] = None, **kwargs: Any + ) -> _models.BillingProfile: + """Get a billing profile. + + Get a billing profile by id. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing + profile + will be included in the response. + + :param id: Required. + :type id: str + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileExpand] + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None) + + _request = build_billing_profiles_get_request( + id=id, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfile, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def update( + self, + id: str, + profile: _models.BillingProfileReplaceUpdateWithWorkflow, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Required. + :type profile: ~openmeter._generated.models.BillingProfileReplaceUpdateWithWorkflow + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, id: str, profile: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Required. + :type profile: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update( + self, id: str, profile: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Required. + :type profile: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update( + self, id: str, profile: Union[_models.BillingProfileReplaceUpdateWithWorkflow, JSON, IO[bytes]], **kwargs: Any + ) -> _models.BillingProfile: + """Update a billing profile. + + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + + :param id: Required. + :type id: str + :param profile: Is one of the following types: BillingProfileReplaceUpdateWithWorkflow, JSON, + IO[bytes] Required. + :type profile: ~openmeter._generated.models.BillingProfileReplaceUpdateWithWorkflow or JSON or + IO[bytes] + :return: BillingProfile. The BillingProfile is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfile + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BillingProfile] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(profile, (IOBase, bytes)): + _content = profile + else: + _content = json.dumps(profile, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_billing_profiles_update_request( + id=id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfile, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerOverridesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_overrides` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list( # pylint: disable=too-many-locals + self, + *, + billing_profile: Optional[List[str]] = None, + customers_without_pinned_profile: Optional[bool] = None, + include_all_customers: Optional[bool] = None, + customer_id: Optional[List[str]] = None, + customer_name: Optional[str] = None, + customer_key: Optional[str] = None, + customer_primary_email: Optional[str] = None, + expand: Optional[List[Union[str, _models.BillingProfileCustomerOverrideExpand]]] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.BillingProfileCustomerOverrideOrderBy]] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse: + """List customer overrides. + + List customer overrides using the specified filters. + + The response will include the customer override values and the merged billing profile values. + + If the includeAllCustomers is set to true, the list contains all customers. This mode is + useful for getting the current effective billing workflow settings for all users regardless + if they have customer orverrides or not. + + :keyword billing_profile: Filter by billing profile. Default value is None. + :paramtype billing_profile: list[str] + :keyword customers_without_pinned_profile: Only return customers without pinned billing + profiles. This implicitly sets includeAllCustomers to true. Default value is None. + :paramtype customers_without_pinned_profile: bool + :keyword include_all_customers: Include customers without customer overrides. + + If set to false only the customers specifically associated with a billing profile will be + returned. + + If set to true, in case of the default billing profile, all customers will be returned. + Default value is None. + :paramtype include_all_customers: bool + :keyword customer_id: Filter by customer id. Default value is None. + :paramtype customer_id: list[str] + :keyword customer_name: Filter by customer name. Default value is None. + :paramtype customer_name: str + :keyword customer_key: Filter by customer key. Default value is None. + :paramtype customer_key: str + :keyword customer_primary_email: Filter by customer primary email. Default value is None. + :paramtype customer_primary_email: str + :keyword expand: Expand the response with additional details. Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileCustomerOverrideExpand] + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "customerId", "customerName", + "customerKey", "customerPrimaryEmail", and "customerCreatedAt". Default value is None. + :paramtype order_by: str or ~openmeter.models.BillingProfileCustomerOverrideOrderBy + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :return: BillingProfileCustomerOverrideWithDetailsPaginatedResponse. The + BillingProfileCustomerOverrideWithDetailsPaginatedResponse is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse] = kwargs.pop("cls", None) + + _request = build_customer_overrides_list_request( + billing_profile=billing_profile, + customers_without_pinned_profile=customers_without_pinned_profile, + include_all_customers=include_all_customers, + customer_id=customer_id, + customer_name=customer_name, + customer_key=customer_key, + customer_primary_email=customer_primary_email, + expand=expand, + order=order, + order_by=order_by, + page=page, + page_size=page_size, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize( + _models.BillingProfileCustomerOverrideWithDetailsPaginatedResponse, response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def upsert( + self, + customer_id: str, + request: _models.BillingProfileCustomerOverrideCreate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: ~openmeter._generated.models.BillingProfileCustomerOverrideCreate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert( + self, customer_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def upsert( + self, customer_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def upsert( + self, + customer_id: str, + request: Union[_models.BillingProfileCustomerOverrideCreate, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Create a new or update a customer override. + + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + + :param customer_id: Required. + :type customer_id: str + :param request: Is one of the following types: BillingProfileCustomerOverrideCreate, JSON, + IO[bytes] Required. + :type request: ~openmeter._generated.models.BillingProfileCustomerOverrideCreate or JSON or + IO[bytes] + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.BillingProfileCustomerOverrideWithDetails] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_overrides_upsert_request( + customer_id=customer_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfileCustomerOverrideWithDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def get( + self, + customer_id: str, + *, + expand: Optional[List[Union[str, _models.BillingProfileCustomerOverrideExpand]]] = None, + **kwargs: Any + ) -> _models.BillingProfileCustomerOverrideWithDetails: + """Get a customer override. + + Get a customer override by customer id. + + The response will include the customer override values and the merged billing profile values. + + If the customer override is not found, the default billing profile's values are returned. This + behavior + allows for getting a merged profile regardless of the customer override existence. + + :param customer_id: Required. + :type customer_id: str + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.BillingProfileCustomerOverrideExpand] + :return: BillingProfileCustomerOverrideWithDetails. The + BillingProfileCustomerOverrideWithDetails is compatible with MutableMapping + :rtype: ~openmeter._generated.models.BillingProfileCustomerOverrideWithDetails + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.BillingProfileCustomerOverrideWithDetails] = kwargs.pop("cls", None) + + _request = build_customer_overrides_get_request( + customer_id=customer_id, + expand=expand, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.BillingProfileCustomerOverrideWithDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete(self, customer_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a customer override. + + Delete a customer override by customer id. + + This will remove the customer override and the customer will be subject to the default + billing profile's settings again. + + :param customer_id: Required. + :type customer_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_customer_overrides_delete_request( + customer_id=customer_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class InvoicesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`invoices` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def invoice_pending_lines_action( + self, request: _models.InvoicePendingLinesActionInput, *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Required. + :type request: ~openmeter._generated.models.InvoicePendingLinesActionInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def invoice_pending_lines_action( + self, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def invoice_pending_lines_action( + self, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def invoice_pending_lines_action( + self, request: Union[_models.InvoicePendingLinesActionInput, JSON, IO[bytes]], **kwargs: Any + ) -> List[_models.Invoice]: + """Invoice a customer based on the pending line items. + + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the + normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice + will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing + cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + + :param request: Is one of the following types: InvoicePendingLinesActionInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.InvoicePendingLinesActionInput or JSON or IO[bytes] + :return: list of Invoice + :rtype: list[~openmeter._generated.models.Invoice] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[List[_models.Invoice]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_invoices_invoice_pending_lines_action_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Invoice], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list( # pylint: disable=too-many-locals + self, + *, + statuses: Optional[List[Union[str, _models.InvoiceStatus]]] = None, + extended_statuses: Optional[List[str]] = None, + issued_after: Optional[datetime.datetime] = None, + issued_before: Optional[datetime.datetime] = None, + period_start_after: Optional[datetime.datetime] = None, + period_start_before: Optional[datetime.datetime] = None, + created_after: Optional[datetime.datetime] = None, + created_before: Optional[datetime.datetime] = None, + expand: Optional[List[Union[str, _models.InvoiceExpand]]] = None, + customers: Optional[List[str]] = None, + include_deleted: Optional[bool] = None, + page: Optional[int] = None, + page_size: Optional[int] = None, + order: Optional[Union[str, _models.SortOrder]] = None, + order_by: Optional[Union[str, _models.InvoiceOrderBy]] = None, + **kwargs: Any + ) -> _models.InvoicePaginatedResponse: + """List invoices. + + List invoices based on the specified filters. + + The expand option can be used to include additional information (besides the invoice header and + totals) + in the response. For example by adding the expand=lines option the invoice lines will be + included in the response. + + Gathering invoices will always show the current usage calculated on the fly. + + :keyword statuses: Filter by the invoice status. Default value is None. + :paramtype statuses: list[str or ~openmeter.models.InvoiceStatus] + :keyword extended_statuses: Filter by invoice extended statuses. Default value is None. + :paramtype extended_statuses: list[str] + :keyword issued_after: Filter by invoice issued time. + Inclusive. Default value is None. + :paramtype issued_after: ~datetime.datetime + :keyword issued_before: Filter by invoice issued time. + Inclusive. Default value is None. + :paramtype issued_before: ~datetime.datetime + :keyword period_start_after: Filter by period start time. + Inclusive. Default value is None. + :paramtype period_start_after: ~datetime.datetime + :keyword period_start_before: Filter by period start time. + Inclusive. Default value is None. + :paramtype period_start_before: ~datetime.datetime + :keyword created_after: Filter by invoice created time. + Inclusive. Default value is None. + :paramtype created_after: ~datetime.datetime + :keyword created_before: Filter by invoice created time. + Inclusive. Default value is None. + :paramtype created_before: ~datetime.datetime + :keyword expand: What parts of the list output to expand in listings. Default value is None. + :paramtype expand: list[str or ~openmeter.models.InvoiceExpand] + :keyword customers: Filter by customer ID. Default value is None. + :paramtype customers: list[str] + :keyword include_deleted: Include deleted invoices. Default value is None. + :paramtype include_deleted: bool + :keyword page: Page index. + + Default is 1. Default value is None. + :paramtype page: int + :keyword page_size: The maximum number of items per page. + + Default is 100. Default value is None. + :paramtype page_size: int + :keyword order: The order direction. Known values are: "ASC" and "DESC". Default value is None. + :paramtype order: str or ~openmeter.models.SortOrder + :keyword order_by: The order by field. Known values are: "customer.name", "issuedAt", "status", + "createdAt", "updatedAt", and "periodStart". Default value is None. + :paramtype order_by: str or ~openmeter.models.InvoiceOrderBy + :return: InvoicePaginatedResponse. The InvoicePaginatedResponse is compatible with + MutableMapping + :rtype: ~openmeter._generated.models.InvoicePaginatedResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.InvoicePaginatedResponse] = kwargs.pop("cls", None) + + _request = build_invoices_list_request( + statuses=statuses, + extended_statuses=extended_statuses, + issued_after=issued_after, + issued_before=issued_before, + period_start_after=period_start_after, + period_start_before=period_start_before, + created_after=created_after, + created_before=created_before, + expand=expand, + customers=customers, + include_deleted=include_deleted, + page=page, + page_size=page_size, + order=order, + order_by=order_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.InvoicePaginatedResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class InvoiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`invoice` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get_invoice( + self, + invoice_id: str, + *, + expand: Optional[List[Union[str, _models.InvoiceExpand]]] = None, + include_deleted_lines: Optional[bool] = None, + **kwargs: Any + ) -> _models.Invoice: + """Get an invoice. + + Get an invoice by ID. + + Gathering invoices will always show the current usage calculated on the fly. + + :param invoice_id: Required. + :type invoice_id: str + :keyword expand: Default value is None. + :paramtype expand: list[str or ~openmeter.models.InvoiceExpand] + :keyword include_deleted_lines: Default value is None. + :paramtype include_deleted_lines: bool + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_get_invoice_request( + invoice_id=invoice_id, + expand=expand, + include_deleted_lines=include_deleted_lines, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def delete_invoice(self, invoice_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete an invoice. + + Delete an invoice + + Only invoices that are in the draft (or earlier) status can be deleted. + + Invoices that are post finalization can only be voided. + + :param invoice_id: Required. + :type invoice_id: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_invoice_delete_invoice_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def update_invoice( + self, + invoice_id: str, + request: _models.InvoiceReplaceUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: ~openmeter._generated.models.InvoiceReplaceUpdate + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update_invoice( + self, invoice_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def update_invoice( + self, invoice_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def update_invoice( + self, invoice_id: str, request: Union[_models.InvoiceReplaceUpdate, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Invoice: + """Update an invoice. + + Update an invoice + + Only invoices in draft or earlier status can be updated. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Is one of the following types: InvoiceReplaceUpdate, JSON, IO[bytes] Required. + :type request: ~openmeter._generated.models.InvoiceReplaceUpdate or JSON or IO[bytes] + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_invoice_update_invoice_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def recalculate_tax_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Recalculate an invoice's tax amounts. + + Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + + Note: charges might apply, depending on the tax provider. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_recalculate_tax_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def approve_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Send the invoice to the customer. + + Approve an invoice and start executing the payment workflow. + + This call instantly sends the invoice to the customer using the configured billing profile app. + + This call is valid in two invoice statuses: + + * `draft`: the invoice will be sent to the customer, the invluce state becomes issued + * `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes + issued. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_approve_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def void_invoice_action( + self, + invoice_id: str, + request: _models.VoidInvoiceActionInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: ~openmeter._generated.models.VoidInvoiceActionInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def void_invoice_action( + self, invoice_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def void_invoice_action( + self, invoice_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def void_invoice_action( + self, invoice_id: str, request: Union[_models.VoidInvoiceActionInput, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Invoice: + """Void an invoice. + + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line + items. + + :param invoice_id: Required. + :type invoice_id: str + :param request: Is one of the following types: VoidInvoiceActionInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.VoidInvoiceActionInput or JSON or IO[bytes] + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_invoice_void_invoice_action_request( + invoice_id=invoice_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def advance_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Advance the invoice's state to the next status. + + Advance the invoice's state to the next status. + + The call doesn't "approve the invoice", it only advances the invoice to the next status if the + transition would be automatic. + + The action can be called when the invoice's statusDetails' actions field contain the "advance" + action. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_advance_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def retry_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Retry advancing the invoice after a failed attempt. + + Retry advancing the invoice after a failed attempt. + + The action can be called when the invoice's statusDetails' actions field contain the "retry" + action. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_retry_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def snapshot_quantities_action(self, invoice_id: str, **kwargs: Any) -> _models.Invoice: + """Snapshot quantities for usage based line items. + + Snapshot quantities for usage based line items. + + This call will snapshot the quantities for all usage based line items in the invoice. + + This call is only valid in ``draft.waiting_for_collection`` status, where the collection period + can be skipped using this action. + + :param invoice_id: Required. + :type invoice_id: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + _request = build_invoice_snapshot_quantities_action_request( + invoice_id=invoice_id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CustomerInvoiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`customer_invoice` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def simulate_invoice( + self, + customer_id: str, + request: _models.InvoiceSimulationInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: ~openmeter._generated.models.InvoiceSimulationInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def simulate_invoice( + self, customer_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def simulate_invoice( + self, customer_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def simulate_invoice( + self, customer_id: str, request: Union[_models.InvoiceSimulationInput, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Invoice: + """Simulate an invoice for a customer. + + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included + in the invoice. + + :param customer_id: Required. + :type customer_id: str + :param request: Is one of the following types: InvoiceSimulationInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.InvoiceSimulationInput or JSON or IO[bytes] + :return: Invoice. The Invoice is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Invoice + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Invoice] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_invoice_simulate_invoice_request( + customer_id=customer_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Invoice, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_pending_invoice_line( + self, + customer_id: str, + request: _models.InvoicePendingLineCreateInput, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: ~openmeter._generated.models.InvoicePendingLineCreateInput + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_pending_invoice_line( + self, customer_id: str, request: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create_pending_invoice_line( + self, customer_id: str, request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Required. + :type request: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create_pending_invoice_line( + self, customer_id: str, request: Union[_models.InvoicePendingLineCreateInput, JSON, IO[bytes]], **kwargs: Any + ) -> _models.InvoicePendingLineCreateResponse: + """Create pending line items. + + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + + * there is no invoice in gathering state + * the currency of the line item doesn't match the currency of any invoices in gathering state. + + :param customer_id: Required. + :type customer_id: str + :param request: Is one of the following types: InvoicePendingLineCreateInput, JSON, IO[bytes] + Required. + :type request: ~openmeter._generated.models.InvoicePendingLineCreateInput or JSON or IO[bytes] + :return: InvoicePendingLineCreateResponse. The InvoicePendingLineCreateResponse is compatible + with MutableMapping + :rtype: ~openmeter._generated.models.InvoicePendingLineCreateResponse + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.InvoicePendingLineCreateResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(request, (IOBase, bytes)): + _content = request + else: + _content = json.dumps(request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_customer_invoice_create_pending_invoice_line_request( + customer_id=customer_id, + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.InvoicePendingLineCreateResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ProgressOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`progress` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def get_progress(self, id: str, **kwargs: Any) -> _models.Progress: + """Get progress. + + Get progress. + + :param id: Required. + :type id: str + :return: Progress. The Progress is compatible with MutableMapping + :rtype: ~openmeter._generated.models.Progress + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Progress] = kwargs.pop("cls", None) + + _request = build_progress_get_progress_request( + id=id, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Progress, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class CurrenciesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`currencies` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def list_currencies(self, **kwargs: Any) -> List[_models.Currency]: + """List supported currencies. + + List all supported currencies. + + :return: list of Currency + :rtype: list[~openmeter._generated.models.Currency] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Currency]] = kwargs.pop("cls", None) + + _request = build_currencies_list_currencies_request( + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.Currency], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class PortalPortalTokensOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`portal_tokens` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def create( + self, token: _models.PortalToken, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Required. + :type token: ~openmeter._generated.models.PortalToken + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, token: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Required. + :type token: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def create(self, token: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Required. + :type token: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def create(self, token: Union[_models.PortalToken, JSON, IO[bytes]], **kwargs: Any) -> _models.PortalToken: + """Create consumer portal token. + + Create a consumer portal token. + + :param token: Is one of the following types: PortalToken, JSON, IO[bytes] Required. + :type token: ~openmeter._generated.models.PortalToken or JSON or IO[bytes] + :return: PortalToken. The PortalToken is compatible with MutableMapping + :rtype: ~openmeter._generated.models.PortalToken + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PortalToken] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(token, (IOBase, bytes)): + _content = token + else: + _content = json.dumps(token, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_portal_portal_tokens_create_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PortalToken, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + def list(self, *, limit: Optional[int] = None, **kwargs: Any) -> List[_models.PortalToken]: + """List consumer portal tokens. + + List tokens. + + :keyword limit: Default value is None. + :paramtype limit: int + :return: list of PortalToken + :rtype: list[~openmeter._generated.models.PortalToken] + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.PortalToken]] = kwargs.pop("cls", None) + + _request = build_portal_portal_tokens_list_request( + limit=limit, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(List[_models.PortalToken], response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def invalidate( + self, + *, + content_type: str = "application/json", + id: Optional[str] = None, + subject: Optional[str] = None, + **kwargs: Any + ) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword id: Invalidate a portal token by ID. Default value is None. + :paramtype id: str + :keyword subject: Invalidate all portal tokens for a subject. Default value is None. + :paramtype subject: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def invalidate(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :param body: Required. + :type body: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + @overload + def invalidate(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + + def invalidate( # pylint: disable=inconsistent-return-statements + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + id: Optional[str] = None, + subject: Optional[str] = None, + **kwargs: Any + ) -> None: + """Invalidate portal tokens. + + Invalidates consumer portal tokens by ID or subject. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword id: Invalidate a portal token by ID. Default value is None. + :paramtype id: str + :keyword subject: Invalidate all portal tokens for a subject. Default value is None. + :paramtype subject: str + :return: None + :rtype: None + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + if body is _Unset: + body = {"id": id, "subject": subject} + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_portal_portal_tokens_invalidate_request( + content_type=content_type, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class PortalPortalMetersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~openmeter.OpenMeterClient`'s + :attr:`portal_meters` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: OpenMeterClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + def query_json( + self, + meter_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> _models.MeterQueryResult: + """Query meter. + + Query meter for consumer portal. This endpoint is publicly exposable to consumers. + + :param meter_slug: Required. + :type meter_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: MeterQueryResult. The MeterQueryResult is compatible with MutableMapping + :rtype: ~openmeter._generated.models.MeterQueryResult + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.MeterQueryResult] = kwargs.pop("cls", None) + + _request = build_portal_portal_meters_query_json_request( + meter_slug=meter_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MeterQueryResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + def query_csv( + self, + meter_slug: str, + *, + client_id: Optional[str] = None, + from_parameter: Optional[datetime.datetime] = None, + to: Optional[datetime.datetime] = None, + window_size: Optional[Union[str, _models.WindowSize]] = None, + window_time_zone: Optional[str] = None, + filter_customer_id: Optional[List[str]] = None, + filter_group_by: Optional[dict[str, str]] = None, + advanced_meter_group_by_filters: Optional[dict[str, _models.FilterString]] = None, + group_by: Optional[List[str]] = None, + **kwargs: Any + ) -> str: + """Query meter. + + Query meter for consumer portal. This endpoint is publicly exposable to consumers. + + :param meter_slug: Required. + :type meter_slug: str + :keyword client_id: Client ID + Useful to track progress of a query. Default value is None. + :paramtype client_id: str + :keyword from_parameter: Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z. Default value is None. + :paramtype from_parameter: ~datetime.datetime + :keyword to: End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z. Default value is None. + :paramtype to: ~datetime.datetime + :keyword window_size: If not specified, a single usage aggregate will be returned for the + entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY. Known values are: "MINUTE", "HOUR", "DAY", and "MONTH". Default + value is None. + :paramtype window_size: str or ~openmeter.models.WindowSize + :keyword window_time_zone: The value is the name of the time zone as defined in the IANA Time + Zone Database (`http://www.iana.org/time-zones `_). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC. Default value is None. + :paramtype window_time_zone: str + :keyword filter_customer_id: Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2. Default value is None. + :paramtype filter_customer_id: list[str] + :keyword filter_group_by: Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ **Deprecated**: Use ``advancedMeterGroupByFilters`` instead. Default value is None. + :paramtype filter_group_by: dict[str, str] + :keyword advanced_meter_group_by_filters: Advanced meter group by filters. Default value is + None. + :paramtype advanced_meter_group_by_filters: dict[str, + ~openmeter._generated.models.FilterString] + :keyword group_by: If not specified a single aggregate will be returned for each subject and + time window. + ``subject`` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model. Default value is None. + :paramtype group_by: list[str] + :return: str + :rtype: str + :raises ~corehttp.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[str] = kwargs.pop("cls", None) + + _request = build_portal_portal_meters_query_csv_request( + meter_slug=meter_slug, + client_id=client_id, + from_parameter=from_parameter, + to=to, + window_size=window_size, + window_time_zone=window_time_zone, + filter_customer_id=filter_customer_id, + filter_group_by=filter_group_by, + advanced_meter_group_by_filters=advanced_meter_group_by_filters, + group_by=group_by, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client.pipeline.run(_request, stream=_stream, **kwargs) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = None + if response.status_code == 404: + error = _failsafe_deserialize(_models.NotFoundProblemResponse, response) + raise ResourceNotFoundError(response=response, model=error) + if response.status_code == 400: + error = _failsafe_deserialize(_models.BadRequestProblemResponse, response) + elif response.status_code == 401: + error = _failsafe_deserialize(_models.UnauthorizedProblemResponse, response) + raise ClientAuthenticationError(response=response, model=error) + if response.status_code == 403: + error = _failsafe_deserialize(_models.ForbiddenProblemResponse, response) + elif response.status_code == 500: + error = _failsafe_deserialize(_models.InternalServerErrorProblemResponse, response) + elif response.status_code == 503: + error = _failsafe_deserialize(_models.ServiceUnavailableProblemResponse, response) + elif response.status_code == 412: + error = _failsafe_deserialize(_models.PreconditionFailedProblemResponse, response) + else: + error = _failsafe_deserialize( + _models.UnexpectedProblemResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["content-type"] = self._deserialize("str", response.headers.get("content-type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(str, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore diff --git a/api/client/python/openmeter/_generated/operations/_patch.py b/api/client/python/openmeter/_generated/operations/_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..b208fb11fbc2e1955c43275aa4e1482dec7e5d6f --- /dev/null +++ b/api/client/python/openmeter/_generated/operations/_patch.py @@ -0,0 +1,17 @@ +# coding=utf-8 + +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/api/client/python/openmeter/_types.py b/api/client/python/openmeter/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..a279e3119db8117db1c237d1c1e4f830feda2277 --- /dev/null +++ b/api/client/python/openmeter/_types.py @@ -0,0 +1,89 @@ +# coding=utf-8 + +import datetime +from typing import TYPE_CHECKING, Union + +if TYPE_CHECKING: + from . import models as _models +App = Union["_models.StripeApp", "_models.SandboxApp", "_models.CustomInvoicingApp"] +CustomerAppData = Union[ + "_models.StripeCustomerAppData", "_models.SandboxCustomerAppData", "_models.CustomInvoicingCustomerAppData" +] +FeatureUnitCost = Union["_models.FeatureManualUnitCost", "_models.FeatureLLMUnitCost"] +RateCardEntitlement = Union[ + "_models.RateCardMeteredEntitlement", "_models.RateCardStaticEntitlement", "_models.RateCardBooleanEntitlement" +] +RateCardUsageBasedPrice = Union[ + "_models.FlatPriceWithPaymentTerm", + "_models.UnitPriceWithCommitments", + "_models.TieredPriceWithCommitments", + "_models.DynamicPriceWithCommitments", + "_models.PackagePriceWithCommitments", +] +RateCard = Union["_models.RateCardFlatFee", "_models.RateCardUsageBased"] +RecurringPeriodInterval = Union[str, str, "_models.RecurringPeriodIntervalEnum"] +Entitlement = Union["_models.EntitlementMetered", "_models.EntitlementStatic", "_models.EntitlementBoolean"] +SubscriptionErrorExtensions = "_models.SubscriptionBadRequestErrorResponseExtensions" +SubscriptionTiming = Union[str, "_models.SubscriptionTimingEnum", datetime.datetime] +SubscriptionEditOperation = Union[ + "_models.EditSubscriptionAddItem", + "_models.EditSubscriptionRemoveItem", + "_models.EditSubscriptionAddPhase", + "_models.EditSubscriptionRemovePhase", + "_models.EditSubscriptionStretchPhase", + "_models.EditSubscriptionUnscheduleEdit", +] +MeasureUsageFrom = Union[str, "_models.MeasureUsageFromPreset", datetime.datetime] +App = Union["_models.StripeApp", "_models.SandboxApp", "_models.CustomInvoicingApp"] +NotificationChannel = "_models.NotificationChannelWebhook" +NotificationRule = Union[ + "_models.NotificationRuleBalanceThreshold", + "_models.NotificationRuleEntitlementReset", + "_models.NotificationRuleInvoiceCreated", + "_models.NotificationRuleInvoiceUpdated", +] +InvoiceDocumentRef = "_models.CreditNoteOriginalInvoiceRef" +BillingProfileAppsOrReference = Union["_models.BillingProfileApps", "_models.BillingProfileAppReferences"] +BillingWorkflowCollectionAlignment = Union[ + "_models.BillingWorkflowCollectionAlignmentSubscription", "_models.BillingWorkflowCollectionAlignmentAnchored" +] +BillingDiscountReason = Union[ + "_models.DiscountReasonMaximumSpend", + "_models.DiscountReasonRatecardPercentage", + "_models.DiscountReasonRatecardUsage", +] +PaymentTerms = Union["_models.PaymentTermInstant", "_models.PaymentTermDueDate"] +NotificationEventPayload = Union[ + "_models.NotificationEventResetPayload", + "_models.NotificationEventBalanceThresholdPayload", + "_models.NotificationEventInvoiceCreatedPayload", + "_models.NotificationEventInvoiceUpdatedPayload", +] +EntitlementV2 = Union["_models.EntitlementMeteredV2", "_models.EntitlementStaticV2", "_models.EntitlementBooleanV2"] +VoidInvoiceLineAction = Union["_models.VoidInvoiceLineDiscardAction", "_models.VoidInvoiceLinePendingAction"] +AppReplaceUpdate = Union[ + "_models.StripeAppReplaceUpdate", "_models.SandboxAppReplaceUpdate", "_models.CustomInvoicingAppReplaceUpdate" +] +ULIDOrExternalKey = str +ListFeaturesResult = Union[list["_models.Feature"], "_models.FeaturePaginatedResponse"] +SubscriptionCreate = Union["_models.PlanSubscriptionCreate", "_models.CustomSubscriptionCreate"] +SubscriptionChange = Union["_models.PlanSubscriptionChange", "_models.CustomSubscriptionChange"] +ListEntitlementsResult = Union[list["_types.Entitlement"], "_models.EntitlementPaginatedResponse"] +EntitlementCreateInputs = Union[ + "_models.EntitlementMeteredCreateInputs", + "_models.EntitlementStaticCreateInputs", + "_models.EntitlementBooleanCreateInputs", +] +IngestEventsBody = Union["_models.Event", list["_models.Event"]] +NotificationChannelCreateRequest = "_models.NotificationChannelWebhookCreateRequest" +NotificationRuleCreateRequest = Union[ + "_models.NotificationRuleBalanceThresholdCreateRequest", + "_models.NotificationRuleEntitlementResetCreateRequest", + "_models.NotificationRuleInvoiceCreatedCreateRequest", + "_models.NotificationRuleInvoiceUpdatedCreateRequest", +] +EntitlementV2CreateInputs = Union[ + "_models.EntitlementMeteredV2CreateInputs", + "_models.EntitlementStaticCreateInputs", + "_models.EntitlementBooleanCreateInputs", +] diff --git a/api/client/python/openmeter/_version.py b/api/client/python/openmeter/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..4c354e371612255573d6f48d7125b88efa5a76a0 --- /dev/null +++ b/api/client/python/openmeter/_version.py @@ -0,0 +1,3 @@ +# coding=utf-8 + +VERSION = "0.0.0" diff --git a/api/client/python/openmeter/aio/__init__.py b/api/client/python/openmeter/aio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bba6a2393eec716136b048a33a80fae004bbcdc5 --- /dev/null +++ b/api/client/python/openmeter/aio/__init__.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .._generated.aio._patch import * # pylint: disable=unused-wildcard-import + +from ._client import Client # type: ignore + +try: + from .._generated.aio._patch import __all__ as _patch_all + from .._generated.aio._patch import * +except ImportError: + _patch_all = [] +from .._generated.aio._patch import patch_sdk as _patch_sdk + +__all__ = [ + "Client", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/api/client/python/openmeter/aio/_client.py b/api/client/python/openmeter/aio/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..67cbaf0f872774dab72e048c5f8b05d993c2351b --- /dev/null +++ b/api/client/python/openmeter/aio/_client.py @@ -0,0 +1,31 @@ +# coding=utf-8 + +from typing import Any, Optional +from typing_extensions import Self + +from corehttp.credentials import ServiceKeyCredential +from corehttp.runtime import policies + +from .._generated.aio._client import OpenMeterClient + + +class Client(OpenMeterClient): + def __init__( + self, + endpoint: str = "https://openmeter.cloud", + token: Optional[str] = None, + **kwargs: Any, + ) -> None: + if token and not kwargs.get("authentication_policy"): + credential = ServiceKeyCredential(token) + kwargs["authentication_policy"] = policies.ServiceKeyCredentialPolicy( + credential, "Authorization", prefix="Bearer" + ) + + super().__init__(endpoint=endpoint, **kwargs) + + def __enter__(self) -> Self: + return super().__enter__() + + def __exit__(self, *exc_details: Any) -> None: + return super().__exit__(*exc_details) diff --git a/api/client/python/openmeter/aio/operations/__init__.py b/api/client/python/openmeter/aio/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eedb7749190beb9160a060df887b86977c2af01e --- /dev/null +++ b/api/client/python/openmeter/aio/operations/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +""" +Re-exports all operations from the generated code for a cleaner API surface. +""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ..._generated.aio.operations._patch import * # pylint: disable=unused-wildcard-import + +# Re-export all operations from _generated.aio.operations +from ..._generated.aio.operations._operations import * # noqa: F401, F403 + +try: + from ..._generated.aio.operations._patch import __all__ as _patch_all + from ..._generated.aio.operations._patch import * # noqa: F401, F403 +except ImportError: + _patch_all = [] +from ..._generated.aio.operations._patch import patch_sdk as _patch_sdk + +# Import and re-export the __all__ list +from ..._generated.aio.operations import __all__ + +__all__ = __all__ +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/api/client/python/openmeter/models/__init__.py b/api/client/python/openmeter/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7805726d8d332845488610e397c9d54cf552bd28 --- /dev/null +++ b/api/client/python/openmeter/models/__init__.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +""" +Re-exports all models from the generated code for a cleaner API surface. +""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .._generated.models._patch import * # pylint: disable=unused-wildcard-import + +# Re-export all models from _generated.models +from .._generated.models._models import * # noqa: F401, F403 +from .._generated.models._enums import * # noqa: F401, F403 + +try: + from .._generated.models._patch import __all__ as _patch_all + from .._generated.models._patch import * # noqa: F401, F403 +except ImportError: + _patch_all = [] +from .._generated.models._patch import patch_sdk as _patch_sdk + +# Import and re-export the __all__ list +from .._generated.models import __all__ + +__all__ = __all__ +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/api/client/python/openmeter/operations/__init__.py b/api/client/python/openmeter/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3afebf00546427b09b6643b2dfb109995b8393 --- /dev/null +++ b/api/client/python/openmeter/operations/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# pylint: disable=wrong-import-position + +""" +Re-exports all operations from the generated code for a cleaner API surface. +""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .._generated.operations._patch import * # pylint: disable=unused-wildcard-import + +# Re-export all operations from _generated.operations +from .._generated.operations._operations import * # noqa: F401, F403 + +try: + from .._generated.operations._patch import __all__ as _patch_all + from .._generated.operations._patch import * # noqa: F401, F403 +except ImportError: + _patch_all = [] +from .._generated.operations._patch import patch_sdk as _patch_sdk + +# Import and re-export the __all__ list +from .._generated.operations import __all__ + +__all__ = __all__ +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/api/client/python/openmeter/py.typed b/api/client/python/openmeter/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e5aff4f83af864a6415aebc309885d1e32c3c63a --- /dev/null +++ b/api/client/python/openmeter/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/api/client/python/poetry.lock b/api/client/python/poetry.lock new file mode 100644 index 0000000000000000000000000000000000000000..6cb86d71b0cd215e6ce01c9f87e324f0499b6dcc --- /dev/null +++ b/api/client/python/poetry.lock @@ -0,0 +1,1316 @@ +# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand. + +[[package]] +name = "aiohappyeyeballs" +version = "2.6.1" +description = "Happy Eyeballs for asyncio" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "aiohappyeyeballs-2.6.1-py3-none-any.whl", hash = "sha256:f349ba8f4b75cb25c99c5c2d84e997e485204d2902a9597802b0371f09331fb8"}, + {file = "aiohappyeyeballs-2.6.1.tar.gz", hash = "sha256:c3f9d0113123803ccadfdf3f0faa505bc78e6a72d1cc4806cbd719826e943558"}, +] + +[[package]] +name = "aiohttp" +version = "3.13.4" +description = "Async http client/server framework (asyncio)" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "aiohttp-3.13.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:6290fe12fe8cefa6ea3c1c5b969d32c010dfe191d4392ff9b599a3f473cbe722"}, + {file = "aiohttp-3.13.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7520d92c0e8fbbe63f36f20a5762db349ff574ad38ad7bc7732558a650439845"}, + {file = "aiohttp-3.13.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d2710ae1e1b81d0f187883b6e9d66cecf8794b50e91aa1e73fc78bfb5503b5d9"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:717d17347567ded1e273aa09918650dfd6fd06f461549204570c7973537d4123"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:383880f7b8de5ac208fa829c7038d08e66377283b2de9e791b71e06e803153c2"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1867087e2c1963db1216aedf001efe3b129835ed2b05d97d058176a6d08b5726"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6234bf416a38d687c3ab7f79934d7fb2a42117a5b9813aca07de0a5398489023"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cdd3393130bf6588962441ffd5bde1d3ea2d63a64afa7119b3f3ba349cebbe7"}, + {file = "aiohttp-3.13.4-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0d0dbc6c76befa76865373d6aa303e480bb8c3486e7763530f7f6e527b471118"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:10fb7b53262cf4144a083c9db0d2b4d22823d6708270a9970c4627b248c6064c"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:eb10ce8c03850e77f4d9518961c227be569e12f71525a7e90d17bca04299921d"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:7c65738ac5ae32b8feef699a4ed0dc91a0c8618b347781b7461458bbcaaac7eb"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:6b335919ffbaf98df8ff3c74f7a6decb8775882632952fd1810a017e38f15aee"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:ec75fc18cb9f4aca51c2cbace20cf6716e36850f44189644d2d69a875d5e0532"}, + {file = "aiohttp-3.13.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:463fa18a95c5a635d2b8c09babe240f9d7dbf2a2010a6c0b35d8c4dff2a0e819"}, + {file = "aiohttp-3.13.4-cp310-cp310-win32.whl", hash = "sha256:13168f5645d9045522c6cef818f54295376257ed8d02513a37c2ef3046fc7a97"}, + {file = "aiohttp-3.13.4-cp310-cp310-win_amd64.whl", hash = "sha256:a7058af1f53209fdf07745579ced525d38d481650a989b7aa4a3b484b901cdab"}, + {file = "aiohttp-3.13.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8ea0c64d1bcbf201b285c2246c51a0c035ba3bbd306640007bc5844a3b4658c1"}, + {file = "aiohttp-3.13.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6f742e1fa45c0ed522b00ede565e18f97e4cf8d1883a712ac42d0339dfb0cce7"}, + {file = "aiohttp-3.13.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6dcfb50ee25b3b7a1222a9123be1f9f89e56e67636b561441f0b304e25aaef8f"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3262386c4ff370849863ea93b9ea60fd59c6cf56bf8f93beac625cf4d677c04d"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:473bb5aa4218dd254e9ae4834f20e31f5a0083064ac0136a01a62ddbae2eaa42"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e56423766399b4c77b965f6aaab6c9546617b8994a956821cc507d00b91d978c"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8af249343fafd5ad90366a16d230fc265cf1149f26075dc9fe93cfd7c7173942"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bc0a5cf4f10ef5a2c94fdde488734b582a3a7a000b131263e27c9295bd682d9"}, + {file = "aiohttp-3.13.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5c7ff1028e3c9fc5123a865ce17df1cb6424d180c503b8517afbe89aa566e6be"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ba5cf98b5dcb9bddd857da6713a503fa6d341043258ca823f0f5ab7ab4a94ee8"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:d85965d3ba21ee4999e83e992fecb86c4614d6920e40705501c0a1f80a583c12"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:49f0b18a9b05d79f6f37ddd567695943fcefb834ef480f17a4211987302b2dc7"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7f78cb080c86fbf765920e5f1ef35af3f24ec4314d6675d0a21eaf41f6f2679c"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:67a3ec705534a614b68bbf1c70efa777a21c3da3895d1c44510a41f5a7ae0453"}, + {file = "aiohttp-3.13.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d6630ec917e85c5356b2295744c8a97d40f007f96a1c76bf1928dc2e27465393"}, + {file = "aiohttp-3.13.4-cp311-cp311-win32.whl", hash = "sha256:54049021bc626f53a5394c29e8c444f726ee5a14b6e89e0ad118315b1f90f5e3"}, + {file = "aiohttp-3.13.4-cp311-cp311-win_amd64.whl", hash = "sha256:c033f2bc964156030772d31cbf7e5defea181238ce1f87b9455b786de7d30145"}, + {file = "aiohttp-3.13.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ee62d4471ce86b108b19c3364db4b91180d13fe3510144872d6bad5401957360"}, + {file = "aiohttp-3.13.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c0fd8f41b54b58636402eb493afd512c23580456f022c1ba2db0f810c959ed0d"}, + {file = "aiohttp-3.13.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4baa48ce49efd82d6b1a0be12d6a36b35e5594d1dd42f8bfba96ea9f8678b88c"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d738ebab9f71ee652d9dbd0211057690022201b11197f9a7324fd4dba128aa97"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0ce692c3468fa831af7dceed52edf51ac348cebfc8d3feb935927b63bd3e8576"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8e08abcfe752a454d2cb89ff0c08f2d1ecd057ae3e8cc6d84638de853530ebab"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5977f701b3fff36367a11087f30ea73c212e686d41cd363c50c022d48b011d8d"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54203e10405c06f8b6020bd1e076ae0fe6c194adcee12a5a78af3ffa3c57025e"}, + {file = "aiohttp-3.13.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:358a6af0145bc4dda037f13167bef3cce54b132087acc4c295c739d05d16b1c3"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:898ea1850656d7d61832ef06aa9846ab3ddb1621b74f46de78fbc5e1a586ba83"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:7bc30cceb710cf6a44e9617e43eebb6e3e43ad855a34da7b4b6a73537d8a6763"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4a31c0c587a8a038f19a4c7e60654a6c899c9de9174593a13e7cc6e15ff271f9"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:2062f675f3fe6e06d6113eb74a157fb9df58953ffed0cdb4182554b116545758"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d1ba8afb847ff80626d5e408c1fdc99f942acc877d0702fe137015903a220a9"}, + {file = "aiohttp-3.13.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b08149419994cdd4d5eecf7fd4bc5986b5a9380285bcd01ab4c0d6bfca47b79d"}, + {file = "aiohttp-3.13.4-cp312-cp312-win32.whl", hash = "sha256:fc432f6a2c4f720180959bc19aa37259651c1a4ed8af8afc84dd41c60f15f791"}, + {file = "aiohttp-3.13.4-cp312-cp312-win_amd64.whl", hash = "sha256:6148c9ae97a3e8bff9a1fc9c757fa164116f86c100468339730e717590a3fb77"}, + {file = "aiohttp-3.13.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:63dd5e5b1e43b8fb1e91b79b7ceba1feba588b317d1edff385084fcc7a0a4538"}, + {file = "aiohttp-3.13.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:746ac3cc00b5baea424dacddea3ec2c2702f9590de27d837aa67004db1eebc6e"}, + {file = "aiohttp-3.13.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bda8f16ea99d6a6705e5946732e48487a448be874e54a4f73d514660ff7c05d3"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4b061e7b5f840391e3f64d0ddf672973e45c4cfff7a0feea425ea24e51530fc2"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b252e8d5cd66184b570d0d010de742736e8a4fab22c58299772b0c5a466d4b21"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:20af8aad61d1803ff11152a26146d8d81c266aa8c5aa9b4504432abb965c36a0"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:13a5cc924b59859ad2adb1478e31f410a7ed46e92a2a619d6d1dd1a63c1a855e"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:534913dfb0a644d537aebb4123e7d466d94e3be5549205e6a31f72368980a81a"}, + {file = "aiohttp-3.13.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:320e40192a2dcc1cf4b5576936e9652981ab596bf81eb309535db7e2f5b5672f"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9e587fcfce2bcf06526a43cb705bdee21ac089096f2e271d75de9c339db3100c"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:9eb9c2eea7278206b5c6c1441fdd9dc420c278ead3f3b2cc87f9b693698cc500"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:29be00c51972b04bf9d5c8f2d7f7314f48f96070ca40a873a53056e652e805f7"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:90c06228a6c3a7c9f776fe4fc0b7ff647fffd3bed93779a6913c804ae00c1073"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:a533ec132f05fd9a1d959e7f34184cd7d5e8511584848dab85faefbaac573069"}, + {file = "aiohttp-3.13.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1c946f10f413836f82ea4cfb90200d2a59578c549f00857e03111cf45ad01ca5"}, + {file = "aiohttp-3.13.4-cp313-cp313-win32.whl", hash = "sha256:48708e2706106da6967eff5908c78ca3943f005ed6bcb75da2a7e4da94ef8c70"}, + {file = "aiohttp-3.13.4-cp313-cp313-win_amd64.whl", hash = "sha256:74a2eb058da44fa3a877a49e2095b591d4913308bb424c418b77beb160c55ce3"}, + {file = "aiohttp-3.13.4-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:e0a2c961fc92abeff61d6444f2ce6ad35bb982db9fc8ff8a47455beacf454a57"}, + {file = "aiohttp-3.13.4-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:153274535985a0ff2bff1fb6c104ed547cec898a09213d21b0f791a44b14d933"}, + {file = "aiohttp-3.13.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:351f3171e2458da3d731ce83f9e6b9619e325c45cbd534c7759750cabf453ad7"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f989ac8bc5595ff761a5ccd32bdb0768a117f36dd1504b1c2c074ed5d3f4df9c"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d36fc1709110ec1e87a229b201dd3ddc32aa01e98e7868083a794609b081c349"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:42adaeea83cbdf069ab94f5103ce0787c21fb1a0153270da76b59d5578302329"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:92deb95469928cc41fd4b42a95d8012fa6df93f6b1c0a83af0ffbc4a5e218cde"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0c0c7c07c4257ef3a1df355f840bc62d133bcdef5c1c5ba75add3c08553e2eed"}, + {file = "aiohttp-3.13.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f062c45de8a1098cb137a1898819796a2491aec4e637a06b03f149315dff4d8f"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:76093107c531517001114f0ebdb4f46858ce818590363e3e99a4a2280334454a"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:6f6ec32162d293b82f8b63a16edc80769662fbd5ae6fbd4936d3206a2c2cc63b"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:5903e2db3d202a00ad9f0ec35a122c005e85d90c9836ab4cda628f01edf425e2"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:2d5bea57be7aca98dbbac8da046d99b5557c5cf4e28538c4c786313078aca09e"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:bcf0c9902085976edc0232b75006ef38f89686901249ce14226b6877f88464fb"}, + {file = "aiohttp-3.13.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c3295f98bfeed2e867cab588f2a146a9db37a85e3ae9062abf46ba062bd29165"}, + {file = "aiohttp-3.13.4-cp314-cp314-win32.whl", hash = "sha256:a598a5c5767e1369d8f5b08695cab1d8160040f796c4416af76fd773d229b3c9"}, + {file = "aiohttp-3.13.4-cp314-cp314-win_amd64.whl", hash = "sha256:c555db4bc7a264bead5a7d63d92d41a1122fcd39cc62a4db815f45ad46f9c2c8"}, + {file = "aiohttp-3.13.4-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:45abbbf09a129825d13c18c7d3182fecd46d9da3cfc383756145394013604ac1"}, + {file = "aiohttp-3.13.4-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:74c80b2bc2c2adb7b3d1941b2b60701ee2af8296fc8aad8b8bc48bc25767266c"}, + {file = "aiohttp-3.13.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c97989ae40a9746650fa196894f317dafc12227c808c774929dda0ff873a5954"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dae86be9811493f9990ef44fff1685f5c1a3192e9061a71a109d527944eed551"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1db491abe852ca2fa6cc48a3341985b0174b3741838e1341b82ac82c8bd9e871"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0e5d701c0aad02a7dce72eef6b93226cf3734330f1a31d69ebbf69f33b86666e"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8ac32a189081ae0a10ba18993f10f338ec94341f0d5df8fff348043962f3c6f8"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:98e968cdaba43e45c73c3f306fca418c8009a957733bac85937c9f9cf3f4de27"}, + {file = "aiohttp-3.13.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ca114790c9144c335d538852612d3e43ea0f075288f4849cf4b05d6cd2238ce7"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ea2e071661ba9cfe11eabbc81ac5376eaeb3061f6e72ec4cc86d7cdd1ffbdbbb"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:34e89912b6c20e0fd80e07fa401fd218a410aa1ce9f1c2f1dad6db1bd0ce0927"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:0e217cf9f6a42908c52b46e42c568bd57adc39c9286ced31aaace614b6087965"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:0c296f1221e21ba979f5ac1964c3b78cfde15c5c5f855ffd2caab337e9cd9182"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:d99a9d168ebaffb74f36d011750e490085ac418f4db926cce3989c8fe6cb6b1b"}, + {file = "aiohttp-3.13.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cb19177205d93b881f3f89e6081593676043a6828f59c78c17a0fd6c1fbed2ba"}, + {file = "aiohttp-3.13.4-cp314-cp314t-win32.whl", hash = "sha256:c606aa5656dab6552e52ca368e43869c916338346bfaf6304e15c58fb113ea30"}, + {file = "aiohttp-3.13.4-cp314-cp314t-win_amd64.whl", hash = "sha256:014dcc10ec8ab8db681f0d68e939d1e9286a5aa2b993cbbdb0db130853e02144"}, + {file = "aiohttp-3.13.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:b3f00bb9403728b08eb3951e982ca0a409c7a871d709684623daeab79465b181"}, + {file = "aiohttp-3.13.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:cb15595eb52870f84248d7cc97013a76f52ab02ff74d394be093b1d9b8b82bc0"}, + {file = "aiohttp-3.13.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:907ad36b6a65cff7d88d7aca0f77c650546ba850a4f92c92ecb83590d4613249"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5539ec0d6a3a5c6799b661b7e79166ad1b7ae71ccb59a92fcb6b4ef89295bc94"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3b4e07d8803a70dd886b5f38588e5b49f894995ca8e132b06c31a2583ae2ef6e"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ce7320a945aac4bf0bb8901600e4f9409eb602f25ce3ef4d275b48f6d704a862"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:26ed03f7d3d6453634729e2c7600d7255d65e879559c5a48fe1bb78355cde74b"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c3f733916e85506b8000dddc071c6b82f8c68f56c99adb328d6550017db062d"}, + {file = "aiohttp-3.13.4-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b3d525648fe7c8b4977e460c18098f9f81d7991d72edfdc2f13cf96068f279bc"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:4e2e68085730a03704beb2cff035fa8648f62c9f93758d7e6d70add7f7bb5b3b"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:797613182ffaaca0b9ad5f3b3d3ce5d21242c768f75e66c750b8292bd97c9de3"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:2d15e7e4f1099d9e4d863eaf77a8eee5dcb002b7d7188061b0fbee37f845899e"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:19f60011ad60e40a01d242238bb335399e3a4d8df958c63cbb835add8d5c3b5a"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:c344c47e85678e410b064fc2ace14db86bb69db7ed5520c234bf13aed603ec30"}, + {file = "aiohttp-3.13.4-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:d904084985ca66459e93797e5e05985c048a9c0633655331144c089943e53d12"}, + {file = "aiohttp-3.13.4-cp39-cp39-win32.whl", hash = "sha256:1746338dc2a33cf706cd7446575d13d451f28f9860bebc908c7632b22e71ae3f"}, + {file = "aiohttp-3.13.4-cp39-cp39-win_amd64.whl", hash = "sha256:a5444dce2e6fba0a1dc2d58d026e674f25f21de178c6f844342629bcef019f2f"}, + {file = "aiohttp-3.13.4.tar.gz", hash = "sha256:d97a6d09c66087890c2ab5d49069e1e570583f7ac0314ecf98294c1b6aaebd38"}, +] + +[package.dependencies] +aiohappyeyeballs = ">=2.5.0" +aiosignal = ">=1.4.0" +async-timeout = {version = ">=4.0,<6.0", markers = "python_version < \"3.11\""} +attrs = ">=17.3.0" +frozenlist = ">=1.1.1" +multidict = ">=4.5,<7.0" +propcache = ">=0.2.0" +yarl = ">=1.17.0,<2.0" + +[package.extras] +speedups = ["Brotli (>=1.2) ; platform_python_implementation == \"CPython\"", "aiodns (>=3.3.0)", "backports.zstd ; platform_python_implementation == \"CPython\" and python_version < \"3.14\"", "brotlicffi (>=1.2) ; platform_python_implementation != \"CPython\""] + +[[package]] +name = "aiosignal" +version = "1.4.0" +description = "aiosignal: a list of registered asynchronous callbacks" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e"}, + {file = "aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7"}, +] + +[package.dependencies] +frozenlist = ">=1.1.0" +typing-extensions = {version = ">=4.2", markers = "python_version < \"3.13\""} + +[[package]] +name = "async-timeout" +version = "5.0.1" +description = "Timeout context manager for asyncio programs" +optional = false +python-versions = ">=3.8" +groups = ["main"] +markers = "python_version < \"3.11\"" +files = [ + {file = "async_timeout-5.0.1-py3-none-any.whl", hash = "sha256:39e3809566ff85354557ec2398b55e096c8364bacac9405a7a1fa429e77fe76c"}, + {file = "async_timeout-5.0.1.tar.gz", hash = "sha256:d9321a7a3d5a6a5e187e824d2fa0793ce379a202935782d555d6e9d2735677d3"}, +] + +[[package]] +name = "attrs" +version = "26.1.0" +description = "Classes Without Boilerplate" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309"}, + {file = "attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"}, +] + +[[package]] +name = "black" +version = "25.11.0" +description = "The uncompromising code formatter." +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "black-25.11.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ec311e22458eec32a807f029b2646f661e6859c3f61bc6d9ffb67958779f392e"}, + {file = "black-25.11.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1032639c90208c15711334d681de2e24821af0575573db2810b0763bcd62e0f0"}, + {file = "black-25.11.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0c0f7c461df55cf32929b002335883946a4893d759f2df343389c4396f3b6b37"}, + {file = "black-25.11.0-cp310-cp310-win_amd64.whl", hash = "sha256:f9786c24d8e9bd5f20dc7a7f0cdd742644656987f6ea6947629306f937726c03"}, + {file = "black-25.11.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:895571922a35434a9d8ca67ef926da6bc9ad464522a5fe0db99b394ef1c0675a"}, + {file = "black-25.11.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cb4f4b65d717062191bdec8e4a442539a8ea065e6af1c4f4d36f0cdb5f71e170"}, + {file = "black-25.11.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d81a44cbc7e4f73a9d6ae449ec2317ad81512d1e7dce7d57f6333fd6259737bc"}, + {file = "black-25.11.0-cp311-cp311-win_amd64.whl", hash = "sha256:7eebd4744dfe92ef1ee349dc532defbf012a88b087bb7ddd688ff59a447b080e"}, + {file = "black-25.11.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:80e7486ad3535636657aa180ad32a7d67d7c273a80e12f1b4bfa0823d54e8fac"}, + {file = "black-25.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6cced12b747c4c76bc09b4db057c319d8545307266f41aaee665540bc0e04e96"}, + {file = "black-25.11.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cb2d54a39e0ef021d6c5eef442e10fd71fcb491be6413d083a320ee768329dd"}, + {file = "black-25.11.0-cp312-cp312-win_amd64.whl", hash = "sha256:ae263af2f496940438e5be1a0c1020e13b09154f3af4df0835ea7f9fe7bfa409"}, + {file = "black-25.11.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0a1d40348b6621cc20d3d7530a5b8d67e9714906dfd7346338249ad9c6cedf2b"}, + {file = "black-25.11.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:51c65d7d60bb25429ea2bf0731c32b2a2442eb4bd3b2afcb47830f0b13e58bfd"}, + {file = "black-25.11.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:936c4dd07669269f40b497440159a221ee435e3fddcf668e0c05244a9be71993"}, + {file = "black-25.11.0-cp313-cp313-win_amd64.whl", hash = "sha256:f42c0ea7f59994490f4dccd64e6b2dd49ac57c7c84f38b8faab50f8759db245c"}, + {file = "black-25.11.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:35690a383f22dd3e468c85dc4b915217f87667ad9cce781d7b42678ce63c4170"}, + {file = "black-25.11.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:dae49ef7369c6caa1a1833fd5efb7c3024bb7e4499bf64833f65ad27791b1545"}, + {file = "black-25.11.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5bd4a22a0b37401c8e492e994bce79e614f91b14d9ea911f44f36e262195fdda"}, + {file = "black-25.11.0-cp314-cp314-win_amd64.whl", hash = "sha256:aa211411e94fdf86519996b7f5f05e71ba34835d8f0c0f03c00a26271da02664"}, + {file = "black-25.11.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a3bb5ce32daa9ff0605d73b6f19da0b0e6c1f8f2d75594db539fdfed722f2b06"}, + {file = "black-25.11.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:9815ccee1e55717fe9a4b924cae1646ef7f54e0f990da39a34fc7b264fcf80a2"}, + {file = "black-25.11.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:92285c37b93a1698dcbc34581867b480f1ba3a7b92acf1fe0467b04d7a4da0dc"}, + {file = "black-25.11.0-cp39-cp39-win_amd64.whl", hash = "sha256:43945853a31099c7c0ff8dface53b4de56c41294fa6783c0441a8b1d9bf668bc"}, + {file = "black-25.11.0-py3-none-any.whl", hash = "sha256:e3f562da087791e96cefcd9dda058380a442ab322a02e222add53736451f604b"}, + {file = "black-25.11.0.tar.gz", hash = "sha256:9a323ac32f5dc75ce7470501b887250be5005a01602e931a15e45593f70f6e08"}, +] + +[package.dependencies] +click = ">=8.0.0" +mypy-extensions = ">=0.4.3" +packaging = ">=22.0" +pathspec = ">=0.9.0" +platformdirs = ">=2" +pytokens = ">=0.3.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""} + +[package.extras] +colorama = ["colorama (>=0.4.3)"] +d = ["aiohttp (>=3.10)"] +jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] +uvloop = ["uvloop (>=0.15.2)"] + +[[package]] +name = "certifi" +version = "2026.2.25" +description = "Python package for providing Mozilla's CA Bundle." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "certifi-2026.2.25-py3-none-any.whl", hash = "sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa"}, + {file = "certifi-2026.2.25.tar.gz", hash = "sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7"}, +] + +[[package]] +name = "charset-normalizer" +version = "3.4.6" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "charset_normalizer-3.4.6-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:2e1d8ca8611099001949d1cdfaefc510cf0f212484fe7c565f735b68c78c3c95"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e25369dc110d58ddf29b949377a93e0716d72a24f62bad72b2b39f155949c1fd"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:259695e2ccc253feb2a016303543d691825e920917e31f894ca1a687982b1de4"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dda86aba335c902b6149a02a55b38e96287157e609200811837678214ba2b1db"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51fb3c322c81d20567019778cb5a4a6f2dc1c200b886bc0d636238e364848c89"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-manylinux_2_31_armv7l.whl", hash = "sha256:4482481cb0572180b6fd976a4d5c72a30263e98564da68b86ec91f0fe35e8565"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:39f5068d35621da2881271e5c3205125cc456f54e9030d3f723288c873a71bf9"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:8bea55c4eef25b0b19a0337dc4e3f9a15b00d569c77211fa8cde38684f234fb7"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:f0cdaecd4c953bfae0b6bb64910aaaca5a424ad9c72d85cb88417bb9814f7550"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:150b8ce8e830eb7ccb029ec9ca36022f756986aaaa7956aad6d9ec90089338c0"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:e68c14b04827dd76dcbd1aeea9e604e3e4b78322d8faf2f8132c7138efa340a8"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:3778fd7d7cd04ae8f54651f4a7a0bd6e39a0cf20f801720a4c21d80e9b7ad6b0"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:dad6e0f2e481fffdcf776d10ebee25e0ef89f16d691f1e5dee4b586375fdc64b"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-win32.whl", hash = "sha256:74a2e659c7ecbc73562e2a15e05039f1e22c75b7c7618b4b574a3ea9118d1557"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-win_amd64.whl", hash = "sha256:aa9cccf4a44b9b62d8ba8b4dd06c649ba683e4bf04eea606d2e94cfc2d6ff4d6"}, + {file = "charset_normalizer-3.4.6-cp310-cp310-win_arm64.whl", hash = "sha256:e985a16ff513596f217cee86c21371b8cd011c0f6f056d0920aa2d926c544058"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:82060f995ab5003a2d6e0f4ad29065b7672b6593c8c63559beefe5b443242c3e"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:60c74963d8350241a79cb8feea80e54d518f72c26db618862a8f53e5023deaf9"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6e4333fb15c83f7d1482a76d45a0818897b3d33f00efd215528ff7c51b8e35d"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bc72863f4d9aba2e8fd9085e63548a324ba706d2ea2c83b260da08a59b9482de"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9cc4fc6c196d6a8b76629a70ddfcd4635a6898756e2d9cac5565cf0654605d73"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-manylinux_2_31_armv7l.whl", hash = "sha256:0c173ce3a681f309f31b87125fecec7a5d1347261ea11ebbb856fa6006b23c8c"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c907cdc8109f6c619e6254212e794d6548373cc40e1ec75e6e3823d9135d29cc"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:404a1e552cf5b675a87f0651f8b79f5f1e6fd100ee88dc612f89aa16abd4486f"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:e3c701e954abf6fc03a49f7c579cc80c2c6cc52525340ca3186c41d3f33482ef"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:7a6967aaf043bceabab5412ed6bd6bd26603dae84d5cb75bf8d9a74a4959d398"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:5feb91325bbceade6afab43eb3b508c63ee53579fe896c77137ded51c6b6958e"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:f820f24b09e3e779fe84c3c456cb4108a7aa639b0d1f02c28046e11bfcd088ed"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b35b200d6a71b9839a46b9b7fff66b6638bb52fc9658aa58796b0326595d3021"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-win32.whl", hash = "sha256:9ca4c0b502ab399ef89248a2c84c54954f77a070f28e546a85e91da627d1301e"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:a9e68c9d88823b274cf1e72f28cb5dc89c990edf430b0bfd3e2fb0785bfeabf4"}, + {file = "charset_normalizer-3.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:97d0235baafca5f2b09cf332cc275f021e694e8362c6bb9c96fc9a0eb74fc316"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2ef7fedc7a6ecbe99969cd09632516738a97eeb8bd7258bf8a0f23114c057dab"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a4ea868bc28109052790eb2b52a9ab33f3aa7adc02f96673526ff47419490e21"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:836ab36280f21fc1a03c99cd05c6b7af70d2697e374c7af0b61ed271401a72a2"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f1ce721c8a7dfec21fcbdfe04e8f68174183cf4e8188e0645e92aa23985c57ff"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e28d62a8fc7a1fa411c43bd65e346f3bce9716dc51b897fbe930c5987b402d5"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:530d548084c4a9f7a16ed4a294d459b4f229db50df689bfe92027452452943a0"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:30f445ae60aad5e1f8bdbb3108e39f6fbc09f4ea16c815c66578878325f8f15a"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ac2393c73378fea4e52aa56285a3d64be50f1a12395afef9cce47772f60334c2"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:90ca27cd8da8118b18a52d5f547859cc1f8354a00cd1e8e5120df3e30d6279e5"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8e5a94886bedca0f9b78fecd6afb6629142fd2605aa70a125d49f4edc6037ee6"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:695f5c2823691a25f17bc5d5ffe79fa90972cc34b002ac6c843bb8a1720e950d"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:231d4da14bcd9301310faf492051bee27df11f2bc7549bc0bb41fef11b82daa2"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a056d1ad2633548ca18ffa2f85c202cfb48b68615129143915b8dc72a806a923"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-win32.whl", hash = "sha256:c2274ca724536f173122f36c98ce188fd24ce3dad886ec2b7af859518ce008a4"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:c8ae56368f8cc97c7e40a7ee18e1cedaf8e780cd8bc5ed5ac8b81f238614facb"}, + {file = "charset_normalizer-3.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:899d28f422116b08be5118ef350c292b36fc15ec2daeb9ea987c89281c7bb5c4"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:11afb56037cbc4b1555a34dd69151e8e069bee82e613a73bef6e714ce733585f"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:423fb7e748a08f854a08a222b983f4df1912b1daedce51a72bd24fe8f26a1843"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d73beaac5e90173ac3deb9928a74763a6d230f494e4bfb422c217a0ad8e629bf"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d60377dce4511655582e300dc1e5a5f24ba0cb229005a1d5c8d0cb72bb758ab8"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:530e8cebeea0d76bdcf93357aa5e41336f48c3dc709ac52da2bb167c5b8271d9"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:a26611d9987b230566f24a0a125f17fe0de6a6aff9f25c9f564aaa2721a5fb88"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:34315ff4fc374b285ad7f4a0bf7dcbfe769e1b104230d40f49f700d4ab6bbd84"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5f8ddd609f9e1af8c7bd6e2aca279c931aefecd148a14402d4e368f3171769fd"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:80d0a5615143c0b3225e5e3ef22c8d5d51f3f72ce0ea6fb84c943546c7b25b6c"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:92734d4d8d187a354a556626c221cd1a892a4e0802ccb2af432a1d85ec012194"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:613f19aa6e082cf96e17e3ffd89383343d0d589abda756b7764cf78361fd41dc"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2b1a63e8224e401cafe7739f77efd3f9e7f5f2026bda4aead8e59afab537784f"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6cceb5473417d28edd20c6c984ab6fee6c6267d38d906823ebfe20b03d607dc2"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-win32.whl", hash = "sha256:d7de2637729c67d67cf87614b566626057e95c303bc0a55ffe391f5205e7003d"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-win_amd64.whl", hash = "sha256:572d7c822caf521f0525ba1bce1a622a0b85cf47ffbdae6c9c19e3b5ac3c4389"}, + {file = "charset_normalizer-3.4.6-cp313-cp313-win_arm64.whl", hash = "sha256:a4474d924a47185a06411e0064b803c68be044be2d60e50e8bddcc2649957c1f"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:9cc6e6d9e571d2f863fa77700701dae73ed5f78881efc8b3f9a4398772ff53e8"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ef5960d965e67165d75b7c7ffc60a83ec5abfc5c11b764ec13ea54fbef8b4421"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b3694e3f87f8ac7ce279d4355645b3c878d24d1424581b46282f24b92f5a4ae2"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5d11595abf8dd942a77883a39d81433739b287b6aa71620f15164f8096221b30"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7bda6eebafd42133efdca535b04ccb338ab29467b3f7bf79569883676fc628db"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:bbc8c8650c6e51041ad1be191742b8b421d05bbd3410f43fa2a00c8db87678e8"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:22c6f0c2fbc31e76c3b8a86fba1a56eda6166e238c29cdd3d14befdb4a4e4815"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7edbed096e4a4798710ed6bc75dcaa2a21b68b6c356553ac4823c3658d53743a"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:7f9019c9cb613f084481bd6a100b12e1547cf2efe362d873c2e31e4035a6fa43"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:58c948d0d086229efc484fe2f30c2d382c86720f55cd9bc33591774348ad44e0"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:419a9d91bd238052642a51938af8ac05da5b3343becde08d5cdeab9046df9ee1"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:5273b9f0b5835ff0350c0828faea623c68bfa65b792720c453e22b25cc72930f"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0e901eb1049fdb80f5bd11ed5ea1e498ec423102f7a9b9e4645d5b8204ff2815"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-win32.whl", hash = "sha256:b4ff1d35e8c5bd078be89349b6f3a845128e685e751b6ea1169cf2160b344c4d"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-win_amd64.whl", hash = "sha256:74119174722c4349af9708993118581686f343adc1c8c9c007d59be90d077f3f"}, + {file = "charset_normalizer-3.4.6-cp314-cp314-win_arm64.whl", hash = "sha256:e5bcc1a1ae744e0bb59641171ae53743760130600da8db48cbb6e4918e186e4e"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ad8faf8df23f0378c6d527d8b0b15ea4a2e23c89376877c598c4870d1b2c7866"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f5ea69428fa1b49573eef0cc44a1d43bebd45ad0c611eb7d7eac760c7ae771bc"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:06a7e86163334edfc5d20fe104db92fcd666e5a5df0977cb5680a506fe26cc8e"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e1f6e2f00a6b8edb562826e4632e26d063ac10307e80f7461f7de3ad8ef3f077"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:95b52c68d64c1878818687a473a10547b3292e82b6f6fe483808fb1468e2f52f"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:7504e9b7dc05f99a9bbb4525c67a2c155073b44d720470a148b34166a69c054e"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:172985e4ff804a7ad08eebec0a1640ece87ba5041d565fff23c8f99c1f389484"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:4be9f4830ba8741527693848403e2c457c16e499100963ec711b1c6f2049b7c7"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:79090741d842f564b1b2827c0b82d846405b744d31e84f18d7a7b41c20e473ff"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:87725cfb1a4f1f8c2fc9890ae2f42094120f4b44db9360be5d99a4c6b0e03a9e"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:fcce033e4021347d80ed9c66dcf1e7b1546319834b74445f561d2e2221de5659"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:ca0276464d148c72defa8bb4390cce01b4a0e425f3b50d1435aa6d7a18107602"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:197c1a244a274bb016dd8b79204850144ef77fe81c5b797dc389327adb552407"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-win32.whl", hash = "sha256:2a24157fa36980478dd1770b585c0f30d19e18f4fb0c47c13aa568f871718579"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-win_amd64.whl", hash = "sha256:cd5e2801c89992ed8c0a3f0293ae83c159a60d9a5d685005383ef4caca77f2c4"}, + {file = "charset_normalizer-3.4.6-cp314-cp314t-win_arm64.whl", hash = "sha256:47955475ac79cc504ef2704b192364e51d0d473ad452caedd0002605f780101c"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:659a1e1b500fac8f2779dd9e1570464e012f43e580371470b45277a27baa7532"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f61aa92e4aad0be58eb6eb4e0c21acf32cf8065f4b2cae5665da756c4ceef982"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f50498891691e0864dc3da965f340fada0771f6142a378083dc4608f4ea513e2"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bf625105bb9eef28a56a943fec8c8a98aeb80e7d7db99bd3c388137e6eb2d237"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2bd9d128ef93637a5d7a6af25363cf5dec3fa21cf80e68055aad627f280e8afa"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-manylinux_2_31_armv7l.whl", hash = "sha256:d08ec48f0a1c48d75d0356cea971921848fb620fdeba805b28f937e90691209f"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:1ed80ff870ca6de33f4d953fda4d55654b9a2b340ff39ab32fa3adbcd718f264"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:f98059e4fcd3e3e4e2d632b7cf81c2faae96c43c60b569e9c621468082f1d104"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-musllinux_1_2_armv7l.whl", hash = "sha256:ab30e5e3e706e3063bc6de96b118688cb10396b70bb9864a430f67df98c61ecc"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-musllinux_1_2_ppc64le.whl", hash = "sha256:d5f5d1e9def3405f60e3ca8232d56f35c98fb7bf581efcc60051ebf53cb8b611"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-musllinux_1_2_riscv64.whl", hash = "sha256:461598cd852bfa5a61b09cae2b1c02e2efcd166ee5516e243d540ac24bfa68a7"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-musllinux_1_2_s390x.whl", hash = "sha256:71be7e0e01753a89cf024abf7ecb6bca2c81738ead80d43004d9b5e3f1244e64"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:df01808ee470038c3f8dc4f48620df7225c49c2d6639e38f96e6d6ac6e6f7b0e"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-win32.whl", hash = "sha256:69dd852c2f0ad631b8b60cfbe25a28c0058a894de5abb566619c205ce0550eae"}, + {file = "charset_normalizer-3.4.6-cp38-cp38-win_amd64.whl", hash = "sha256:517ad0e93394ac532745129ceabdf2696b609ec9f87863d337140317ebce1c14"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:31215157227939b4fb3d740cd23fe27be0439afef67b785a1eb78a3ae69cba9e"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecbbd45615a6885fe3240eb9db73b9e62518b611850fdf8ab08bd56de7ad2b17"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c45a03a4c69820a399f1dda9e1d8fbf3562eda46e7720458180302021b08f778"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e8aeb10fcbe92767f0fa69ad5a72deca50d0dca07fbde97848997d778a50c9fe"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54fae94be3d75f3e573c9a1b5402dc593de19377013c9a0e4285e3d402dd3a2a"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-manylinux_2_31_armv7l.whl", hash = "sha256:2f7fdd9b6e6c529d6a2501a2d36b240109e78a8ceaef5687cfcfa2bbe671d297"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d1d02209e06550bdaef34af58e041ad71b88e624f5d825519da3a3308e22687"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:8bc5f0687d796c05b1e28ab0d38a50e6309906ee09375dd3aff6a9c09dd6e8f4"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:ee4ec14bc1680d6b0afab9aea2ef27e26d2024f18b24a2d7155a52b60da7e833"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:d1a2ee9c1499fc8f86f4521f27a973c914b211ffa87322f4ee33bb35392da2c5"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-musllinux_1_2_riscv64.whl", hash = "sha256:48696db7f18afb80a068821504296eb0787d9ce239b91ca15059d1d3eaacf13b"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:4f41da960b196ea355357285ad1316a00099f22d0929fe168343b99b254729c9"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:802168e03fba8bbc5ce0d866d589e4b1ca751d06edee69f7f3a19c5a9fe6b597"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-win32.whl", hash = "sha256:8761ac29b6c81574724322a554605608a9960769ea83d2c73e396f3df896ad54"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-win_amd64.whl", hash = "sha256:1cf0a70018692f85172348fe06d3a4b63f94ecb055e13a00c644d368eb82e5b8"}, + {file = "charset_normalizer-3.4.6-cp39-cp39-win_arm64.whl", hash = "sha256:3516bbb8d42169de9e61b8520cbeeeb716f12f4ecfe3fd30a9919aa16c806ca8"}, + {file = "charset_normalizer-3.4.6-py3-none-any.whl", hash = "sha256:947cf925bc916d90adba35a64c82aace04fa39b46b52d4630ece166655905a69"}, + {file = "charset_normalizer-3.4.6.tar.gz", hash = "sha256:1ae6b62897110aa7c79ea2f5dd38d1abca6db663687c0b1ad9aed6f6bae3d9d6"}, +] + +[[package]] +name = "click" +version = "8.1.8" +description = "Composable command line interface toolkit" +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"}, + {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} + +[[package]] +name = "cloudevents" +version = "1.12.1" +description = "CloudEvents Python SDK" +optional = false +python-versions = "*" +groups = ["main"] +files = [ + {file = "cloudevents-1.12.1-py3-none-any.whl", hash = "sha256:5f1574bf49ff334381319bdddcab02175a69ca877a26d0900b59c85505b675b3"}, + {file = "cloudevents-1.12.1.tar.gz", hash = "sha256:1eb52051309c3228934f86f41d50bd02c0e3d9561e5876e73ad8ad9f98f0d3ef"}, +] + +[package.dependencies] +deprecation = ">=2.0,<3.0" + +[package.extras] +pydantic = ["pydantic (>=1.0.0,<3.0)"] + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +groups = ["dev"] +markers = "platform_system == \"Windows\"" +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] + +[[package]] +name = "corehttp" +version = "1.0.0b7" +description = "CoreHTTP Library for Python" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "corehttp-1.0.0b7-py3-none-any.whl", hash = "sha256:d20d0291407458789298fbee27a551a60156a1ba23a8fd27ec0a0e63c48f8718"}, + {file = "corehttp-1.0.0b7.tar.gz", hash = "sha256:f21b71028a62e67e346f4669590b1285afa09145d39a50573b3cfabf9c7b2457"}, +] + +[package.dependencies] +aiohttp = {version = ">=3.0", optional = true, markers = "extra == \"aiohttp\""} +requests = {version = ">=2.18.4", optional = true, markers = "extra == \"requests\""} +typing-extensions = ">=4.6.0" + +[package.extras] +aiohttp = ["aiohttp (>=3.0)"] +httpx = ["httpx (>=0.25.0)"] +requests = ["requests (>=2.18.4)"] +tracing = ["opentelemetry-api (>=1.26,<2.0)"] + +[[package]] +name = "deprecation" +version = "2.1.0" +description = "A library to handle automated deprecations" +optional = false +python-versions = "*" +groups = ["main"] +files = [ + {file = "deprecation-2.1.0-py2.py3-none-any.whl", hash = "sha256:a10811591210e1fb0e768a8c25517cabeabcba6f0bf96564f8ff45189f90b14a"}, + {file = "deprecation-2.1.0.tar.gz", hash = "sha256:72b3bde64e5d778694b0cf68178aed03d15e15477116add3fb773e581f9518ff"}, +] + +[package.dependencies] +packaging = "*" + +[[package]] +name = "frozenlist" +version = "1.8.0" +description = "A list-like structure which implements collections.abc.MutableSequence" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "frozenlist-1.8.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b37f6d31b3dcea7deb5e9696e529a6aa4a898adc33db82da12e4c60a7c4d2011"}, + {file = "frozenlist-1.8.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ef2b7b394f208233e471abc541cc6991f907ffd47dc72584acee3147899d6565"}, + {file = "frozenlist-1.8.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:a88f062f072d1589b7b46e951698950e7da00442fc1cacbe17e19e025dc327ad"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f57fb59d9f385710aa7060e89410aeb5058b99e62f4d16b08b91986b9a2140c2"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:799345ab092bee59f01a915620b5d014698547afd011e691a208637312db9186"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c23c3ff005322a6e16f71bf8692fcf4d5a304aaafe1e262c98c6d4adc7be863e"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8a76ea0f0b9dfa06f254ee06053d93a600865b3274358ca48a352ce4f0798450"}, + {file = "frozenlist-1.8.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c7366fe1418a6133d5aa824ee53d406550110984de7637d65a178010f759c6ef"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:13d23a45c4cebade99340c4165bd90eeb4a56c6d8a9d8aa49568cac19a6d0dc4"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:e4a3408834f65da56c83528fb52ce7911484f0d1eaf7b761fc66001db1646eff"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:42145cd2748ca39f32801dad54aeea10039da6f86e303659db90db1c4b614c8c"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:e2de870d16a7a53901e41b64ffdf26f2fbb8917b3e6ebf398098d72c5b20bd7f"}, + {file = "frozenlist-1.8.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:20e63c9493d33ee48536600d1a5c95eefc870cd71e7ab037763d1fbb89cc51e7"}, + {file = "frozenlist-1.8.0-cp310-cp310-win32.whl", hash = "sha256:adbeebaebae3526afc3c96fad434367cafbfd1b25d72369a9e5858453b1bb71a"}, + {file = "frozenlist-1.8.0-cp310-cp310-win_amd64.whl", hash = "sha256:667c3777ca571e5dbeb76f331562ff98b957431df140b54c85fd4d52eea8d8f6"}, + {file = "frozenlist-1.8.0-cp310-cp310-win_arm64.whl", hash = "sha256:80f85f0a7cc86e7a54c46d99c9e1318ff01f4687c172ede30fd52d19d1da1c8e"}, + {file = "frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84"}, + {file = "frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9"}, + {file = "frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581"}, + {file = "frozenlist-1.8.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd"}, + {file = "frozenlist-1.8.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967"}, + {file = "frozenlist-1.8.0-cp311-cp311-win32.whl", hash = "sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25"}, + {file = "frozenlist-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b"}, + {file = "frozenlist-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a"}, + {file = "frozenlist-1.8.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1"}, + {file = "frozenlist-1.8.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b"}, + {file = "frozenlist-1.8.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b"}, + {file = "frozenlist-1.8.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608"}, + {file = "frozenlist-1.8.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa"}, + {file = "frozenlist-1.8.0-cp312-cp312-win32.whl", hash = "sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf"}, + {file = "frozenlist-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746"}, + {file = "frozenlist-1.8.0-cp312-cp312-win_arm64.whl", hash = "sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd"}, + {file = "frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a"}, + {file = "frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7"}, + {file = "frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5"}, + {file = "frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8"}, + {file = "frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed"}, + {file = "frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496"}, + {file = "frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231"}, + {file = "frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62"}, + {file = "frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94"}, + {file = "frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c"}, + {file = "frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714"}, + {file = "frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0"}, + {file = "frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41"}, + {file = "frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b"}, + {file = "frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888"}, + {file = "frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042"}, + {file = "frozenlist-1.8.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0"}, + {file = "frozenlist-1.8.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f"}, + {file = "frozenlist-1.8.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e"}, + {file = "frozenlist-1.8.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30"}, + {file = "frozenlist-1.8.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7"}, + {file = "frozenlist-1.8.0-cp314-cp314-win32.whl", hash = "sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806"}, + {file = "frozenlist-1.8.0-cp314-cp314-win_amd64.whl", hash = "sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0"}, + {file = "frozenlist-1.8.0-cp314-cp314-win_arm64.whl", hash = "sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b"}, + {file = "frozenlist-1.8.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d"}, + {file = "frozenlist-1.8.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed"}, + {file = "frozenlist-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a"}, + {file = "frozenlist-1.8.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a"}, + {file = "frozenlist-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e"}, + {file = "frozenlist-1.8.0-cp314-cp314t-win32.whl", hash = "sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df"}, + {file = "frozenlist-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd"}, + {file = "frozenlist-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79"}, + {file = "frozenlist-1.8.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:d8b7138e5cd0647e4523d6685b0eac5d4be9a184ae9634492f25c6eb38c12a47"}, + {file = "frozenlist-1.8.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a6483e309ca809f1efd154b4d37dc6d9f61037d6c6a81c2dc7a15cb22c8c5dca"}, + {file = "frozenlist-1.8.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1b9290cf81e95e93fdf90548ce9d3c1211cf574b8e3f4b3b7cb0537cf2227068"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:59a6a5876ca59d1b63af8cd5e7ffffb024c3dc1e9cf9301b21a2e76286505c95"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6dc4126390929823e2d2d9dc79ab4046ed74680360fc5f38b585c12c66cdf459"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:332db6b2563333c5671fecacd085141b5800cb866be16d5e3eb15a2086476675"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9ff15928d62a0b80bb875655c39bf517938c7d589554cbd2669be42d97c2cb61"}, + {file = "frozenlist-1.8.0-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7bf6cdf8e07c8151fba6fe85735441240ec7f619f935a5205953d58009aef8c6"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:48e6d3f4ec5c7273dfe83ff27c91083c6c9065af655dc2684d2c200c94308bb5"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:1a7607e17ad33361677adcd1443edf6f5da0ce5e5377b798fba20fae194825f3"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:5a3a935c3a4e89c733303a2d5a7c257ea44af3a56c8202df486b7f5de40f37e1"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:940d4a017dbfed9daf46a3b086e1d2167e7012ee297fef9e1c545c4d022f5178"}, + {file = "frozenlist-1.8.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:b9be22a69a014bc47e78072d0ecae716f5eb56c15238acca0f43d6eb8e4a5bda"}, + {file = "frozenlist-1.8.0-cp39-cp39-win32.whl", hash = "sha256:1aa77cb5697069af47472e39612976ed05343ff2e84a3dcf15437b232cbfd087"}, + {file = "frozenlist-1.8.0-cp39-cp39-win_amd64.whl", hash = "sha256:7398c222d1d405e796970320036b1b563892b65809d9e5261487bb2c7f7b5c6a"}, + {file = "frozenlist-1.8.0-cp39-cp39-win_arm64.whl", hash = "sha256:b4f3b365f31c6cd4af24545ca0a244a53688cad8834e32f56831c4923b50a103"}, + {file = "frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d"}, + {file = "frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad"}, +] + +[[package]] +name = "idna" +version = "3.15" +description = "Internationalized Domain Names in Applications (IDNA)" +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8"}, + {file = "idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc"}, +] + +[package.extras] +all = ["mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2)"] + +[[package]] +name = "isodate" +version = "0.7.2" +description = "An ISO 8601 date/time/duration parser and formatter" +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "isodate-0.7.2-py3-none-any.whl", hash = "sha256:28009937d8031054830160fce6d409ed342816b543597cece116d966c6d99e15"}, + {file = "isodate-0.7.2.tar.gz", hash = "sha256:4cd1aa0f43ca76f4a6c6c0292a85f40b35ec2e43e315b59f06e6d32171a953e6"}, +] + +[[package]] +name = "multidict" +version = "6.7.1" +description = "multidict implementation" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "multidict-6.7.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c93c3db7ea657dd4637d57e74ab73de31bccefe144d3d4ce370052035bc85fb5"}, + {file = "multidict-6.7.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:974e72a2474600827abaeda71af0c53d9ebbc3c2eb7da37b37d7829ae31232d8"}, + {file = "multidict-6.7.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:cdea2e7b2456cfb6694fb113066fd0ec7ea4d67e3a35e1f4cbeea0b448bf5872"}, + {file = "multidict-6.7.1-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17207077e29342fdc2c9a82e4b306f1127bf1ea91f8b71e02d4798a70bb99991"}, + {file = "multidict-6.7.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4f49cb5661344764e4c7c7973e92a47a59b8fc19b6523649ec9dc4960e58a03"}, + {file = "multidict-6.7.1-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a9fc4caa29e2e6ae408d1c450ac8bf19892c5fca83ee634ecd88a53332c59981"}, + {file = "multidict-6.7.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c5f0c21549ab432b57dcc82130f388d84ad8179824cc3f223d5e7cfbfd4143f6"}, + {file = "multidict-6.7.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7dfb78d966b2c906ae1d28ccf6e6712a3cd04407ee5088cd276fe8cb42186190"}, + {file = "multidict-6.7.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9b0d9b91d1aa44db9c1f1ecd0d9d2ae610b2f4f856448664e01a3b35899f3f92"}, + {file = "multidict-6.7.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:dd96c01a9dcd4889dcfcf9eb5544ca0c77603f239e3ffab0524ec17aea9a93ee"}, + {file = "multidict-6.7.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:067343c68cd6612d375710f895337b3a98a033c94f14b9a99eff902f205424e2"}, + {file = "multidict-6.7.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:5884a04f4ff56c6120f6ccf703bdeb8b5079d808ba604d4d53aec0d55dc33568"}, + {file = "multidict-6.7.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8affcf1c98b82bc901702eb73b6947a1bfa170823c153fe8a47b5f5f02e48e40"}, + {file = "multidict-6.7.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:0d17522c37d03e85c8098ec8431636309b2682cf12e58f4dbc76121fb50e4962"}, + {file = "multidict-6.7.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:24c0cf81544ca5e17cfcb6e482e7a82cd475925242b308b890c9452a074d4505"}, + {file = "multidict-6.7.1-cp310-cp310-win32.whl", hash = "sha256:d82dd730a95e6643802f4454b8fdecdf08667881a9c5670db85bc5a56693f122"}, + {file = "multidict-6.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:cf37cbe5ced48d417ba045aca1b21bafca67489452debcde94778a576666a1df"}, + {file = "multidict-6.7.1-cp310-cp310-win_arm64.whl", hash = "sha256:59bc83d3f66b41dac1e7460aac1d196edc70c9ba3094965c467715a70ecb46db"}, + {file = "multidict-6.7.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7ff981b266af91d7b4b3793ca3382e53229088d193a85dfad6f5f4c27fc73e5d"}, + {file = "multidict-6.7.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:844c5bca0b5444adb44a623fb0a1310c2f4cd41f402126bb269cd44c9b3f3e1e"}, + {file = "multidict-6.7.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f2a0a924d4c2e9afcd7ec64f9de35fcd96915149b2216e1cb2c10a56df483855"}, + {file = "multidict-6.7.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:8be1802715a8e892c784c0197c2ace276ea52702a0ede98b6310c8f255a5afb3"}, + {file = "multidict-6.7.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2e2d2ed645ea29f31c4c7ea1552fcfd7cb7ba656e1eafd4134a6620c9f5fdd9e"}, + {file = "multidict-6.7.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:95922cee9a778659e91db6497596435777bd25ed116701a4c034f8e46544955a"}, + {file = "multidict-6.7.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6b83cabdc375ffaaa15edd97eb7c0c672ad788e2687004990074d7d6c9b140c8"}, + {file = "multidict-6.7.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:38fb49540705369bab8484db0689d86c0a33a0a9f2c1b197f506b71b4b6c19b0"}, + {file = "multidict-6.7.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:439cbebd499f92e9aa6793016a8acaa161dfa749ae86d20960189f5398a19144"}, + {file = "multidict-6.7.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6d3bc717b6fe763b8be3f2bee2701d3c8eb1b2a8ae9f60910f1b2860c82b6c49"}, + {file = "multidict-6.7.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:619e5a1ac57986dbfec9f0b301d865dddf763696435e2962f6d9cf2fdff2bb71"}, + {file = "multidict-6.7.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:0b38ebffd9be37c1170d33bc0f36f4f262e0a09bc1aac1c34c7aa51a7293f0b3"}, + {file = "multidict-6.7.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:10ae39c9cfe6adedcdb764f5e8411d4a92b055e35573a2eaa88d3323289ef93c"}, + {file = "multidict-6.7.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:25167cc263257660290fba06b9318d2026e3c910be240a146e1f66dd114af2b0"}, + {file = "multidict-6.7.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:128441d052254f42989ef98b7b6a6ecb1e6f708aa962c7984235316db59f50fa"}, + {file = "multidict-6.7.1-cp311-cp311-win32.whl", hash = "sha256:d62b7f64ffde3b99d06b707a280db04fb3855b55f5a06df387236051d0668f4a"}, + {file = "multidict-6.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:bdbf9f3b332abd0cdb306e7c2113818ab1e922dc84b8f8fd06ec89ed2a19ab8b"}, + {file = "multidict-6.7.1-cp311-cp311-win_arm64.whl", hash = "sha256:b8c990b037d2fff2f4e33d3f21b9b531c5745b33a49a7d6dbe7a177266af44f6"}, + {file = "multidict-6.7.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a90f75c956e32891a4eda3639ce6dd86e87105271f43d43442a3aedf3cddf172"}, + {file = "multidict-6.7.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fccb473e87eaa1382689053e4a4618e7ba7b9b9b8d6adf2027ee474597128cd"}, + {file = "multidict-6.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:b0fa96985700739c4c7853a43c0b3e169360d6855780021bfc6d0f1ce7c123e7"}, + {file = "multidict-6.7.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cb2a55f408c3043e42b40cc8eecd575afa27b7e0b956dfb190de0f8499a57a53"}, + {file = "multidict-6.7.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb0ce7b2a32d09892b3dd6cc44877a0d02a33241fafca5f25c8b6b62374f8b75"}, + {file = "multidict-6.7.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c3a32d23520ee37bf327d1e1a656fec76a2edd5c038bf43eddfa0572ec49c60b"}, + {file = "multidict-6.7.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c90fed18bffc0189ba814749fdcc102b536e83a9f738a9003e569acd540a733"}, + {file = "multidict-6.7.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:da62917e6076f512daccfbbde27f46fed1c98fee202f0559adec8ee0de67f71a"}, + {file = "multidict-6.7.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bfde23ef6ed9db7eaee6c37dcec08524cb43903c60b285b172b6c094711b3961"}, + {file = "multidict-6.7.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3758692429e4e32f1ba0df23219cd0b4fc0a52f476726fff9337d1a57676a582"}, + {file = "multidict-6.7.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:398c1478926eca669f2fd6a5856b6de9c0acf23a2cb59a14c0ba5844fa38077e"}, + {file = "multidict-6.7.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:c102791b1c4f3ab36ce4101154549105a53dc828f016356b3e3bcae2e3a039d3"}, + {file = "multidict-6.7.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a088b62bd733e2ad12c50dad01b7d0166c30287c166e137433d3b410add807a6"}, + {file = "multidict-6.7.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:3d51ff4785d58d3f6c91bdbffcb5e1f7ddfda557727043aa20d20ec4f65e324a"}, + {file = "multidict-6.7.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc5907494fccf3e7d3f94f95c91d6336b092b5fc83811720fae5e2765890dfba"}, + {file = "multidict-6.7.1-cp312-cp312-win32.whl", hash = "sha256:28ca5ce2fd9716631133d0e9a9b9a745ad7f60bac2bccafb56aa380fc0b6c511"}, + {file = "multidict-6.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:fcee94dfbd638784645b066074b338bc9cc155d4b4bffa4adce1615c5a426c19"}, + {file = "multidict-6.7.1-cp312-cp312-win_arm64.whl", hash = "sha256:ba0a9fb644d0c1a2194cf7ffb043bd852cea63a57f66fbd33959f7dae18517bf"}, + {file = "multidict-6.7.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:2b41f5fed0ed563624f1c17630cb9941cf2309d4df00e494b551b5f3e3d67a23"}, + {file = "multidict-6.7.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:84e61e3af5463c19b67ced91f6c634effb89ef8bfc5ca0267f954451ed4bb6a2"}, + {file = "multidict-6.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:935434b9853c7c112eee7ac891bc4cb86455aa631269ae35442cb316790c1445"}, + {file = "multidict-6.7.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:432feb25a1cb67fe82a9680b4d65fb542e4635cb3166cd9c01560651ad60f177"}, + {file = "multidict-6.7.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e82d14e3c948952a1a85503817e038cba5905a3352de76b9a465075d072fba23"}, + {file = "multidict-6.7.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4cfb48c6ea66c83bcaaf7e4dfa7ec1b6bbcf751b7db85a328902796dfde4c060"}, + {file = "multidict-6.7.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1d540e51b7e8e170174555edecddbd5538105443754539193e3e1061864d444d"}, + {file = "multidict-6.7.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:273d23f4b40f3dce4d6c8a821c741a86dec62cded82e1175ba3d99be128147ed"}, + {file = "multidict-6.7.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d624335fd4fa1c08a53f8b4be7676ebde19cd092b3895c421045ca87895b429"}, + {file = "multidict-6.7.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:12fad252f8b267cc75b66e8fc51b3079604e8d43a75428ffe193cd9e2195dfd6"}, + {file = "multidict-6.7.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:03ede2a6ffbe8ef936b92cb4529f27f42be7f56afcdab5ab739cd5f27fb1cbf9"}, + {file = "multidict-6.7.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:90efbcf47dbe33dcf643a1e400d67d59abeac5db07dc3f27d6bdeae497a2198c"}, + {file = "multidict-6.7.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5c4b9bfc148f5a91be9244d6264c53035c8a0dcd2f51f1c3c6e30e30ebaa1c84"}, + {file = "multidict-6.7.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:401c5a650f3add2472d1d288c26deebc540f99e2fb83e9525007a74cd2116f1d"}, + {file = "multidict-6.7.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:97891f3b1b3ffbded884e2916cacf3c6fc87b66bb0dde46f7357404750559f33"}, + {file = "multidict-6.7.1-cp313-cp313-win32.whl", hash = "sha256:e1c5988359516095535c4301af38d8a8838534158f649c05dd1050222321bcb3"}, + {file = "multidict-6.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:960c83bf01a95b12b08fd54324a4eb1d5b52c88932b5cba5d6e712bb3ed12eb5"}, + {file = "multidict-6.7.1-cp313-cp313-win_arm64.whl", hash = "sha256:563fe25c678aaba333d5399408f5ec3c383ca5b663e7f774dd179a520b8144df"}, + {file = "multidict-6.7.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:c76c4bec1538375dad9d452d246ca5368ad6e1c9039dadcf007ae59c70619ea1"}, + {file = "multidict-6.7.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:57b46b24b5d5ebcc978da4ec23a819a9402b4228b8a90d9c656422b4bdd8a963"}, + {file = "multidict-6.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e954b24433c768ce78ab7929e84ccf3422e46deb45a4dc9f93438f8217fa2d34"}, + {file = "multidict-6.7.1-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3bd231490fa7217cc832528e1cd8752a96f0125ddd2b5749390f7c3ec8721b65"}, + {file = "multidict-6.7.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:253282d70d67885a15c8a7716f3a73edf2d635793ceda8173b9ecc21f2fb8292"}, + {file = "multidict-6.7.1-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0b4c48648d7649c9335cf1927a8b87fa692de3dcb15faa676c6a6f1f1aabda43"}, + {file = "multidict-6.7.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:98bc624954ec4d2c7cb074b8eefc2b5d0ce7d482e410df446414355d158fe4ca"}, + {file = "multidict-6.7.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1b99af4d9eec0b49927b4402bcbb58dea89d3e0db8806a4086117019939ad3dd"}, + {file = "multidict-6.7.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6aac4f16b472d5b7dc6f66a0d49dd57b0e0902090be16594dc9ebfd3d17c47e7"}, + {file = "multidict-6.7.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:21f830fe223215dffd51f538e78c172ed7c7f60c9b96a2bf05c4848ad49921c3"}, + {file = "multidict-6.7.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f5dd81c45b05518b9aa4da4aa74e1c93d715efa234fd3e8a179df611cc85e5f4"}, + {file = "multidict-6.7.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:eb304767bca2bb92fb9c5bd33cedc95baee5bb5f6c88e63706533a1c06ad08c8"}, + {file = "multidict-6.7.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:c9035dde0f916702850ef66460bc4239d89d08df4d02023a5926e7446724212c"}, + {file = "multidict-6.7.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:af959b9beeb66c822380f222f0e0a1889331597e81f1ded7f374f3ecb0fd6c52"}, + {file = "multidict-6.7.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:41f2952231456154ee479651491e94118229844dd7226541788be783be2b5108"}, + {file = "multidict-6.7.1-cp313-cp313t-win32.whl", hash = "sha256:df9f19c28adcb40b6aae30bbaa1478c389efd50c28d541d76760199fc1037c32"}, + {file = "multidict-6.7.1-cp313-cp313t-win_amd64.whl", hash = "sha256:d54ecf9f301853f2c5e802da559604b3e95bb7a3b01a9c295c6ee591b9882de8"}, + {file = "multidict-6.7.1-cp313-cp313t-win_arm64.whl", hash = "sha256:5a37ca18e360377cfda1d62f5f382ff41f2b8c4ccb329ed974cc2e1643440118"}, + {file = "multidict-6.7.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8f333ec9c5eb1b7105e3b84b53141e66ca05a19a605368c55450b6ba208cb9ee"}, + {file = "multidict-6.7.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a407f13c188f804c759fc6a9f88286a565c242a76b27626594c133b82883b5c2"}, + {file = "multidict-6.7.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0e161ddf326db5577c3a4cc2d8648f81456e8a20d40415541587a71620d7a7d1"}, + {file = "multidict-6.7.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:1e3a8bb24342a8201d178c3b4984c26ba81a577c80d4d525727427460a50c22d"}, + {file = "multidict-6.7.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97231140a50f5d447d3164f994b86a0bed7cd016e2682f8650d6a9158e14fd31"}, + {file = "multidict-6.7.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b10359683bd8806a200fd2909e7c8ca3a7b24ec1d8132e483d58e791d881048"}, + {file = "multidict-6.7.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:283ddac99f7ac25a4acadbf004cb5ae34480bbeb063520f70ce397b281859362"}, + {file = "multidict-6.7.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:538cec1e18c067d0e6103aa9a74f9e832904c957adc260e61cd9d8cf0c3b3d37"}, + {file = "multidict-6.7.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7eee46ccb30ff48a1e35bb818cc90846c6be2b68240e42a78599166722cea709"}, + {file = "multidict-6.7.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa263a02f4f2dd2d11a7b1bb4362aa7cb1049f84a9235d31adf63f30143469a0"}, + {file = "multidict-6.7.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:2e1425e2f99ec5bd36c15a01b690a1a2456209c5deed58f95469ffb46039ccbb"}, + {file = "multidict-6.7.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:497394b3239fc6f0e13a78a3e1b61296e72bf1c5f94b4c4eb80b265c37a131cd"}, + {file = "multidict-6.7.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:233b398c29d3f1b9676b4b6f75c518a06fcb2ea0b925119fb2c1bc35c05e1601"}, + {file = "multidict-6.7.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:93b1818e4a6e0930454f0f2af7dfce69307ca03cdcfb3739bf4d91241967b6c1"}, + {file = "multidict-6.7.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f33dc2a3abe9249ea5d8360f969ec7f4142e7ac45ee7014d8f8d5acddf178b7b"}, + {file = "multidict-6.7.1-cp314-cp314-win32.whl", hash = "sha256:3ab8b9d8b75aef9df299595d5388b14530839f6422333357af1339443cff777d"}, + {file = "multidict-6.7.1-cp314-cp314-win_amd64.whl", hash = "sha256:5e01429a929600e7dab7b166062d9bb54a5eed752384c7384c968c2afab8f50f"}, + {file = "multidict-6.7.1-cp314-cp314-win_arm64.whl", hash = "sha256:4885cb0e817aef5d00a2e8451d4665c1808378dc27c2705f1bf4ef8505c0d2e5"}, + {file = "multidict-6.7.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0458c978acd8e6ea53c81eefaddbbee9c6c5e591f41b3f5e8e194780fe026581"}, + {file = "multidict-6.7.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c0abd12629b0af3cf590982c0b413b1e7395cd4ec026f30986818ab95bfaa94a"}, + {file = "multidict-6.7.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:14525a5f61d7d0c94b368a42cff4c9a4e7ba2d52e2672a7b23d84dc86fb02b0c"}, + {file = "multidict-6.7.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:17307b22c217b4cf05033dabefe68255a534d637c6c9b0cc8382718f87be4262"}, + {file = "multidict-6.7.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a7e590ff876a3eaf1c02a4dfe0724b6e69a9e9de6d8f556816f29c496046e59"}, + {file = "multidict-6.7.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:5fa6a95dfee63893d80a34758cd0e0c118a30b8dcb46372bf75106c591b77889"}, + {file = "multidict-6.7.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a0543217a6a017692aa6ae5cc39adb75e587af0f3a82288b1492eb73dd6cc2a4"}, + {file = "multidict-6.7.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f99fe611c312b3c1c0ace793f92464d8cd263cc3b26b5721950d977b006b6c4d"}, + {file = "multidict-6.7.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9004d8386d133b7e6135679424c91b0b854d2d164af6ea3f289f8f2761064609"}, + {file = "multidict-6.7.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e628ef0e6859ffd8273c69412a2465c4be4a9517d07261b33334b5ec6f3c7489"}, + {file = "multidict-6.7.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:841189848ba629c3552035a6a7f5bf3b02eb304e9fea7492ca220a8eda6b0e5c"}, + {file = "multidict-6.7.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:ce1bbd7d780bb5a0da032e095c951f7014d6b0a205f8318308140f1a6aba159e"}, + {file = "multidict-6.7.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:b26684587228afed0d50cf804cc71062cc9c1cdf55051c4c6345d372947b268c"}, + {file = "multidict-6.7.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:9f9af11306994335398293f9958071019e3ab95e9a707dc1383a35613f6abcb9"}, + {file = "multidict-6.7.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b4938326284c4f1224178a560987b6cf8b4d38458b113d9b8c1db1a836e640a2"}, + {file = "multidict-6.7.1-cp314-cp314t-win32.whl", hash = "sha256:98655c737850c064a65e006a3df7c997cd3b220be4ec8fe26215760b9697d4d7"}, + {file = "multidict-6.7.1-cp314-cp314t-win_amd64.whl", hash = "sha256:497bde6223c212ba11d462853cfa4f0ae6ef97465033e7dc9940cdb3ab5b48e5"}, + {file = "multidict-6.7.1-cp314-cp314t-win_arm64.whl", hash = "sha256:2bbd113e0d4af5db41d5ebfe9ccaff89de2120578164f86a5d17d5a576d1e5b2"}, + {file = "multidict-6.7.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:65573858d27cdeaca41893185677dc82395159aa28875a8867af66532d413a8f"}, + {file = "multidict-6.7.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c524c6fb8fc342793708ab111c4dbc90ff9abd568de220432500e47e990c0358"}, + {file = "multidict-6.7.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:aa23b001d968faef416ff70dc0f1ab045517b9b42a90edd3e9bcdb06479e31d5"}, + {file = "multidict-6.7.1-cp39-cp39-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:6704fa2b7453b2fb121740555fa1ee20cd98c4d011120caf4d2b8d4e7c76eec0"}, + {file = "multidict-6.7.1-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:121a34e5bfa410cdf2c8c49716de160de3b1dbcd86b49656f5681e4543bcd1a8"}, + {file = "multidict-6.7.1-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:026d264228bcd637d4e060844e39cdc60f86c479e463d49075dedc21b18fbbe0"}, + {file = "multidict-6.7.1-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0e697826df7eb63418ee190fd06ce9f1803593bb4b9517d08c60d9b9a7f69d8f"}, + {file = "multidict-6.7.1-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bb08271280173720e9fea9ede98e5231defcbad90f1624bea26f32ec8a956e2f"}, + {file = "multidict-6.7.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c6b3228e1d80af737b72925ce5fb4daf5a335e49cd7ab77ed7b9fdfbf58c526e"}, + {file = "multidict-6.7.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:3943debf0fbb57bdde5901695c11094a9a36723e5c03875f87718ee15ca2f4d2"}, + {file = "multidict-6.7.1-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:98c5787b0a0d9a41d9311eae44c3b76e6753def8d8870ab501320efe75a6a5f8"}, + {file = "multidict-6.7.1-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:08ccb2a6dc72009093ebe7f3f073e5ec5964cba9a706fa94b1a1484039b87941"}, + {file = "multidict-6.7.1-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:eb351f72c26dc9abe338ca7294661aa22969ad8ffe7ef7d5541d19f368dc854a"}, + {file = "multidict-6.7.1-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:ac1c665bad8b5d762f5f85ebe4d94130c26965f11de70c708c75671297c776de"}, + {file = "multidict-6.7.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:1fa6609d0364f4f6f58351b4659a1f3e0e898ba2a8c5cac04cb2c7bc556b0bc5"}, + {file = "multidict-6.7.1-cp39-cp39-win32.whl", hash = "sha256:6f77ce314a29263e67adadc7e7c1bc699fcb3a305059ab973d038f87caa42ed0"}, + {file = "multidict-6.7.1-cp39-cp39-win_amd64.whl", hash = "sha256:f537b55778cd3cbee430abe3131255d3a78202e0f9ea7ffc6ada893a4bcaeea4"}, + {file = "multidict-6.7.1-cp39-cp39-win_arm64.whl", hash = "sha256:749aa54f578f2e5f439538706a475aa844bfa8ef75854b1401e6e528e4937cf9"}, + {file = "multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56"}, + {file = "multidict-6.7.1.tar.gz", hash = "sha256:ec6652a1bee61c53a3e5776b6049172c53b6aaba34f18c9ad04f82712bac623d"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.1.0", markers = "python_version < \"3.11\""} + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +description = "Type system extensions for programs checked with the mypy type checker." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505"}, + {file = "mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558"}, +] + +[[package]] +name = "packaging" +version = "26.0" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.8" +groups = ["main", "dev"] +files = [ + {file = "packaging-26.0-py3-none-any.whl", hash = "sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529"}, + {file = "packaging-26.0.tar.gz", hash = "sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4"}, +] + +[[package]] +name = "pathspec" +version = "1.0.4" +description = "Utility library for gitignore style pattern matching of file paths." +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "pathspec-1.0.4-py3-none-any.whl", hash = "sha256:fb6ae2fd4e7c921a165808a552060e722767cfa526f99ca5156ed2ce45a5c723"}, + {file = "pathspec-1.0.4.tar.gz", hash = "sha256:0210e2ae8a21a9137c0d470578cb0e595af87edaa6ebf12ff176f14a02e0e645"}, +] + +[package.extras] +hyperscan = ["hyperscan (>=0.7)"] +optional = ["typing-extensions (>=4)"] +re2 = ["google-re2 (>=1.1)"] +tests = ["pytest (>=9)", "typing-extensions (>=4.15)"] + +[[package]] +name = "platformdirs" +version = "4.4.0" +description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`." +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "platformdirs-4.4.0-py3-none-any.whl", hash = "sha256:abd01743f24e5287cd7a5db3752faf1a2d65353f38ec26d98e25a6db65958c85"}, + {file = "platformdirs-4.4.0.tar.gz", hash = "sha256:ca753cf4d81dc309bc67b0ea38fd15dc97bc30ce419a7f58d13eb3bf14c4febf"}, +] + +[package.extras] +docs = ["furo (>=2024.8.6)", "proselint (>=0.14)", "sphinx (>=8.1.3)", "sphinx-autodoc-typehints (>=3)"] +test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=8.3.4)", "pytest-cov (>=6)", "pytest-mock (>=3.14)"] +type = ["mypy (>=1.14.1)"] + +[[package]] +name = "propcache" +version = "0.4.1" +description = "Accelerated property cache" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "propcache-0.4.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7c2d1fa3201efaf55d730400d945b5b3ab6e672e100ba0f9a409d950ab25d7db"}, + {file = "propcache-0.4.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1eb2994229cc8ce7fe9b3db88f5465f5fd8651672840b2e426b88cdb1a30aac8"}, + {file = "propcache-0.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:66c1f011f45a3b33d7bcb22daed4b29c0c9e2224758b6be00686731e1b46f925"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9a52009f2adffe195d0b605c25ec929d26b36ef986ba85244891dee3b294df21"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5d4e2366a9c7b837555cf02fb9be2e3167d333aff716332ef1b7c3a142ec40c5"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9d2b6caef873b4f09e26ea7e33d65f42b944837563a47a94719cc3544319a0db"}, + {file = "propcache-0.4.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2b16ec437a8c8a965ecf95739448dd938b5c7f56e67ea009f4300d8df05f32b7"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:296f4c8ed03ca7476813fe666c9ea97869a8d7aec972618671b33a38a5182ef4"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:1f0978529a418ebd1f49dad413a2b68af33f85d5c5ca5c6ca2a3bed375a7ac60"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:fd138803047fb4c062b1c1dd95462f5209456bfab55c734458f15d11da288f8f"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:8c9b3cbe4584636d72ff556d9036e0c9317fa27b3ac1f0f558e7e84d1c9c5900"}, + {file = "propcache-0.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:f93243fdc5657247533273ac4f86ae106cc6445a0efacb9a1bfe982fcfefd90c"}, + {file = "propcache-0.4.1-cp310-cp310-win32.whl", hash = "sha256:a0ee98db9c5f80785b266eb805016e36058ac72c51a064040f2bc43b61101cdb"}, + {file = "propcache-0.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:1cdb7988c4e5ac7f6d175a28a9aa0c94cb6f2ebe52756a3c0cda98d2809a9e37"}, + {file = "propcache-0.4.1-cp310-cp310-win_arm64.whl", hash = "sha256:d82ad62b19645419fe79dd63b3f9253e15b30e955c0170e5cebc350c1844e581"}, + {file = "propcache-0.4.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:60a8fda9644b7dfd5dece8c61d8a85e271cb958075bfc4e01083c148b61a7caf"}, + {file = "propcache-0.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c30b53e7e6bda1d547cabb47c825f3843a0a1a42b0496087bb58d8fedf9f41b5"}, + {file = "propcache-0.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6918ecbd897443087a3b7cd978d56546a812517dcaaca51b49526720571fa93e"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3d902a36df4e5989763425a8ab9e98cd8ad5c52c823b34ee7ef307fd50582566"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a9695397f85973bb40427dedddf70d8dc4a44b22f1650dd4af9eedf443d45165"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2bb07ffd7eaad486576430c89f9b215f9e4be68c4866a96e97db9e97fead85dc"}, + {file = "propcache-0.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fd6f30fdcf9ae2a70abd34da54f18da086160e4d7d9251f81f3da0ff84fc5a48"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fc38cba02d1acba4e2869eef1a57a43dfbd3d49a59bf90dda7444ec2be6a5570"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:67fad6162281e80e882fb3ec355398cf72864a54069d060321f6cd0ade95fe85"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f10207adf04d08bec185bae14d9606a1444715bc99180f9331c9c02093e1959e"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:e9b0d8d0845bbc4cfcdcbcdbf5086886bc8157aa963c31c777ceff7846c77757"}, + {file = "propcache-0.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:981333cb2f4c1896a12f4ab92a9cc8f09ea664e9b7dbdc4eff74627af3a11c0f"}, + {file = "propcache-0.4.1-cp311-cp311-win32.whl", hash = "sha256:f1d2f90aeec838a52f1c1a32fe9a619fefd5e411721a9117fbf82aea638fe8a1"}, + {file = "propcache-0.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:364426a62660f3f699949ac8c621aad6977be7126c5807ce48c0aeb8e7333ea6"}, + {file = "propcache-0.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:e53f3a38d3510c11953f3e6a33f205c6d1b001129f972805ca9b42fc308bc239"}, + {file = "propcache-0.4.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e153e9cd40cc8945138822807139367f256f89c6810c2634a4f6902b52d3b4e2"}, + {file = "propcache-0.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:cd547953428f7abb73c5ad82cbb32109566204260d98e41e5dfdc682eb7f8403"}, + {file = "propcache-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f048da1b4f243fc44f205dfd320933a951b8d89e0afd4c7cacc762a8b9165207"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ec17c65562a827bba85e3872ead335f95405ea1674860d96483a02f5c698fa72"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:405aac25c6394ef275dee4c709be43745d36674b223ba4eb7144bf4d691b7367"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0013cb6f8dde4b2a2f66903b8ba740bdfe378c943c4377a200551ceb27f379e4"}, + {file = "propcache-0.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15932ab57837c3368b024473a525e25d316d8353016e7cc0e5ba9eb343fbb1cf"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:031dce78b9dc099f4c29785d9cf5577a3faf9ebf74ecbd3c856a7b92768c3df3"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:ab08df6c9a035bee56e31af99be621526bd237bea9f32def431c656b29e41778"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:4d7af63f9f93fe593afbf104c21b3b15868efb2c21d07d8732c0c4287e66b6a6"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:cfc27c945f422e8b5071b6e93169679e4eb5bf73bbcbf1ba3ae3a83d2f78ebd9"}, + {file = "propcache-0.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:35c3277624a080cc6ec6f847cbbbb5b49affa3598c4535a0a4682a697aaa5c75"}, + {file = "propcache-0.4.1-cp312-cp312-win32.whl", hash = "sha256:671538c2262dadb5ba6395e26c1731e1d52534bfe9ae56d0b5573ce539266aa8"}, + {file = "propcache-0.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:cb2d222e72399fcf5890d1d5cc1060857b9b236adff2792ff48ca2dfd46c81db"}, + {file = "propcache-0.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:204483131fb222bdaaeeea9f9e6c6ed0cac32731f75dfc1d4a567fc1926477c1"}, + {file = "propcache-0.4.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:43eedf29202c08550aac1d14e0ee619b0430aaef78f85864c1a892294fbc28cf"}, + {file = "propcache-0.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:d62cdfcfd89ccb8de04e0eda998535c406bf5e060ffd56be6c586cbcc05b3311"}, + {file = "propcache-0.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:cae65ad55793da34db5f54e4029b89d3b9b9490d8abe1b4c7ab5d4b8ec7ebf74"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:333ddb9031d2704a301ee3e506dc46b1fe5f294ec198ed6435ad5b6a085facfe"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:fd0858c20f078a32cf55f7e81473d96dcf3b93fd2ccdb3d40fdf54b8573df3af"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:678ae89ebc632c5c204c794f8dab2837c5f159aeb59e6ed0539500400577298c"}, + {file = "propcache-0.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d472aeb4fbf9865e0c6d622d7f4d54a4e101a89715d8904282bb5f9a2f476c3f"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d3df5fa7e36b3225954fba85589da77a0fe6a53e3976de39caf04a0db4c36f1"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:ee17f18d2498f2673e432faaa71698032b0127ebf23ae5974eeaf806c279df24"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:580e97762b950f993ae618e167e7be9256b8353c2dcd8b99ec100eb50f5286aa"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:501d20b891688eb8e7aa903021f0b72d5a55db40ffaab27edefd1027caaafa61"}, + {file = "propcache-0.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9a0bd56e5b100aef69bd8562b74b46254e7c8812918d3baa700c8a8009b0af66"}, + {file = "propcache-0.4.1-cp313-cp313-win32.whl", hash = "sha256:bcc9aaa5d80322bc2fb24bb7accb4a30f81e90ab8d6ba187aec0744bc302ad81"}, + {file = "propcache-0.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:381914df18634f5494334d201e98245c0596067504b9372d8cf93f4bb23e025e"}, + {file = "propcache-0.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:8873eb4460fd55333ea49b7d189749ecf6e55bf85080f11b1c4530ed3034cba1"}, + {file = "propcache-0.4.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:92d1935ee1f8d7442da9c0c4fa7ac20d07e94064184811b685f5c4fada64553b"}, + {file = "propcache-0.4.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:473c61b39e1460d386479b9b2f337da492042447c9b685f28be4f74d3529e566"}, + {file = "propcache-0.4.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:c0ef0aaafc66fbd87842a3fe3902fd889825646bc21149eafe47be6072725835"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f95393b4d66bfae908c3ca8d169d5f79cd65636ae15b5e7a4f6e67af675adb0e"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c07fda85708bc48578467e85099645167a955ba093be0a2dcba962195676e859"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:af223b406d6d000830c6f65f1e6431783fc3f713ba3e6cc8c024d5ee96170a4b"}, + {file = "propcache-0.4.1-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a78372c932c90ee474559c5ddfffd718238e8673c340dc21fe45c5b8b54559a0"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:564d9f0d4d9509e1a870c920a89b2fec951b44bf5ba7d537a9e7c1ccec2c18af"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:17612831fda0138059cc5546f4d12a2aacfb9e47068c06af35c400ba58ba7393"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:41a89040cb10bd345b3c1a873b2bf36413d48da1def52f268a055f7398514874"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:e35b88984e7fa64aacecea39236cee32dd9bd8c55f57ba8a75cf2399553f9bd7"}, + {file = "propcache-0.4.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6f8b465489f927b0df505cbe26ffbeed4d6d8a2bbc61ce90eb074ff129ef0ab1"}, + {file = "propcache-0.4.1-cp313-cp313t-win32.whl", hash = "sha256:2ad890caa1d928c7c2965b48f3a3815c853180831d0e5503d35cf00c472f4717"}, + {file = "propcache-0.4.1-cp313-cp313t-win_amd64.whl", hash = "sha256:f7ee0e597f495cf415bcbd3da3caa3bd7e816b74d0d52b8145954c5e6fd3ff37"}, + {file = "propcache-0.4.1-cp313-cp313t-win_arm64.whl", hash = "sha256:929d7cbe1f01bb7baffb33dc14eb5691c95831450a26354cd210a8155170c93a"}, + {file = "propcache-0.4.1-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3f7124c9d820ba5548d431afb4632301acf965db49e666aa21c305cbe8c6de12"}, + {file = "propcache-0.4.1-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:c0d4b719b7da33599dfe3b22d3db1ef789210a0597bc650b7cee9c77c2be8c5c"}, + {file = "propcache-0.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:9f302f4783709a78240ebc311b793f123328716a60911d667e0c036bc5dcbded"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c80ee5802e3fb9ea37938e7eecc307fb984837091d5fd262bb37238b1ae97641"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ed5a841e8bb29a55fb8159ed526b26adc5bdd7e8bd7bf793ce647cb08656cdf4"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:55c72fd6ea2da4c318e74ffdf93c4fe4e926051133657459131a95c846d16d44"}, + {file = "propcache-0.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8326e144341460402713f91df60ade3c999d601e7eb5ff8f6f7862d54de0610d"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:060b16ae65bc098da7f6d25bf359f1f31f688384858204fe5d652979e0015e5b"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:89eb3fa9524f7bec9de6e83cf3faed9d79bffa560672c118a96a171a6f55831e"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:dee69d7015dc235f526fe80a9c90d65eb0039103fe565776250881731f06349f"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:5558992a00dfd54ccbc64a32726a3357ec93825a418a401f5cc67df0ac5d9e49"}, + {file = "propcache-0.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c9b822a577f560fbd9554812526831712c1436d2c046cedee4c3796d3543b144"}, + {file = "propcache-0.4.1-cp314-cp314-win32.whl", hash = "sha256:ab4c29b49d560fe48b696cdcb127dd36e0bc2472548f3bf56cc5cb3da2b2984f"}, + {file = "propcache-0.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:5a103c3eb905fcea0ab98be99c3a9a5ab2de60228aa5aceedc614c0281cf6153"}, + {file = "propcache-0.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:74c1fb26515153e482e00177a1ad654721bf9207da8a494a0c05e797ad27b992"}, + {file = "propcache-0.4.1-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:824e908bce90fb2743bd6b59db36eb4f45cd350a39637c9f73b1c1ea66f5b75f"}, + {file = "propcache-0.4.1-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:c2b5e7db5328427c57c8e8831abda175421b709672f6cfc3d630c3b7e2146393"}, + {file = "propcache-0.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6f6ff873ed40292cd4969ef5310179afd5db59fdf055897e282485043fc80ad0"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49a2dc67c154db2c1463013594c458881a069fcf98940e61a0569016a583020a"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:005f08e6a0529984491e37d8dbc3dd86f84bd78a8ceb5fa9a021f4c48d4984be"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5c3310452e0d31390da9035c348633b43d7e7feb2e37be252be6da45abd1abcc"}, + {file = "propcache-0.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c3c70630930447f9ef1caac7728c8ad1c56bc5015338b20fed0d08ea2480b3a"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8e57061305815dfc910a3634dcf584f08168a8836e6999983569f51a8544cd89"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:521a463429ef54143092c11a77e04056dd00636f72e8c45b70aaa3140d639726"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:120c964da3fdc75e3731aa392527136d4ad35868cc556fd09bb6d09172d9a367"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:d8f353eb14ee3441ee844ade4277d560cdd68288838673273b978e3d6d2c8f36"}, + {file = "propcache-0.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ab2943be7c652f09638800905ee1bab2c544e537edb57d527997a24c13dc1455"}, + {file = "propcache-0.4.1-cp314-cp314t-win32.whl", hash = "sha256:05674a162469f31358c30bcaa8883cb7829fa3110bf9c0991fe27d7896c42d85"}, + {file = "propcache-0.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:990f6b3e2a27d683cb7602ed6c86f15ee6b43b1194736f9baaeb93d0016633b1"}, + {file = "propcache-0.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ecef2343af4cc68e05131e45024ba34f6095821988a9d0a02aa7c73fcc448aa9"}, + {file = "propcache-0.4.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:3d233076ccf9e450c8b3bc6720af226b898ef5d051a2d145f7d765e6e9f9bcff"}, + {file = "propcache-0.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:357f5bb5c377a82e105e44bd3d52ba22b616f7b9773714bff93573988ef0a5fb"}, + {file = "propcache-0.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:cbc3b6dfc728105b2a57c06791eb07a94229202ea75c59db644d7d496b698cac"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:182b51b421f0501952d938dc0b0eb45246a5b5153c50d42b495ad5fb7517c888"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4b536b39c5199b96fc6245eb5fb796c497381d3942f169e44e8e392b29c9ebcc"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:db65d2af507bbfbdcedb254a11149f894169d90488dd3e7190f7cdcb2d6cd57a"}, + {file = "propcache-0.4.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fd2dbc472da1f772a4dae4fa24be938a6c544671a912e30529984dd80400cd88"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:daede9cd44e0f8bdd9e6cc9a607fc81feb80fae7a5fc6cecaff0e0bb32e42d00"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:71b749281b816793678ae7f3d0d84bd36e694953822eaad408d682efc5ca18e0"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:0002004213ee1f36cfb3f9a42b5066100c44276b9b72b4e1504cddd3d692e86e"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:fe49d0a85038f36ba9e3ffafa1103e61170b28e95b16622e11be0a0ea07c6781"}, + {file = "propcache-0.4.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:99d43339c83aaf4d32bda60928231848eee470c6bda8d02599cc4cebe872d183"}, + {file = "propcache-0.4.1-cp39-cp39-win32.whl", hash = "sha256:a129e76735bc792794d5177069691c3217898b9f5cee2b2661471e52ffe13f19"}, + {file = "propcache-0.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:948dab269721ae9a87fd16c514a0a2c2a1bdb23a9a61b969b0f9d9ee2968546f"}, + {file = "propcache-0.4.1-cp39-cp39-win_arm64.whl", hash = "sha256:5fd37c406dd6dc85aa743e214cef35dc54bbdd1419baac4f6ae5e5b1a2976938"}, + {file = "propcache-0.4.1-py3-none-any.whl", hash = "sha256:af2a6052aeb6cf17d3e46ee169099044fd8224cbaf75c76a2ef596e8163e2237"}, + {file = "propcache-0.4.1.tar.gz", hash = "sha256:f48107a8c637e80362555f37ecf49abe20370e557cc4ab374f04ec4423c97c3d"}, +] + +[[package]] +name = "pytokens" +version = "0.4.1" +description = "A Fast, spec compliant Python 3.14+ tokenizer that runs on older Pythons." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "pytokens-0.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2a44ed93ea23415c54f3face3b65ef2b844d96aeb3455b8a69b3df6beab6acc5"}, + {file = "pytokens-0.4.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:add8bf86b71a5d9fb5b89f023a80b791e04fba57960aa790cc6125f7f1d39dfe"}, + {file = "pytokens-0.4.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:670d286910b531c7b7e3c0b453fd8156f250adb140146d234a82219459b9640c"}, + {file = "pytokens-0.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:4e691d7f5186bd2842c14813f79f8884bb03f5995f0575272009982c5ac6c0f7"}, + {file = "pytokens-0.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:27b83ad28825978742beef057bfe406ad6ed524b2d28c252c5de7b4a6dd48fa2"}, + {file = "pytokens-0.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d70e77c55ae8380c91c0c18dea05951482e263982911fc7410b1ffd1dadd3440"}, + {file = "pytokens-0.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a58d057208cb9075c144950d789511220b07636dd2e4708d5645d24de666bdc"}, + {file = "pytokens-0.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b49750419d300e2b5a3813cf229d4e5a4c728dae470bcc89867a9ad6f25a722d"}, + {file = "pytokens-0.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d9907d61f15bf7261d7e775bd5d7ee4d2930e04424bab1972591918497623a16"}, + {file = "pytokens-0.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:ee44d0f85b803321710f9239f335aafe16553b39106384cef8e6de40cb4ef2f6"}, + {file = "pytokens-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:140709331e846b728475786df8aeb27d24f48cbcf7bcd449f8de75cae7a45083"}, + {file = "pytokens-0.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d6c4268598f762bc8e91f5dbf2ab2f61f7b95bdc07953b602db879b3c8c18e1"}, + {file = "pytokens-0.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:24afde1f53d95348b5a0eb19488661147285ca4dd7ed752bbc3e1c6242a304d1"}, + {file = "pytokens-0.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ad948d085ed6c16413eb5fec6b3e02fa00dc29a2534f088d3302c47eb59adf9"}, + {file = "pytokens-0.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:3f901fe783e06e48e8cbdc82d631fca8f118333798193e026a50ce1b3757ea68"}, + {file = "pytokens-0.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8bdb9d0ce90cbf99c525e75a2fa415144fd570a1ba987380190e8b786bc6ef9b"}, + {file = "pytokens-0.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5502408cab1cb18e128570f8d598981c68a50d0cbd7c61312a90507cd3a1276f"}, + {file = "pytokens-0.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29d1d8fb1030af4d231789959f21821ab6325e463f0503a61d204343c9b355d1"}, + {file = "pytokens-0.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:970b08dd6b86058b6dc07efe9e98414f5102974716232d10f32ff39701e841c4"}, + {file = "pytokens-0.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:9bd7d7f544d362576be74f9d5901a22f317efc20046efe2034dced238cbbfe78"}, + {file = "pytokens-0.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:4a14d5f5fc78ce85e426aa159489e2d5961acf0e47575e08f35584009178e321"}, + {file = "pytokens-0.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97f50fd18543be72da51dd505e2ed20d2228c74e0464e4262e4899797803d7fa"}, + {file = "pytokens-0.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:dc74c035f9bfca0255c1af77ddd2d6ae8419012805453e4b0e7513e17904545d"}, + {file = "pytokens-0.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f66a6bbe741bd431f6d741e617e0f39ec7257ca1f89089593479347cc4d13324"}, + {file = "pytokens-0.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:b35d7e5ad269804f6697727702da3c517bb8a5228afa450ab0fa787732055fc9"}, + {file = "pytokens-0.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8fcb9ba3709ff77e77f1c7022ff11d13553f3c30299a9fe246a166903e9091eb"}, + {file = "pytokens-0.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:79fc6b8699564e1f9b521582c35435f1bd32dd06822322ec44afdeba666d8cb3"}, + {file = "pytokens-0.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d31b97b3de0f61571a124a00ffe9a81fb9939146c122c11060725bd5aea79975"}, + {file = "pytokens-0.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:967cf6e3fd4adf7de8fc73cd3043754ae79c36475c1c11d514fc72cf5490094a"}, + {file = "pytokens-0.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:584c80c24b078eec1e227079d56dc22ff755e0ba8654d8383b2c549107528918"}, + {file = "pytokens-0.4.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:da5baeaf7116dced9c6bb76dc31ba04a2dc3695f3d9f74741d7910122b456edc"}, + {file = "pytokens-0.4.1-cp38-cp38-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:11edda0942da80ff58c4408407616a310adecae1ddd22eef8c692fe266fa5009"}, + {file = "pytokens-0.4.1-cp38-cp38-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0fc71786e629cef478cbf29d7ea1923299181d0699dbe7c3c0f4a583811d9fc1"}, + {file = "pytokens-0.4.1-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:dcafc12c30dbaf1e2af0490978352e0c4041a7cde31f4f81435c2a5e8b9cabb6"}, + {file = "pytokens-0.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:42f144f3aafa5d92bad964d471a581651e28b24434d184871bd02e3a0d956037"}, + {file = "pytokens-0.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:34bcc734bd2f2d5fe3b34e7b3c0116bfb2397f2d9666139988e7a3eb5f7400e3"}, + {file = "pytokens-0.4.1-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:941d4343bf27b605e9213b26bfa1c4bf197c9c599a9627eb7305b0defcfe40c1"}, + {file = "pytokens-0.4.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3ad72b851e781478366288743198101e5eb34a414f1d5627cdd585ca3b25f1db"}, + {file = "pytokens-0.4.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:682fa37ff4d8e95f7df6fe6fe6a431e8ed8e788023c6bcc0f0880a12eab80ad1"}, + {file = "pytokens-0.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:30f51edd9bb7f85c748979384165601d028b84f7bd13fe14d3e065304093916a"}, + {file = "pytokens-0.4.1-py3-none-any.whl", hash = "sha256:26cef14744a8385f35d0e095dc8b3a7583f6c953c2e3d269c7f82484bf5ad2de"}, + {file = "pytokens-0.4.1.tar.gz", hash = "sha256:292052fe80923aae2260c073f822ceba21f3872ced9a68bb7953b348e561179a"}, +] + +[package.extras] +dev = ["black", "build", "mypy", "pytest", "pytest-cov", "setuptools", "tox", "twine", "wheel"] + +[[package]] +name = "requests" +version = "2.32.5" +description = "Python HTTP for Humans." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6"}, + {file = "requests-2.32.5.tar.gz", hash = "sha256:dbba0bac56e100853db0ea71b82b4dfd5fe2bf6d3754a8893c3af500cec7d7cf"}, +] + +[package.dependencies] +certifi = ">=2017.4.17" +charset_normalizer = ">=2,<4" +idna = ">=2.5,<4" +urllib3 = ">=1.21.1,<3" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] + +[[package]] +name = "tomli" +version = "2.4.0" +description = "A lil' TOML parser" +optional = false +python-versions = ">=3.8" +groups = ["dev"] +markers = "python_version < \"3.11\"" +files = [ + {file = "tomli-2.4.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b5ef256a3fd497d4973c11bf142e9ed78b150d36f5773f1ca6088c230ffc5867"}, + {file = "tomli-2.4.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5572e41282d5268eb09a697c89a7bee84fae66511f87533a6f88bd2f7b652da9"}, + {file = "tomli-2.4.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:551e321c6ba03b55676970b47cb1b73f14a0a4dce6a3e1a9458fd6d921d72e95"}, + {file = "tomli-2.4.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e3f639a7a8f10069d0e15408c0b96a2a828cfdec6fca05296ebcdcc28ca7c76"}, + {file = "tomli-2.4.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1b168f2731796b045128c45982d3a4874057626da0e2ef1fdd722848b741361d"}, + {file = "tomli-2.4.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:133e93646ec4300d651839d382d63edff11d8978be23da4cc106f5a18b7d0576"}, + {file = "tomli-2.4.0-cp311-cp311-win32.whl", hash = "sha256:b6c78bdf37764092d369722d9946cb65b8767bfa4110f902a1b2542d8d173c8a"}, + {file = "tomli-2.4.0-cp311-cp311-win_amd64.whl", hash = "sha256:d3d1654e11d724760cdb37a3d7691f0be9db5fbdaef59c9f532aabf87006dbaa"}, + {file = "tomli-2.4.0-cp311-cp311-win_arm64.whl", hash = "sha256:cae9c19ed12d4e8f3ebf46d1a75090e4c0dc16271c5bce1c833ac168f08fb614"}, + {file = "tomli-2.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:920b1de295e72887bafa3ad9f7a792f811847d57ea6b1215154030cf131f16b1"}, + {file = "tomli-2.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7d6d9a4aee98fac3eab4952ad1d73aee87359452d1c086b5ceb43ed02ddb16b8"}, + {file = "tomli-2.4.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:36b9d05b51e65b254ea6c2585b59d2c4cb91c8a3d91d0ed0f17591a29aaea54a"}, + {file = "tomli-2.4.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c8a885b370751837c029ef9bc014f27d80840e48bac415f3412e6593bbc18c1"}, + {file = "tomli-2.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8768715ffc41f0008abe25d808c20c3d990f42b6e2e58305d5da280ae7d1fa3b"}, + {file = "tomli-2.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7b438885858efd5be02a9a133caf5812b8776ee0c969fea02c45e8e3f296ba51"}, + {file = "tomli-2.4.0-cp312-cp312-win32.whl", hash = "sha256:0408e3de5ec77cc7f81960c362543cbbd91ef883e3138e81b729fc3eea5b9729"}, + {file = "tomli-2.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:685306e2cc7da35be4ee914fd34ab801a6acacb061b6a7abca922aaf9ad368da"}, + {file = "tomli-2.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:5aa48d7c2356055feef06a43611fc401a07337d5b006be13a30f6c58f869e3c3"}, + {file = "tomli-2.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:84d081fbc252d1b6a982e1870660e7330fb8f90f676f6e78b052ad4e64714bf0"}, + {file = "tomli-2.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9a08144fa4cba33db5255f9b74f0b89888622109bd2776148f2597447f92a94e"}, + {file = "tomli-2.4.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c73add4bb52a206fd0c0723432db123c0c75c280cbd67174dd9d2db228ebb1b4"}, + {file = "tomli-2.4.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1fb2945cbe303b1419e2706e711b7113da57b7db31ee378d08712d678a34e51e"}, + {file = "tomli-2.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:bbb1b10aa643d973366dc2cb1ad94f99c1726a02343d43cbc011edbfac579e7c"}, + {file = "tomli-2.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4cbcb367d44a1f0c2be408758b43e1ffb5308abe0ea222897d6bfc8e8281ef2f"}, + {file = "tomli-2.4.0-cp313-cp313-win32.whl", hash = "sha256:7d49c66a7d5e56ac959cb6fc583aff0651094ec071ba9ad43df785abc2320d86"}, + {file = "tomli-2.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:3cf226acb51d8f1c394c1b310e0e0e61fecdd7adcb78d01e294ac297dd2e7f87"}, + {file = "tomli-2.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:d20b797a5c1ad80c516e41bc1fb0443ddb5006e9aaa7bda2d71978346aeb9132"}, + {file = "tomli-2.4.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:26ab906a1eb794cd4e103691daa23d95c6919cc2fa9160000ac02370cc9dd3f6"}, + {file = "tomli-2.4.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:20cedb4ee43278bc4f2fee6cb50daec836959aadaf948db5172e776dd3d993fc"}, + {file = "tomli-2.4.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:39b0b5d1b6dd03684b3fb276407ebed7090bbec989fa55838c98560c01113b66"}, + {file = "tomli-2.4.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a26d7ff68dfdb9f87a016ecfd1e1c2bacbe3108f4e0f8bcd2228ef9a766c787d"}, + {file = "tomli-2.4.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:20ffd184fb1df76a66e34bd1b36b4a4641bd2b82954befa32fe8163e79f1a702"}, + {file = "tomli-2.4.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:75c2f8bbddf170e8effc98f5e9084a8751f8174ea6ccf4fca5398436e0320bc8"}, + {file = "tomli-2.4.0-cp314-cp314-win32.whl", hash = "sha256:31d556d079d72db7c584c0627ff3a24c5d3fb4f730221d3444f3efb1b2514776"}, + {file = "tomli-2.4.0-cp314-cp314-win_amd64.whl", hash = "sha256:43e685b9b2341681907759cf3a04e14d7104b3580f808cfde1dfdb60ada85475"}, + {file = "tomli-2.4.0-cp314-cp314-win_arm64.whl", hash = "sha256:3d895d56bd3f82ddd6faaff993c275efc2ff38e52322ea264122d72729dca2b2"}, + {file = "tomli-2.4.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:5b5807f3999fb66776dbce568cc9a828544244a8eb84b84b9bafc080c99597b9"}, + {file = "tomli-2.4.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c084ad935abe686bd9c898e62a02a19abfc9760b5a79bc29644463eaf2840cb0"}, + {file = "tomli-2.4.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0f2e3955efea4d1cfbcb87bc321e00dc08d2bcb737fd1d5e398af111d86db5df"}, + {file = "tomli-2.4.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e0fe8a0b8312acf3a88077a0802565cb09ee34107813bba1c7cd591fa6cfc8d"}, + {file = "tomli-2.4.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:413540dce94673591859c4c6f794dfeaa845e98bf35d72ed59636f869ef9f86f"}, + {file = "tomli-2.4.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0dc56fef0e2c1c470aeac5b6ca8cc7b640bb93e92d9803ddaf9ea03e198f5b0b"}, + {file = "tomli-2.4.0-cp314-cp314t-win32.whl", hash = "sha256:d878f2a6707cc9d53a1be1414bbb419e629c3d6e67f69230217bb663e76b5087"}, + {file = "tomli-2.4.0-cp314-cp314t-win_amd64.whl", hash = "sha256:2add28aacc7425117ff6364fe9e06a183bb0251b03f986df0e78e974047571fd"}, + {file = "tomli-2.4.0-cp314-cp314t-win_arm64.whl", hash = "sha256:2b1e3b80e1d5e52e40e9b924ec43d81570f0e7d09d11081b797bc4692765a3d4"}, + {file = "tomli-2.4.0-py3-none-any.whl", hash = "sha256:1f776e7d669ebceb01dee46484485f43a4048746235e683bcdffacdf1fb4785a"}, + {file = "tomli-2.4.0.tar.gz", hash = "sha256:aa89c3f6c277dd275d8e243ad24f3b5e701491a860d5121f2cdd399fbb31fc9c"}, +] + +[[package]] +name = "typing-extensions" +version = "4.15.0" +description = "Backported and Experimental Type Hints for Python 3.9+" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548"}, + {file = "typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466"}, +] + +[[package]] +name = "urllib3" +version = "2.6.3" +description = "HTTP library with thread-safe connection pooling, file post, and more." +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4"}, + {file = "urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed"}, +] + +[package.extras] +brotli = ["brotli (>=1.2.0) ; platform_python_implementation == \"CPython\"", "brotlicffi (>=1.2.0.0) ; platform_python_implementation != \"CPython\""] +h2 = ["h2 (>=4,<5)"] +socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] +zstd = ["backports-zstd (>=1.0.0) ; python_version < \"3.14\""] + +[[package]] +name = "yarl" +version = "1.22.0" +description = "Yet another URL library" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "yarl-1.22.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c7bd6683587567e5a49ee6e336e0612bec8329be1b7d4c8af5687dcdeb67ee1e"}, + {file = "yarl-1.22.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:5cdac20da754f3a723cceea5b3448e1a2074866406adeb4ef35b469d089adb8f"}, + {file = "yarl-1.22.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:07a524d84df0c10f41e3ee918846e1974aba4ec017f990dc735aad487a0bdfdf"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e1b329cb8146d7b736677a2440e422eadd775d1806a81db2d4cded80a48efc1a"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:75976c6945d85dbb9ee6308cd7ff7b1fb9409380c82d6119bd778d8fcfe2931c"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:80ddf7a5f8c86cb3eb4bc9028b07bbbf1f08a96c5c0bc1244be5e8fefcb94147"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d332fc2e3c94dad927f2112395772a4e4fedbcf8f80efc21ed7cdfae4d574fdb"}, + {file = "yarl-1.22.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0cf71bf877efeac18b38d3930594c0948c82b64547c1cf420ba48722fe5509f6"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:663e1cadaddae26be034a6ab6072449a8426ddb03d500f43daf952b74553bba0"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_armv7l.whl", hash = "sha256:6dcbb0829c671f305be48a7227918cfcd11276c2d637a8033a99a02b67bf9eda"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:f0d97c18dfd9a9af4490631905a3f131a8e4c9e80a39353919e2cfed8f00aedc"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:437840083abe022c978470b942ff832c3940b2ad3734d424b7eaffcd07f76737"}, + {file = "yarl-1.22.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:a899cbd98dce6f5d8de1aad31cb712ec0a530abc0a86bd6edaa47c1090138467"}, + {file = "yarl-1.22.0-cp310-cp310-win32.whl", hash = "sha256:595697f68bd1f0c1c159fcb97b661fc9c3f5db46498043555d04805430e79bea"}, + {file = "yarl-1.22.0-cp310-cp310-win_amd64.whl", hash = "sha256:cb95a9b1adaa48e41815a55ae740cfda005758104049a640a398120bf02515ca"}, + {file = "yarl-1.22.0-cp310-cp310-win_arm64.whl", hash = "sha256:b85b982afde6df99ecc996990d4ad7ccbdbb70e2a4ba4de0aecde5922ba98a0b"}, + {file = "yarl-1.22.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:1ab72135b1f2db3fed3997d7e7dc1b80573c67138023852b6efb336a5eae6511"}, + {file = "yarl-1.22.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:669930400e375570189492dc8d8341301578e8493aec04aebc20d4717f899dd6"}, + {file = "yarl-1.22.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:792a2af6d58177ef7c19cbf0097aba92ca1b9cb3ffdd9c7470e156c8f9b5e028"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3ea66b1c11c9150f1372f69afb6b8116f2dd7286f38e14ea71a44eee9ec51b9d"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3e2daa88dc91870215961e96a039ec73e4937da13cf77ce17f9cad0c18df3503"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ba440ae430c00eee41509353628600212112cd5018d5def7e9b05ea7ac34eb65"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e6438cc8f23a9c1478633d216b16104a586b9761db62bfacb6425bac0a36679e"}, + {file = "yarl-1.22.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4c52a6e78aef5cf47a98ef8e934755abf53953379b7d53e68b15ff4420e6683d"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:3b06bcadaac49c70f4c88af4ffcfbe3dc155aab3163e75777818092478bcbbe7"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:6944b2dc72c4d7f7052683487e3677456050ff77fcf5e6204e98caf785ad1967"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d5372ca1df0f91a86b047d1277c2aaf1edb32d78bbcefffc81b40ffd18f027ed"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:51af598701f5299012b8416486b40fceef8c26fc87dc6d7d1f6fc30609ea0aa6"}, + {file = "yarl-1.22.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b266bd01fedeffeeac01a79ae181719ff848a5a13ce10075adbefc8f1daee70e"}, + {file = "yarl-1.22.0-cp311-cp311-win32.whl", hash = "sha256:a9b1ba5610a4e20f655258d5a1fdc7ebe3d837bb0e45b581398b99eb98b1f5ca"}, + {file = "yarl-1.22.0-cp311-cp311-win_amd64.whl", hash = "sha256:078278b9b0b11568937d9509b589ee83ef98ed6d561dfe2020e24a9fd08eaa2b"}, + {file = "yarl-1.22.0-cp311-cp311-win_arm64.whl", hash = "sha256:b6a6f620cfe13ccec221fa312139135166e47ae169f8253f72a0abc0dae94376"}, + {file = "yarl-1.22.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e340382d1afa5d32b892b3ff062436d592ec3d692aeea3bef3a5cfe11bbf8c6f"}, + {file = "yarl-1.22.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f1e09112a2c31ffe8d80be1b0988fa6a18c5d5cad92a9ffbb1c04c91bfe52ad2"}, + {file = "yarl-1.22.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:939fe60db294c786f6b7c2d2e121576628468f65453d86b0fe36cb52f987bd74"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e1651bf8e0398574646744c1885a41198eba53dc8a9312b954073f845c90a8df"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b8a0588521a26bf92a57a1705b77b8b59044cdceccac7151bd8d229e66b8dedb"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:42188e6a615c1a75bcaa6e150c3fe8f3e8680471a6b10150c5f7e83f47cc34d2"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f6d2cb59377d99718913ad9a151030d6f83ef420a2b8f521d94609ecc106ee82"}, + {file = "yarl-1.22.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50678a3b71c751d58d7908edc96d332af328839eea883bb554a43f539101277a"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1e8fbaa7cec507aa24ea27a01456e8dd4b6fab829059b69844bd348f2d467124"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:433885ab5431bc3d3d4f2f9bd15bfa1614c522b0f1405d62c4f926ccd69d04fa"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b790b39c7e9a4192dc2e201a282109ed2985a1ddbd5ac08dc56d0e121400a8f7"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:31f0b53913220599446872d757257be5898019c85e7971599065bc55065dc99d"}, + {file = "yarl-1.22.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a49370e8f711daec68d09b821a34e1167792ee2d24d405cbc2387be4f158b520"}, + {file = "yarl-1.22.0-cp312-cp312-win32.whl", hash = "sha256:70dfd4f241c04bd9239d53b17f11e6ab672b9f1420364af63e8531198e3f5fe8"}, + {file = "yarl-1.22.0-cp312-cp312-win_amd64.whl", hash = "sha256:8884d8b332a5e9b88e23f60bb166890009429391864c685e17bd73a9eda9105c"}, + {file = "yarl-1.22.0-cp312-cp312-win_arm64.whl", hash = "sha256:ea70f61a47f3cc93bdf8b2f368ed359ef02a01ca6393916bc8ff877427181e74"}, + {file = "yarl-1.22.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8dee9c25c74997f6a750cd317b8ca63545169c098faee42c84aa5e506c819b53"}, + {file = "yarl-1.22.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:01e73b85a5434f89fc4fe27dcda2aff08ddf35e4d47bbbea3bdcd25321af538a"}, + {file = "yarl-1.22.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:22965c2af250d20c873cdbee8ff958fb809940aeb2e74ba5f20aaf6b7ac8c70c"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4f15793aa49793ec8d1c708ab7f9eded1aa72edc5174cae703651555ed1b601"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e5542339dcf2747135c5c85f68680353d5cb9ffd741c0f2e8d832d054d41f35a"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5c401e05ad47a75869c3ab3e35137f8468b846770587e70d71e11de797d113df"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:243dda95d901c733f5b59214d28b0120893d91777cb8aa043e6ef059d3cddfe2"}, + {file = "yarl-1.22.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bec03d0d388060058f5d291a813f21c011041938a441c593374da6077fe21b1b"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b0748275abb8c1e1e09301ee3cf90c8a99678a4e92e4373705f2a2570d581273"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:47fdb18187e2a4e18fda2c25c05d8251a9e4a521edaed757fef033e7d8498d9a"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c7044802eec4524fde550afc28edda0dd5784c4c45f0be151a2d3ba017daca7d"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:139718f35149ff544caba20fce6e8a2f71f1e39b92c700d8438a0b1d2a631a02"}, + {file = "yarl-1.22.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e1b51bebd221006d3d2f95fbe124b22b247136647ae5dcc8c7acafba66e5ee67"}, + {file = "yarl-1.22.0-cp313-cp313-win32.whl", hash = "sha256:d3e32536234a95f513bd374e93d717cf6b2231a791758de6c509e3653f234c95"}, + {file = "yarl-1.22.0-cp313-cp313-win_amd64.whl", hash = "sha256:47743b82b76d89a1d20b83e60d5c20314cbd5ba2befc9cda8f28300c4a08ed4d"}, + {file = "yarl-1.22.0-cp313-cp313-win_arm64.whl", hash = "sha256:5d0fcda9608875f7d052eff120c7a5da474a6796fe4d83e152e0e4d42f6d1a9b"}, + {file = "yarl-1.22.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:719ae08b6972befcba4310e49edb1161a88cdd331e3a694b84466bd938a6ab10"}, + {file = "yarl-1.22.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:47d8a5c446df1c4db9d21b49619ffdba90e77c89ec6e283f453856c74b50b9e3"}, + {file = "yarl-1.22.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:cfebc0ac8333520d2d0423cbbe43ae43c8838862ddb898f5ca68565e395516e9"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4398557cbf484207df000309235979c79c4356518fd5c99158c7d38203c4da4f"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2ca6fd72a8cd803be290d42f2dec5cdcd5299eeb93c2d929bf060ad9efaf5de0"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ca1f59c4e1ab6e72f0a23c13fca5430f889634166be85dbf1013683e49e3278e"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6c5010a52015e7c70f86eb967db0f37f3c8bd503a695a49f8d45700144667708"}, + {file = "yarl-1.22.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d7672ecf7557476642c88497c2f8d8542f8e36596e928e9bcba0e42e1e7d71f"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:3b7c88eeef021579d600e50363e0b6ee4f7f6f728cd3486b9d0f3ee7b946398d"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:f4afb5c34f2c6fecdcc182dfcfc6af6cccf1aa923eed4d6a12e9d96904e1a0d8"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:59c189e3e99a59cf8d83cbb31d4db02d66cda5a1a4374e8a012b51255341abf5"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:5a3bf7f62a289fa90f1990422dc8dff5a458469ea71d1624585ec3a4c8d6960f"}, + {file = "yarl-1.22.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:de6b9a04c606978fdfe72666fa216ffcf2d1a9f6a381058d4378f8d7b1e5de62"}, + {file = "yarl-1.22.0-cp313-cp313t-win32.whl", hash = "sha256:1834bb90991cc2999f10f97f5f01317f99b143284766d197e43cd5b45eb18d03"}, + {file = "yarl-1.22.0-cp313-cp313t-win_amd64.whl", hash = "sha256:ff86011bd159a9d2dfc89c34cfd8aff12875980e3bd6a39ff097887520e60249"}, + {file = "yarl-1.22.0-cp313-cp313t-win_arm64.whl", hash = "sha256:7861058d0582b847bc4e3a4a4c46828a410bca738673f35a29ba3ca5db0b473b"}, + {file = "yarl-1.22.0-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:34b36c2c57124530884d89d50ed2c1478697ad7473efd59cfd479945c95650e4"}, + {file = "yarl-1.22.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:0dd9a702591ca2e543631c2a017e4a547e38a5c0f29eece37d9097e04a7ac683"}, + {file = "yarl-1.22.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:594fcab1032e2d2cc3321bb2e51271e7cd2b516c7d9aee780ece81b07ff8244b"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f3d7a87a78d46a2e3d5b72587ac14b4c16952dd0887dbb051451eceac774411e"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:852863707010316c973162e703bddabec35e8757e67fcb8ad58829de1ebc8590"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:131a085a53bfe839a477c0845acf21efc77457ba2bcf5899618136d64f3303a2"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:078a8aefd263f4d4f923a9677b942b445a2be970ca24548a8102689a3a8ab8da"}, + {file = "yarl-1.22.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bca03b91c323036913993ff5c738d0842fc9c60c4648e5c8d98331526df89784"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:68986a61557d37bb90d3051a45b91fa3d5c516d177dfc6dd6f2f436a07ff2b6b"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:4792b262d585ff0dff6bcb787f8492e40698443ec982a3568c2096433660c694"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:ebd4549b108d732dba1d4ace67614b9545b21ece30937a63a65dd34efa19732d"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f87ac53513d22240c7d59203f25cc3beac1e574c6cd681bbfd321987b69f95fd"}, + {file = "yarl-1.22.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:22b029f2881599e2f1b06f8f1db2ee63bd309e2293ba2d566e008ba12778b8da"}, + {file = "yarl-1.22.0-cp314-cp314-win32.whl", hash = "sha256:6a635ea45ba4ea8238463b4f7d0e721bad669f80878b7bfd1f89266e2ae63da2"}, + {file = "yarl-1.22.0-cp314-cp314-win_amd64.whl", hash = "sha256:0d6e6885777af0f110b0e5d7e5dda8b704efed3894da26220b7f3d887b839a79"}, + {file = "yarl-1.22.0-cp314-cp314-win_arm64.whl", hash = "sha256:8218f4e98d3c10d683584cb40f0424f4b9fd6e95610232dd75e13743b070ee33"}, + {file = "yarl-1.22.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:45c2842ff0e0d1b35a6bf1cd6c690939dacb617a70827f715232b2e0494d55d1"}, + {file = "yarl-1.22.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:d947071e6ebcf2e2bee8fce76e10faca8f7a14808ca36a910263acaacef08eca"}, + {file = "yarl-1.22.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:334b8721303e61b00019474cc103bdac3d7b1f65e91f0bfedeec2d56dfe74b53"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e7ce67c34138a058fd092f67d07a72b8e31ff0c9236e751957465a24b28910c"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:d77e1b2c6d04711478cb1c4ab90db07f1609ccf06a287d5607fcd90dc9863acf"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c4647674b6150d2cae088fc07de2738a84b8bcedebef29802cf0b0a82ab6face"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efb07073be061c8f79d03d04139a80ba33cbd390ca8f0297aae9cce6411e4c6b"}, + {file = "yarl-1.22.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e51ac5435758ba97ad69617e13233da53908beccc6cfcd6c34bbed8dcbede486"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:33e32a0dd0c8205efa8e83d04fc9f19313772b78522d1bdc7d9aed706bfd6138"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:bf4a21e58b9cde0e401e683ebd00f6ed30a06d14e93f7c8fd059f8b6e8f87b6a"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:e4b582bab49ac33c8deb97e058cd67c2c50dac0dd134874106d9c774fd272529"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:0b5bcc1a9c4839e7e30b7b30dd47fe5e7e44fb7054ec29b5bb8d526aa1041093"}, + {file = "yarl-1.22.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c0232bce2170103ec23c454e54a57008a9a72b5d1c3105dc2496750da8cfa47c"}, + {file = "yarl-1.22.0-cp314-cp314t-win32.whl", hash = "sha256:8009b3173bcd637be650922ac455946197d858b3630b6d8787aa9e5c4564533e"}, + {file = "yarl-1.22.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9fb17ea16e972c63d25d4a97f016d235c78dd2344820eb35bc034bc32012ee27"}, + {file = "yarl-1.22.0-cp314-cp314t-win_arm64.whl", hash = "sha256:9f6d73c1436b934e3f01df1e1b21ff765cd1d28c77dfb9ace207f746d4610ee1"}, + {file = "yarl-1.22.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:3aa27acb6de7a23785d81557577491f6c38a5209a254d1191519d07d8fe51748"}, + {file = "yarl-1.22.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:af74f05666a5e531289cb1cc9c883d1de2088b8e5b4de48004e5ca8a830ac859"}, + {file = "yarl-1.22.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:62441e55958977b8167b2709c164c91a6363e25da322d87ae6dd9c6019ceecf9"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b580e71cac3f8113d3135888770903eaf2f507e9421e5697d6ee6d8cd1c7f054"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e81fda2fb4a07eda1a2252b216aa0df23ebcd4d584894e9612e80999a78fd95b"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:99b6fc1d55782461b78221e95fc357b47ad98b041e8e20f47c1411d0aacddc60"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:088e4e08f033db4be2ccd1f34cf29fe994772fb54cfe004bbf54db320af56890"}, + {file = "yarl-1.22.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e4e1f6f0b4da23e61188676e3ed027ef0baa833a2e633c29ff8530800edccba"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:84fc3ec96fce86ce5aa305eb4aa9358279d1aa644b71fab7b8ed33fe3ba1a7ca"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_armv7l.whl", hash = "sha256:5dbeefd6ca588b33576a01b0ad58aa934bc1b41ef89dee505bf2932b22ddffba"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:14291620375b1060613f4aab9ebf21850058b6b1b438f386cc814813d901c60b"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:a4fcfc8eb2c34148c118dfa02e6427ca278bfd0f3df7c5f99e33d2c0e81eae3e"}, + {file = "yarl-1.22.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:029866bde8d7b0878b9c160e72305bbf0a7342bcd20b9999381704ae03308dc8"}, + {file = "yarl-1.22.0-cp39-cp39-win32.whl", hash = "sha256:4dcc74149ccc8bba31ce1944acee24813e93cfdee2acda3c172df844948ddf7b"}, + {file = "yarl-1.22.0-cp39-cp39-win_amd64.whl", hash = "sha256:10619d9fdee46d20edc49d3479e2f8269d0779f1b031e6f7c2aa1c76be04b7ed"}, + {file = "yarl-1.22.0-cp39-cp39-win_arm64.whl", hash = "sha256:dd7afd3f8b0bfb4e0d9fc3c31bfe8a4ec7debe124cfd90619305def3c8ca8cd2"}, + {file = "yarl-1.22.0-py3-none-any.whl", hash = "sha256:1380560bdba02b6b6c90de54133c81c9f2a453dee9912fe58c1dcced1edb7cff"}, + {file = "yarl-1.22.0.tar.gz", hash = "sha256:bebf8557577d4401ba8bd9ff33906f1376c877aa78d1fe216ad01b4d6745af71"}, +] + +[package.dependencies] +idna = ">=2.0" +multidict = ">=4.0" +propcache = ">=0.2.1" + +[metadata] +lock-version = "2.1" +python-versions = "^3.9" +content-hash = "3a3d9c63df2cb352fe31576993219c335fd56858ff11bd59a042c99aadf86cd0" diff --git a/api/client/python/pyproject.toml b/api/client/python/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..f98b95207c740879cdbb4e424cfff509f187ea3a --- /dev/null +++ b/api/client/python/pyproject.toml @@ -0,0 +1,37 @@ +[tool.poetry] +name = "openmeter" +version = "0.0.0" +description = "Client for OpenMeter: Real-Time and Scalable Usage Metering" +authors = ["Andras Toth <4157749+tothandras@users.noreply.github.com>"] +license = "Apache-2.0" +readme = "README.md" +repository = "https://github.com/openmeter/openmeter" +homepage = "https://openmeter.io" +keywords = [ + "openmeter", + "api", + "client", + "usage", + "usage-based", + "metering", + "ai", + "aggregation", + "real-time", + "billing", + "cloud", +] + +[tool.poetry.dependencies] +python = "^3.9" +isodate = ">=0.7.2,<0.8.0" +corehttp = { version = ">=1.0.0b7", extras = ["requests", "aiohttp"] } +typing-extensions = ">=4.15.0" +cloudevents = "^1.12.1" +urllib3 = "^2.6.3" + +[tool.poetry.group.dev.dependencies] +black = ">=25.11,<27.0" + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" diff --git a/api/client/python/scripts/release.sh b/api/client/python/scripts/release.sh new file mode 100644 index 0000000000000000000000000000000000000000..74f824210824250e13646a1184feb2b315d994cc --- /dev/null +++ b/api/client/python/scripts/release.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env sh + +set -euo pipefail + +# Determine PY_SDK_RELEASE_VERSION if not provided +if [ -z "${PY_SDK_RELEASE_VERSION:-}" ]; then + # Validate PY_SDK_RELEASE_TAG + if [ -z "${PY_SDK_RELEASE_TAG:-}" ]; then + echo "ERROR: PY_SDK_RELEASE_VERSION or PY_SDK_RELEASE_TAG is required" + exit 1 + fi + + if [ "$PY_SDK_RELEASE_TAG" != "alpha" ]; then + echo "ERROR: PY_SDK_RELEASE_TAG must be 'alpha'" + exit 1 + fi + + LATEST_VERSION=$(curl -s https://pypi.org/pypi/openmeter/json | jq -r '.releases | keys[] | select(test("a[0-9]+"))' | sort -V | tail -1) + if [ -z "$LATEST_VERSION" ]; then + PY_SDK_RELEASE_VERSION="1.0.0a0" + else + BASE_VERSION=$(echo "$LATEST_VERSION" | grep -o '^[0-9]*\.[0-9]*\.[0-9]*') + PRE_NUM=$(echo "$LATEST_VERSION" | grep -o 'a[0-9]*' | grep -o '[0-9]*' || echo "-1") + NEXT_NUM=$((PRE_NUM + 1)) + PY_SDK_RELEASE_VERSION="${BASE_VERSION}a${NEXT_NUM}" + fi + export PY_SDK_RELEASE_VERSION +fi + +# Set COMMIT_SHORT_SHA if not provided +if [ -z "${COMMIT_SHORT_SHA:-}" ]; then + COMMIT_SHORT_SHA=$(git rev-parse --short=12 HEAD) +fi + +# Convert PY_SDK_RELEASE_VERSION to a valid Python version +export PY_SDK_RELEASE_VERSION=$(echo "$PY_SDK_RELEASE_VERSION" | sed -E 's/^v//' | sed -E 's/-alpha\.?/a/; s/-beta\.?/b/;') + +# Update poetry version +poetry version "$PY_SDK_RELEASE_VERSION" + +# Write version and commit files +printf "VERSION = \"%s\"" "$PY_SDK_RELEASE_VERSION" > openmeter/_version.py || true +printf "COMMIT = \"%s\"" "$COMMIT_SHORT_SHA" > openmeter/_commit.py || true + +# Clean dist directory to avoid prompts about existing files +rm -rf dist + +# Publish with poetry +poetry publish --build --no-interaction + +echo "Published Python SDK version $PY_SDK_RELEASE_VERSION" + diff --git a/api/client/web/README.md b/api/client/web/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5800d92068a7f8f7c170a9e753acb1488a8540a5 --- /dev/null +++ b/api/client/web/README.md @@ -0,0 +1,3 @@ +# OpenMeter Web SDK + +Moved to fetch based client in [JavaScript SDK](../javascript) diff --git a/api/codegen.yaml b/api/codegen.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2c32b24deee65bf609c56c98b2799b76c3f282d --- /dev/null +++ b/api/codegen.yaml @@ -0,0 +1,15 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/HEAD/configuration-schema.json +package: api +generate: + chi-server: true + models: true + embedded-spec: true +compatibility: + apply-chi-middleware-first-to-last: true + # See: https://github.com/oapi-codegen/oapi-codegen/issues/778 + disable-required-readonly-as-pointer: true + always-prefix-enum-values: true + preserve-original-operation-id-casing-in-embedded-spec: true +output: ./api.gen.go +output-options: + skip-prune: true diff --git a/api/convert.gen.go b/api/convert.gen.go new file mode 100644 index 0000000000000000000000000000000000000000..0214cf00b6174126dbc4c99b48b1cbdc061de3ea --- /dev/null +++ b/api/convert.gen.go @@ -0,0 +1,17 @@ +// Code generated by github.com/jmattheis/goverter, DO NOT EDIT. +//go:build !goverter + +package api + +func init() { + FromBillingDiscountPercentageToDiscountPercentage = func(source BillingDiscountPercentage) DiscountPercentage { + var apiDiscountPercentage DiscountPercentage + apiDiscountPercentage.Percentage = source.Percentage + return apiDiscountPercentage + } + FromBillingDiscountUsageToDiscountUsage = func(source BillingDiscountUsage) DiscountUsage { + var apiDiscountUsage DiscountUsage + apiDiscountUsage.Quantity = source.Quantity + return apiDiscountUsage + } +} diff --git a/api/convert.go b/api/convert.go new file mode 100644 index 0000000000000000000000000000000000000000..87f05a8175e3446e4959f0da575cde9af03f2b88 --- /dev/null +++ b/api/convert.go @@ -0,0 +1,16 @@ +//go:generate go tool github.com/jmattheis/goverter/cmd/goverter gen ./ + +package api + +// This file contains the conversion functions for the API types. +// This can be used to convert between similar API types, as the oapi-codegen generates +// different types for the same Go struct. + +// goverter:variables +// goverter:skipCopySameType +// goverter:output:file ./convert.gen.go +// goverter:enum no +var ( + FromBillingDiscountPercentageToDiscountPercentage func(BillingDiscountPercentage) DiscountPercentage + FromBillingDiscountUsageToDiscountUsage func(BillingDiscountUsage) DiscountUsage +) diff --git a/api/openapi.cloud.yaml b/api/openapi.cloud.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33486790ccb2550b9180a04590cfaed64dc02cc7 --- /dev/null +++ b/api/openapi.cloud.yaml @@ -0,0 +1,25463 @@ +openapi: 3.0.0 +info: + title: OpenMeter Cloud API + version: 1.0.0 + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + termsOfService: https://openmeter.cloud/terms-of-service + description: |- + OpenMeter is a cloud native usage metering service. + The OpenMeter API allows you to ingest events, query meter usage, and manage resources. +tags: + - name: Subscriptions + description: With Subscriptions, you can easily start, cancel, and manage customer subscriptions. For example, provisioning them on a specific plan or assigning custom rate cards. + - name: Subjects + description: |- + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + + Subjects are entities that consume resources you wish to meter. These can range from users, servers, and services to devices. The design of subjects is intentionally generic, enabling flexible application across various metering scenarios. Typically, a subject acts as a unique identifier within your system for a user or customer. Meters are aggregating events for each subject. + - name: Product Catalog + description: 'Configure and manage your product plans, pricing tiers, and subscription offerings. ' + - name: Portal + description: With the Consumer Portal, you can build in-app user-facing dashboards where your users can track their usage in real-time. Subject scoped portal tokens can be generated on your behalf to allow restricted access to the OpenMeter API. + - name: Notifications + description: Notifications provide automated triggers when specific entitlement balances and usage thresholds are reached, ensuring that your customers and sales teams are always informed. Notify customers and internal teams when specific conditions are met, like reaching 75%, 100%, and 150% of their monthly usage allowance. [Read more](https://openmeter.io/docs/guides/notifications/overview). + - name: Meters + description: Meters specify how to aggregate events for billing and analytics purposes. Meters can be configured with multiple aggregation methods and groupings. Multiple meters can be created for the same event type, enabling flexible metering scenarios. + - name: Lookup Information + description: Lookup information for static data like currencies + - name: Events + description: Events are used to track usage of your product or service. Events are processed asynchronously by the meters, so they may not be immediately available for querying. + - name: Entitlements + description: With Entitlements, you can define and enforce usage limits, implement quota-based pricing, and manage access to features in your application. + - name: Debug + description: Debugging and testing endpoints. + - name: Customers + description: 'Manage customer subscription lifecycles and plan assignments. ' + - name: Billing + description: 'Manage your billing profiles and invoices. ' + - name: 'App: Custom Invoicing' + description: Interface third party invoicing and payment systems. + - name: 'App: Stripe' + description: Support for Stripe billing. + - name: Apps + description: "Manage integrations for extending OpenMeter's functionality. " +paths: + /api/v1/addons: + get: + operationId: listAddons + summary: List add-ons + description: List all add-ons. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted add-ons in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: id + in: query + required: false + description: Filter by addon.id attribute + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: key + in: query + required: false + description: Filter by addon.key attribute + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + style: form + - name: keyVersion + in: query + required: false + description: Filter by addon.key and addon.version attributes + schema: + type: object + additionalProperties: + type: array + items: + type: integer + style: deepObject + - name: status + in: query + required: false + description: |- + Only return add-ons with the given status. + + Usage: + - `?status=active`: return only the currently active add-ons + - `?status=draft`: return only the draft add-ons + - `?status=archived`: return only the archived add-ons + schema: + type: array + items: + $ref: '#/components/schemas/AddonStatus' + style: form + - name: currency + in: query + required: false + description: Filter by addon.currency attribute + schema: + type: array + items: + $ref: '#/components/schemas/CurrencyCode' + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/AddonOrderByOrdering.order' + - $ref: '#/components/parameters/AddonOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/AddonPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createAddon + summary: Create an add-on + description: Create a new add-on. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AddonCreate' + /api/v1/addons/{addonId}: + put: + operationId: updateAddon + summary: Update add-on + description: Update add-on by id. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AddonReplaceUpdate' + get: + operationId: getAddon + summary: Get add-on + description: Get add-on by id or key. The latest published version is returned if latter is used. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + x-go-type: string + x-go-type: string + - name: includeLatest + in: query + required: false + description: |- + Include latest version of the add-on instead of the version in active state. + + Usage: `?includeLatest=true` + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deleteAddon + summary: Delete add-on + description: |- + Soft delete add-on by id. + + Once a add-on is deleted it cannot be undeleted. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/addons/{addonId}/archive: + post: + operationId: archiveAddon + summary: Archive add-on version + description: Archive a add-on version. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/addons/{addonId}/publish: + post: + operationId: publishAddon + summary: Publish add-on + description: Publish a add-on version. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/apps: + get: + operationId: listApps + summary: List apps + description: List apps. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/AppPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized: + post: + operationId: appCustomInvoicingDraftSynchronized + summary: Submit draft synchronization results + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Custom Invoicing' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomInvoicingDraftSynchronizedRequest' + /api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized: + post: + operationId: appCustomInvoicingIssuingSynchronized + summary: Submit issuing synchronization results + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Custom Invoicing' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomInvoicingFinalizedRequest' + /api/v1/apps/custom-invoicing/{invoiceId}/payment/status: + post: + operationId: appCustomInvoicingUpdatePaymentStatus + summary: Update payment status + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Custom Invoicing' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomInvoicingUpdatePaymentStatusRequest' + /api/v1/apps/{id}: + get: + operationId: getApp + summary: Get app + description: Get the app. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/App' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + put: + operationId: updateApp + summary: Update app + description: Update an app. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/App' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AppReplaceUpdate' + delete: + operationId: uninstallApp + summary: Uninstall app + description: Uninstall an app. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/apps/{id}/stripe/api-key: + put: + operationId: updateStripeAPIKey + summary: Update Stripe API key + description: |- + Update the Stripe API key. + + ⚠️ __Deprecated__: Use [`PUT /api/v1/apps/{id}`](#tag/apps/put/api/v1/apps/{id}) instead. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Stripe' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/StripeAPIKeyInput' + deprecated: true + /api/v1/apps/{id}/stripe/webhook: + post: + operationId: appStripeWebhook + summary: Stripe webhook + description: Handle stripe webhooks for apps. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeWebhookResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Stripe' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/StripeWebhookEvent' + security: + - {} + /api/v1/billing/customers: + get: + operationId: listBillingProfileCustomerOverrides + summary: List customer overrides + description: |- + List customer overrides using the specified filters. + + The response will include the customer override values and the merged billing profile values. + + If the includeAllCustomers is set to true, the list contains all customers. This mode is + useful for getting the current effective billing workflow settings for all users regardless + if they have customer orverrides or not. + parameters: + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.billingProfile' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.includeAllCustomers' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerId' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerName' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerKey' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerPrimaryEmail' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.expand' + - $ref: '#/components/parameters/BillingProfileCustomerOverrideOrderByOrdering.order' + - $ref: '#/components/parameters/BillingProfileCustomerOverrideOrderByOrdering.orderBy' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetailsPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/customers/{customerId}: + put: + operationId: upsertBillingProfileCustomerOverride + summary: Create a new or update a customer override + description: |- + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetails' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideCreate' + get: + operationId: getBillingProfileCustomerOverride + summary: Get a customer override + description: |- + Get a customer override by customer id. + + The response will include the customer override values and the merged billing profile values. + + If the customer override is not found, the default billing profile's values are returned. This behavior + allows for getting a merged profile regardless of the customer override existence. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileCustomerOverrideExpand' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetails' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + delete: + operationId: deleteBillingProfileCustomerOverride + summary: Delete a customer override + description: |- + Delete a customer override by customer id. + + This will remove the customer override and the customer will be subject to the default + billing profile's settings again. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/customers/{customerId}/invoices/pending-lines: + post: + operationId: createPendingInvoiceLine + summary: Create pending line items + description: |- + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + - there is no invoice in gathering state + - the currency of the line item doesn't match the currency of any invoices in gathering state + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePendingLineCreateResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePendingLineCreateInput' + /api/v1/billing/customers/{customerId}/invoices/simulate: + post: + operationId: simulateInvoice + summary: Simulate an invoice for a customer + description: |- + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included in the invoice. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoiceSimulationInput' + /api/v1/billing/invoices: + get: + operationId: listInvoices + summary: List invoices + description: |- + List invoices based on the specified filters. + + The expand option can be used to include additional information (besides the invoice header and totals) + in the response. For example by adding the expand=lines option the invoice lines will be included in the response. + + Gathering invoices will always show the current usage calculated on the fly. + parameters: + - $ref: '#/components/parameters/InvoiceListParams.statuses' + - $ref: '#/components/parameters/InvoiceListParams.extendedStatuses' + - $ref: '#/components/parameters/InvoiceListParams.issuedAfter' + - $ref: '#/components/parameters/InvoiceListParams.issuedBefore' + - $ref: '#/components/parameters/InvoiceListParams.periodStartAfter' + - $ref: '#/components/parameters/InvoiceListParams.periodStartBefore' + - $ref: '#/components/parameters/InvoiceListParams.createdAfter' + - $ref: '#/components/parameters/InvoiceListParams.createdBefore' + - $ref: '#/components/parameters/InvoiceListParams.expand' + - $ref: '#/components/parameters/InvoiceListParams.customers' + - $ref: '#/components/parameters/InvoiceListParams.includeDeleted' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/InvoiceOrderByOrdering.order' + - $ref: '#/components/parameters/InvoiceOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/invoice: + post: + operationId: invoicePendingLinesAction + summary: Invoice a customer based on the pending line items + description: |- + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePendingLinesActionInput' + /api/v1/billing/invoices/{invoiceId}: + get: + operationId: getInvoice + summary: Get an invoice + description: |- + Get an invoice by ID. + + Gathering invoices will always show the current usage calculated on the fly. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/InvoiceExpand' + default: + - lines + style: form + - name: includeDeletedLines + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + delete: + operationId: deleteInvoice + summary: Delete an invoice + description: |- + Delete an invoice + + Only invoices that are in the draft (or earlier) status can be deleted. + + Invoices that are post finalization can only be voided. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + put: + operationId: updateInvoice + summary: Update an invoice + description: |- + Update an invoice + + Only invoices in draft or earlier status can be updated. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoiceReplaceUpdate' + /api/v1/billing/invoices/{invoiceId}/advance: + post: + operationId: advanceInvoiceAction + summary: Advance the invoice's state to the next status + description: |- + Advance the invoice's state to the next status. + + The call doesn't "approve the invoice", it only advances the invoice to the next status if the transition would be automatic. + + The action can be called when the invoice's statusDetails' actions field contain the "advance" action. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/approve: + post: + operationId: approveInvoiceAction + summary: Send the invoice to the customer + description: |- + Approve an invoice and start executing the payment workflow. + + This call instantly sends the invoice to the customer using the configured billing profile app. + + This call is valid in two invoice statuses: + - `draft`: the invoice will be sent to the customer, the invluce state becomes issued + - `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes issued + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/retry: + post: + operationId: retryInvoiceAction + summary: Retry advancing the invoice after a failed attempt. + description: |- + Retry advancing the invoice after a failed attempt. + + The action can be called when the invoice's statusDetails' actions field contain the "retry" action. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/snapshot-quantities: + post: + operationId: snapshotQuantitiesInvoiceAction + summary: Snapshot quantities for usage based line items + description: |- + Snapshot quantities for usage based line items. + + This call will snapshot the quantities for all usage based line items in the invoice. + + This call is only valid in `draft.waiting_for_collection` status, where the collection period + can be skipped using this action. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/taxes/recalculate: + post: + operationId: recalculateInvoiceTaxAction + summary: Recalculate an invoice's tax amounts + description: |- + Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + + Note: charges might apply, depending on the tax provider. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/void: + post: + operationId: voidInvoiceAction + summary: Void an invoice + description: |- + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line items. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/VoidInvoiceActionInput' + /api/v1/billing/profiles: + get: + operationId: listBillingProfiles + summary: List billing profiles + description: |- + List all billing profiles matching the specified filters. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing profile + will be included in the response. + parameters: + - name: includeArchived + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileExpand' + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/BillingProfileOrderByOrdering.order' + - $ref: '#/components/parameters/BillingProfileOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfilePaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + post: + operationId: createBillingProfile + summary: Create a new billing profile + description: |- + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfile' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCreate' + /api/v1/billing/profiles/{id}: + delete: + operationId: deleteBillingProfile + summary: Delete a billing profile + description: |- + Delete a billing profile by id. + + Only such billing profiles can be deleted that are: + - not the default one + - not pinned to any customer using customer overrides + - only have finalized invoices + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + get: + operationId: getBillingProfile + summary: Get a billing profile + description: |- + Get a billing profile by id. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing profile + will be included in the response. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileExpand' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfile' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + put: + operationId: updateBillingProfile + summary: Update a billing profile + description: |- + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfile' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileReplaceUpdateWithWorkflow' + /api/v1/customers: + post: + operationId: createCustomer + summary: Create customer + description: Create a new customer. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Customer' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerCreate' + get: + operationId: listCustomers + summary: List customers + description: List customers. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/CustomerOrderByOrdering.order' + - $ref: '#/components/parameters/CustomerOrderByOrdering.orderBy' + - $ref: '#/components/parameters/queryCustomerList.includeDeleted' + - $ref: '#/components/parameters/queryCustomerList.key' + - $ref: '#/components/parameters/queryCustomerList.name' + - $ref: '#/components/parameters/queryCustomerList.primaryEmail' + - $ref: '#/components/parameters/queryCustomerList.subject' + - $ref: '#/components/parameters/queryCustomerList.planKey' + - $ref: '#/components/parameters/queryCustomerList.expand' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + /api/v1/customers/{customerIdOrKey}: + get: + operationId: getCustomer + summary: Get customer + description: Get a customer by ID or key. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - $ref: '#/components/parameters/queryCustomerGet' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Customer' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + put: + operationId: updateCustomer + summary: Update customer + description: Update a customer by ID. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Customer' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerReplaceUpdate' + delete: + operationId: deleteCustomer + summary: Delete customer + description: Delete a customer by ID. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + /api/v1/customers/{customerIdOrKey}/access: + get: + operationId: getCustomerAccess + summary: Get customer access + description: Get the overall access of a customer. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerAccess' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v1/customers/{customerIdOrKey}/apps: + get: + operationId: listCustomerAppData + summary: List customer app data + description: List customers app data. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/listCustomerAppDataParams.type' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerAppDataPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + put: + operationId: upsertCustomerAppData + summary: Upsert customer app data + description: Upsert customer app data. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CustomerAppData' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CustomerAppDataCreateOrUpdateItem' + /api/v1/customers/{customerIdOrKey}/apps/{appId}: + delete: + operationId: deleteCustomerAppData + summary: Delete customer app data + description: Delete customer app data. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: appId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + /api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value: + get: + operationId: getCustomerEntitlementValue + summary: Get customer entitlement value + description: Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: featureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + - name: time + in: query + required: false + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementValue' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v1/customers/{customerIdOrKey}/stripe: + get: + operationId: getCustomerStripeAppData + summary: Get customer stripe app data + description: |- + Get stripe app data for a customer. + Only returns data if the customer billing profile is linked to a stripe app. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerAppData' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + put: + operationId: upsertCustomerStripeAppData + summary: Upsert customer stripe app data + description: |- + Upsert stripe app data for a customer. + Only updates data if the customer billing profile is linked to a stripe app. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerAppData' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerAppDataBase' + /api/v1/customers/{customerIdOrKey}/stripe/portal: + post: + operationId: createCustomerStripePortalSession + summary: Create Stripe customer portal session + description: |- + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerPortalSession' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateStripeCustomerPortalSessionParams' + /api/v1/customers/{customerIdOrKey}/subscriptions: + get: + operationId: listCustomerSubscriptions + summary: List customer subscriptions + description: Lists all subscriptions for a customer. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: status + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/SubscriptionStatus' + style: form + - $ref: '#/components/parameters/CustomerSubscriptionOrderByOrdering.order' + - $ref: '#/components/parameters/CustomerSubscriptionOrderByOrdering.orderBy' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + /api/v1/debug/metrics: + get: + operationId: getDebugMetrics + summary: Get event metrics + description: |- + Returns debug metrics (in OpenMetrics format) like the number of ingested events since mindnight UTC. + + The OpenMetrics Counter(s) reset every day at midnight UTC. + responses: + '200': + description: The request has succeeded. + content: + text/plain: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Debug + /api/v1/entitlements: + get: + operationId: listEntitlements + summary: List all entitlements + description: |- + List all entitlements for all the subjects and features. This endpoint is intended for administrative purposes only. + To fetch the entitlements of a specific subject please use the /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements`](#tag/entitlements/get/api/v2/entitlements) instead. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: subject + in: query + required: false + description: |- + Filtering by multiple subjects. + + Usage: `?subject=customer-1&subject=customer-2` + schema: + type: array + items: + type: string + style: form + - name: entitlementType + in: query + required: false + description: |- + Filtering by multiple entitlement types. + + Usage: `?entitlementType=metered&entitlementType=boolean` + schema: + type: array + items: + $ref: '#/components/schemas/EntitlementType' + style: form + - name: excludeInactive + in: query + required: false + description: Exclude inactive entitlements in the response (those scheduled for later or earlier) + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.order' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/ListEntitlementsResult' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + x-internal: true + /api/v1/entitlements/{entitlementId}: + get: + operationId: getEntitlementById + summary: Get entitlement by ID + description: |- + Get entitlement by ID. + + ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements/{entitlementId}`](#tag/entitlements/get/api/v2/entitlements/{entitlementId}) instead. + parameters: + - name: entitlementId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/events: + get: + operationId: listEvents + summary: List ingested events + description: |- + List ingested events within a time range. + + If the from query param is not provided it defaults to last 72 hours. + parameters: + - name: clientId + in: query + required: false + description: |- + Client ID + Useful to track progress of a query. + schema: + type: string + minLength: 1 + maxLength: 36 + explode: false + style: form + - name: ingestedAtFrom + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: ingestedAtTo + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: id + in: query + required: false + description: |- + The event ID. + + Accepts partial ID. + schema: + type: string + explode: false + style: form + - name: subject + in: query + required: false + description: |- + The event subject. + + Accepts partial subject. + schema: + type: string + explode: false + style: form + - name: customerId + in: query + required: false + description: The event customer ID. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: limit + in: query + required: false + description: Number of events to return. + schema: + type: integer + minimum: 1 + maximum: 100 + default: 100 + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/IngestedEvent' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Events + post: + operationId: ingestEvents + description: Ingests an event or batch of events following the CloudEvents specification. + summary: Ingest events + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Events + requestBody: + required: true + content: + application/cloudevents+json: + schema: + $ref: '#/components/schemas/Event' + application/cloudevents-batch+json: + schema: + type: array + items: + $ref: '#/components/schemas/Event' + application/json: + schema: + $ref: '#/components/schemas/IngestEventsBody' + /api/v1/features: + get: + operationId: listFeatures + summary: List features + description: List features. + parameters: + - name: meterSlug + in: query + required: false + description: Filter by meterSlug + schema: + type: array + items: + type: string + style: form + - name: includeArchived + in: query + required: false + description: Include archived features in response. + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/FeatureOrderByOrdering.order' + - $ref: '#/components/parameters/FeatureOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/ListFeaturesResult' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createFeature + summary: Create feature + description: |- + Features are either metered or static. A feature is metered if meterSlug is provided at creation. + For metered features you can pass additional filters that will be applied when calculating feature usage, based on the meter's groupBy fields. + Meters with SUM, COUNT, UNIQUE_COUNT and LATEST aggregations are supported for features. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Feature' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/FeatureCreateInputs' + /api/v1/features/{featureId}: + get: + operationId: getFeature + summary: Get feature + description: Get a feature by ID. + parameters: + - name: featureId + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Feature' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deleteFeature + summary: Delete feature + description: |- + Archive a feature by ID. + + Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements cannot be created for it, but archiving the feature does not affect existing entitlements. + This means, if you want to create a new feature with the same key, and then create entitlements for it, the previous entitlements have to be deleted first on a per subject basis. + parameters: + - name: featureId + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/grants: + get: + operationId: listGrants + summary: List grants + description: |- + List all grants for all the subjects and entitlements. This endpoint is intended for administrative purposes only. + To fetch the grants of a specific entitlement please use the /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ __Deprecated__: Use [`GET /api/v2/grants`](#tag/entitlements/get/api/v2/grants) instead. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: subject + in: query + required: false + description: |- + Filtering by multiple subjects. + + Usage: `?subject=customer-1&subject=customer-2` + schema: + type: array + items: + type: string + style: form + - name: includeDeleted + in: query + required: false + description: Include deleted + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/GrantOrderByOrdering.order' + - $ref: '#/components/parameters/GrantOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + anyOf: + - type: array + items: + $ref: '#/components/schemas/EntitlementGrant' + - $ref: '#/components/schemas/GrantPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/grants/{grantId}: + delete: + operationId: voidGrant + summary: Void grant + description: |- + Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed to the grant will remain, but future usage cannot be burnt down from the grant. + For example, if you have a single grant for your metered entitlement with an initial amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous usage will not be affected. + parameters: + - name: grantId + in: path + required: true + schema: + type: string + - name: at + in: query + required: false + description: |- + The time at which the grant should be voided. + Must not be in the future and must be within the current usage period of the entitlement. + Defaults to the current time if not specified. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v1/info/currencies: + get: + operationId: listCurrencies + summary: List supported currencies + description: List all supported currencies. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Currency' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Lookup Information + /api/v1/info/progress/{id}: + get: + operationId: getProgress + summary: Get progress + description: Get progress + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Progress' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Lookup Information + /api/v1/marketplace/listings: + get: + operationId: listMarketplaceListings + summary: List available apps + description: List available apps of the app marketplace. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceListingPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/marketplace/listings/{type}: + get: + operationId: getMarketplaceListing + summary: Get app details by type + description: Get a marketplace listing by type. + parameters: + - name: type + in: path + required: true + schema: + $ref: '#/components/schemas/AppType' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceListing' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/marketplace/listings/{type}/install: + post: + operationId: marketplaceAppInstall + summary: Install app + description: Install an app from the marketplace. + parameters: + - $ref: '#/components/parameters/MarketplaceInstallRequest.type' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceInstallResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceInstallRequestPayload' + /api/v1/marketplace/listings/{type}/install/apikey: + post: + operationId: marketplaceAppAPIKeyInstall + summary: Install app via API key + description: Install an marketplace app via API Key. + parameters: + - $ref: '#/components/parameters/MarketplaceApiKeyInstallRequest.type' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceInstallResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: |- + Name of the application to install. + + If name is not provided defaults to the marketplace listing's name. + createBillingProfile: + type: boolean + description: |- + If true, a billing profile will be created for the app. + The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + default: true + apiKey: + type: string + description: |- + The API key for the provider. + For example, the Stripe API key. + required: + - apiKey + /api/v1/marketplace/listings/{type}/install/oauth2: + get: + operationId: marketplaceOAuth2InstallGetURL + summary: Get OAuth2 install URL + description: |- + Install an app via OAuth. + Returns a URL to start the OAuth 2.0 flow. + parameters: + - name: type + in: path + required: true + schema: + $ref: '#/components/schemas/AppType' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientAppStartResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/marketplace/listings/{type}/install/oauth2/authorize: + get: + operationId: marketplaceOAuth2InstallAuthorize + summary: Install app via OAuth2 + description: |- + Authorize OAuth2 code. + Verifies the OAuth code and exchanges it for a token and refresh token + parameters: + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantSuccessParams.state' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantSuccessParams.code' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantErrorParams.error' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantErrorParams.error_description' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantErrorParams.error_uri' + - $ref: '#/components/parameters/MarketplaceOAuth2InstallAuthorizeRequest.type' + responses: + '303': + description: Redirection + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/meters: + get: + operationId: listMeters + summary: List meters + description: List meters. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/MeterOrderByOrdering.order' + - $ref: '#/components/parameters/MeterOrderByOrdering.orderBy' + - $ref: '#/components/parameters/queryMeterList.includeDeleted' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + post: + operationId: createMeter + summary: Create meter + description: Create a meter. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MeterCreate' + /api/v1/meters/{meterIdOrSlug}: + get: + operationId: getMeter + summary: Get meter + description: Get a meter by ID or slug. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + put: + operationId: updateMeter + summary: Update meter + description: Update a meter. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MeterUpdate' + delete: + operationId: deleteMeter + summary: Delete meter + description: Delete a meter. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + /api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values: + get: + operationId: listMeterGroupByValues + summary: List meter group by values + description: List meter group by values. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: groupByKey + in: path + required: true + schema: + type: string + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. Defaults to 24 hours ago. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + /api/v1/meters/{meterIdOrSlug}/query: + get: + operationId: queryMeter + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - $ref: '#/components/parameters/MeterQuery.clientId' + - $ref: '#/components/parameters/MeterQuery.from' + - $ref: '#/components/parameters/MeterQuery.to' + - $ref: '#/components/parameters/MeterQuery.windowSize' + - $ref: '#/components/parameters/MeterQuery.windowTimeZone' + - $ref: '#/components/parameters/MeterQuery.subject' + - $ref: '#/components/parameters/MeterQuery.filterCustomerId' + - $ref: '#/components/parameters/MeterQuery.filterGroupBy' + - $ref: '#/components/parameters/MeterQuery.advancedMeterGroupByFilters' + - $ref: '#/components/parameters/MeterQuery.groupBy' + description: Query meter for usage. + summary: Query meter + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryResult' + text/csv: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + post: + operationId: queryMeterPost + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + summary: Query meter + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryResult' + text/csv: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryRequest' + /api/v1/meters/{meterIdOrSlug}/subjects: + get: + operationId: listMeterSubjects + summary: List meter subjects + description: List subjects for a meter. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. Defaults to the beginning of time. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + /api/v1/notification/channels: + get: + operationId: listNotificationChannels + summary: List notification channels + description: List all notification channels. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted notification channels in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: includeDisabled + in: query + required: false + description: |- + Include disabled notification channels in response. + + Usage: `?includeDisabled=false` + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/NotificationChannelOrderByOrdering.order' + - $ref: '#/components/parameters/NotificationChannelOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + post: + operationId: createNotificationChannel + summary: Create a notification channel + description: Create a new notification channel. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannel' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelCreateRequest' + /api/v1/notification/channels/{channelId}: + put: + operationId: updateNotificationChannel + summary: Update a notification channel + description: Update notification channel. + parameters: + - name: channelId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannel' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelCreateRequest' + get: + operationId: getNotificationChannel + summary: Get notification channel + description: Get a notification channel by id. + parameters: + - name: channelId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannel' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + delete: + operationId: deleteNotificationChannel + summary: Delete a notification channel + description: |- + Soft delete notification channel by id. + + Once a notification channel is deleted it cannot be undeleted. + parameters: + - name: channelId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/events: + get: + operationId: listNotificationEvents + summary: List notification events + description: List all notification events. + parameters: + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: feature + in: query + required: false + description: |- + Filtering by multiple feature ids or keys. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: subject + in: query + required: false + description: |- + Filtering by multiple subject ids or keys. + + Usage: `?subject=subject-1&subject=subject-2` + schema: + type: array + items: + type: string + style: form + - name: rule + in: query + required: false + description: |- + Filtering by multiple rule ids. + + Usage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5` + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: channel + in: query + required: false + description: |- + Filtering by multiple channel ids. + + Usage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J` + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/NotificationEventOrderByOrdering.order' + - $ref: '#/components/parameters/NotificationEventOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEventPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/events/{eventId}: + get: + operationId: getNotificationEvent + summary: Get notification event + description: Get a notification event by id. + parameters: + - name: eventId + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEvent' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/events/{eventId}/resend: + post: + operationId: resendNotificationEvent + summary: Re-send notification event + parameters: + - name: eventId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '202': + description: The request has been accepted for processing, but processing has not yet completed. + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEventResendRequest' + /api/v1/notification/rules: + get: + operationId: listNotificationRules + summary: List notification rules + description: List all notification rules. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted notification rules in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: includeDisabled + in: query + required: false + description: |- + Include disabled notification rules in response. + + Usage: `?includeDisabled=false` + schema: + type: boolean + default: false + explode: false + style: form + - name: feature + in: query + required: false + description: |- + Filtering by multiple feature ids/keys. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ULID (Universally Unique Lexicographically Sortable Identifier). + A key is a unique string that is used to identify a resource. + + TODO: this is a temporary solution to support both ULID and Key in the same spec for codegen. + style: form + - name: channel + in: query + required: false + description: |- + Filtering by multiple notifiaction channel ids. + + Usage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3` + schema: + type: array + items: + type: string + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/NotificationRuleOrderByOrdering.order' + - $ref: '#/components/parameters/NotificationRuleOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRulePaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + post: + operationId: createNotificationRule + summary: Create a notification rule + description: Create a new notification rule. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRule' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRuleCreateRequest' + /api/v1/notification/rules/{ruleId}: + put: + operationId: updateNotificationRule + summary: Update a notification rule + description: Update notification rule. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRule' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRuleCreateRequest' + get: + operationId: getNotificationRule + summary: Get notification rule + description: Get a notification rule by id. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRule' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + delete: + operationId: deleteNotificationRule + summary: Delete a notification rule + description: |- + Soft delete notification rule by id. + + Once a notification rule is deleted it cannot be undeleted. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/rules/{ruleId}/test: + post: + operationId: testNotificationRule + summary: Test notification rule + description: Test a notification rule by sending a test event with random data. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEvent' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/plans: + get: + operationId: listPlans + summary: List plans + description: List all plans. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted plans in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: id + in: query + required: false + description: Filter by plan.id attribute + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: key + in: query + required: false + description: Filter by plan.key attribute + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + style: form + - name: keyVersion + in: query + required: false + description: Filter by plan.key and plan.version attributes + schema: + type: object + additionalProperties: + type: array + items: + type: integer + style: deepObject + - name: status + in: query + required: false + description: |- + Only return plans with the given status. + + Usage: + - `?status=active`: return only the currently active plan + - `?status=draft`: return only the draft plan + - `?status=archived`: return only the archived plans + schema: + type: array + items: + $ref: '#/components/schemas/PlanStatus' + style: form + - name: currency + in: query + required: false + description: Filter by plan.currency attribute + schema: + type: array + items: + $ref: '#/components/schemas/CurrencyCode' + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/PlanOrderByOrdering.order' + - $ref: '#/components/parameters/PlanOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createPlan + summary: Create a plan + description: Create a new plan. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanCreate' + /api/v1/plans/{planIdOrKey}/next: + post: + operationId: nextPlan + summary: New draft plan + description: |- + Create a new draft version from plan. + It returns error if there is already a plan in draft or planId does not reference the latest published version. + parameters: + - name: planIdOrKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + x-go-type: string + x-go-type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + deprecated: true + /api/v1/plans/{planId}: + put: + operationId: updatePlan + summary: Update a plan + description: Update plan by id. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanReplaceUpdate' + get: + operationId: getPlan + summary: Get plan + description: Get a plan by id or key. The latest published version is returned if latter is used. + parameters: + - name: planId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + x-go-type: string + x-go-type: string + - name: includeLatest + in: query + required: false + description: |- + Include latest version of the Plan instead of the version in active state. + + Usage: `?includeLatest=true` + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deletePlan + summary: Delete plan + description: |- + Soft delete plan by plan.id. + + Once a plan is deleted it cannot be undeleted. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/plans/{planId}/addons: + get: + operationId: listPlanAddons + summary: List all available add-ons for plan + description: List all available add-ons for plan. + parameters: + - name: planId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: includeDeleted + in: query + required: false + description: |- + Include deleted plan add-on assignments. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: id + in: query + required: false + description: Filter by addon.id attribute. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: key + in: query + required: false + description: Filter by addon.key attribute. + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + style: form + - name: keyVersion + in: query + required: false + description: Filter by addon.key and addon.version attributes. + schema: + type: object + additionalProperties: + type: array + items: + type: integer + style: deepObject + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/PlanAddonOrderByOrdering.order' + - $ref: '#/components/parameters/PlanAddonOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddonPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createPlanAddon + summary: Create new add-on assignment for plan + description: Create new add-on assignment for plan. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddonCreate' + /api/v1/plans/{planId}/addons/{planAddonId}: + put: + operationId: updatePlanAddon + summary: Update add-on assignment for plan + description: Update add-on assignment for plan. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: planAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddonReplaceUpdate' + get: + operationId: getPlanAddon + summary: Get add-on assignment for plan + description: Get add-on assignment for plan by id. + parameters: + - name: planId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: planAddonId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deletePlanAddon + summary: Delete add-on assignment for plan + description: |- + Delete add-on assignment for plan. + + Once a plan is deleted it cannot be undeleted. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: planAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/plans/{planId}/archive: + post: + operationId: archivePlan + summary: Archive plan version + description: Archive a plan version. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/plans/{planId}/publish: + post: + operationId: publishPlan + summary: Publish plan + description: Publish a plan version. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/portal/meters/{meterSlug}/query: + get: + operationId: queryPortalMeter + parameters: + - name: meterSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + - $ref: '#/components/parameters/MeterQuery.clientId' + - $ref: '#/components/parameters/MeterQuery.from' + - $ref: '#/components/parameters/MeterQuery.to' + - $ref: '#/components/parameters/MeterQuery.windowSize' + - $ref: '#/components/parameters/MeterQuery.windowTimeZone' + - $ref: '#/components/parameters/MeterQuery.filterCustomerId' + - $ref: '#/components/parameters/MeterQuery.filterGroupBy' + - $ref: '#/components/parameters/MeterQuery.advancedMeterGroupByFilters' + - $ref: '#/components/parameters/MeterQuery.groupBy' + description: Query meter for consumer portal. This endpoint is publicly exposable to consumers. Query meter for consumer portal. This endpoint is publicly exposable to consumers. + summary: Query meter Query meter + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryResult' + text/csv: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + security: + - CloudPortalTokenAuth: [] + /api/v1/portal/tokens: + post: + operationId: createPortalToken + summary: Create consumer portal token + description: Create a consumer portal token. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PortalToken' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PortalToken' + get: + operationId: listPortalTokens + summary: List consumer portal tokens + description: List tokens. + parameters: + - name: limit + in: query + required: false + schema: + type: integer + minimum: 1 + maximum: 100 + default: 25 + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PortalToken' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + /api/v1/portal/tokens/invalidate: + post: + operationId: invalidatePortalTokens + summary: Invalidate portal tokens + description: Invalidates consumer portal tokens by ID or subject. + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + id: + type: string + description: Invalidate a portal token by ID. + subject: + type: string + description: Invalidate all portal tokens for a subject. + /api/v1/stripe/checkout/sessions: + post: + operationId: createStripeCheckoutSession + summary: Create checkout session + description: Create checkout session. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/CreateStripeCheckoutSessionResult' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Stripe' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateStripeCheckoutSessionRequest' + /api/v1/subjects: + get: + operationId: listSubjects + summary: List subjects + description: |- + List subjects. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Subject' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + deprecated: true + post: + operationId: upsertSubject + summary: Upsert subject + description: |- + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Subject' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SubjectUpsert' + deprecated: true + /api/v1/subjects/{subjectIdOrKey}: + get: + operationId: getSubject + summary: Get subject + description: |- + Get subject by ID or key. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subject' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + deprecated: true + delete: + operationId: deleteSubject + summary: Delete subject + description: |- + Delete subject by ID or key. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements: + post: + operationId: createEntitlement + summary: Create a subject entitlement + description: |- + OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + + - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementCreateInputs' + deprecated: true + get: + operationId: listSubjectEntitlements + summary: List subject entitlements + description: |- + List all entitlements for a subject. For checking entitlement access, use the /value endpoint instead. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants: + get: + operationId: listEntitlementGrants + summary: List subject entitlement grants + description: |- + List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - name: orderBy + in: query + required: false + schema: + allOf: + - $ref: '#/components/schemas/GrantOrderBy' + default: updatedAt + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/EntitlementGrant' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + post: + operationId: createGrant + summary: Create subject entitlement grant + description: |- + Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + + ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrant' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrantCreateInput' + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override: + put: + operationId: overrideEntitlement + summary: Override subject entitlement + description: |- + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided subject-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + + ⚠️ __Deprecated__: Use [`PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override`](#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementCreateInputs' + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value: + get: + operationId: getEntitlementValue + summary: Get subject entitlement value + description: |- + This endpoint should be used for access checks and enforcement. All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + + For convenience reasons, /value works with both entitlementId and featureKey. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + - name: time + in: query + required: false + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementValue' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}: + get: + operationId: getEntitlement + summary: Get subject entitlement + description: |- + Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + delete: + operationId: deleteEntitlement + summary: Delete subject entitlement + description: |- + Deleting an entitlement revokes access to the associated feature. As a single subject can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + + ⚠️ __Deprecated__: Use [`DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history: + get: + operationId: getEntitlementHistory + summary: Get subject entitlement history + description: |- + Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + - name: from + in: query + required: false + description: 'Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter.' + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + If not now then gets truncated to the granularity of the underlying meter. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: windowSize + in: query + required: true + description: Windowsize + schema: + $ref: '#/components/schemas/WindowSize' + explode: false + style: form + - name: windowTimeZone + in: query + required: false + description: The timezone used when calculating the windows. + schema: + type: string + default: UTC + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/WindowedBalanceHistory' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset: + post: + operationId: resetEntitlementUsage + summary: Reset subject entitlement + description: |- + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the subjects billing period to enforce usage based on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + + ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ResetEntitlementUsageInput' + deprecated: true + /api/v1/subscriptions: + post: + operationId: createSubscription + summary: Create subscription + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionCreate' + /api/v1/subscriptions/{subscriptionId}: + get: + operationId: getSubscription + summary: Get subscription + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: at + in: query + required: false + description: The time at which the subscription should be queried. If not provided the current time is used. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionExpanded' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + patch: + operationId: editSubscription + summary: Edit subscription + description: |- + Batch processing commands for manipulating running subscriptions. + The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionEdit' + delete: + operationId: deleteSubscription + summary: Delete subscription + description: Deletes a subscription. Only scheduled subscriptions can be deleted. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + /api/v1/subscriptions/{subscriptionId}/addons: + post: + operationId: createSubscriptionAddon + summary: Create subscription addon + description: Create a new subscription addon, either providing the key or the id of the addon. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddonCreate' + get: + operationId: listSubscriptionAddons + summary: List subscription addons + description: List all addons of a subscription. In the returned list will match to a set unique by addonId. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + /api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}: + get: + operationId: getSubscriptionAddon + summary: Get subscription addon + description: Get a subscription addon by id. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: subscriptionAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + patch: + operationId: updateSubscriptionAddon + summary: Update subscription addon + description: 'Updates a subscription addon (allows changing the quantity: purchasing more instances or cancelling the current instances)' + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: subscriptionAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddonUpdate' + /api/v1/subscriptions/{subscriptionId}/cancel: + post: + operationId: cancelSubscription + summary: Cancel subscription + description: |- + Cancels the subscription. + Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancellation time. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: If not provided the subscription is canceled immediately. + /api/v1/subscriptions/{subscriptionId}/change: + post: + operationId: changeSubscription + summary: Change subscription + description: |- + Closes a running subscription and starts a new one according to the specification. + Can be used for upgrades, downgrades, and plan changes. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionChangeResponseBody' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionChange' + /api/v1/subscriptions/{subscriptionId}/migrate: + post: + operationId: migrateSubscription + summary: Migrate subscription + description: |- + Migrates the subscripiton to the provided version of the current plan. + If possible, the migration will be done immediately. + If not, the migration will be scheduled to the end of the current billing period. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionChangeResponseBody' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the migration, when the migration should take effect. + If not supported by the subscription, 400 will be returned. + default: immediate + targetVersion: + type: integer + minimum: 1 + description: |- + The version of the plan to migrate to. + If not provided, the subscription will migrate to the latest version of the current plan. + startingPhase: + type: string + minLength: 1 + description: |- + The key of the phase to start the subscription in. + If not provided, the subscription will start in the first phase of the plan. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + example: '2023-01-01T01:01:01.001Z' + /api/v1/subscriptions/{subscriptionId}/restore: + post: + operationId: restoreSubscription + summary: Restore subscription + description: |- + Restores a canceled subscription. + Any subscription scheduled to start later will be deleted and this subscription will be continued indefinitely. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + deprecated: true + /api/v1/subscriptions/{subscriptionId}/unschedule-cancelation: + post: + operationId: unscheduleCancelation + summary: Unschedule cancelation + description: Cancels the scheduled cancelation. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + /api/v2/customers/{customerIdOrKey}/entitlements: + post: + operationId: createCustomerEntitlementV2 + summary: Create a customer entitlement + description: |- + OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + + - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2CreateInputs' + get: + operationId: listCustomerEntitlementsV2 + summary: List customer entitlements + description: List all entitlements for a customer. For checking entitlement access, use the /value endpoint instead. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.order' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}: + get: + operationId: getCustomerEntitlementV2 + summary: Get customer entitlement + description: |- + Get entitlement by feature key. For checking entitlement access, use the /value endpoint instead. + If featureKey is used, the entitlement is resolved for the current timestamp. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + delete: + operationId: deleteCustomerEntitlementV2 + summary: Delete customer entitlement + description: |- + Deleting an entitlement revokes access to the associated feature. As a single customer can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants: + get: + operationId: listCustomerEntitlementGrantsV2 + summary: List customer entitlement grants + description: List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/GrantOrderByOrdering.order' + - $ref: '#/components/parameters/GrantOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/GrantV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + post: + operationId: createCustomerEntitlementGrantV2 + summary: Create customer entitlement grant + description: |- + Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrantV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrantCreateInputV2' + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history: + get: + operationId: getCustomerEntitlementHistoryV2 + summary: Get customer entitlement history + description: |- + Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: from + in: query + required: false + description: 'Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter.' + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + If not now then gets truncated to the granularity of the underlying meter. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: windowSize + in: query + required: true + description: Windowsize + schema: + $ref: '#/components/schemas/WindowSize' + explode: false + style: form + - name: windowTimeZone + in: query + required: false + description: The timezone used when calculating the windows. + schema: + type: string + default: UTC + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/WindowedBalanceHistory' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override: + put: + operationId: overrideCustomerEntitlementV2 + summary: Override customer entitlement + description: |- + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided customer-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2CreateInputs' + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset: + post: + operationId: resetCustomerEntitlementUsageV2 + summary: Reset customer entitlement + description: |- + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the customers billing period to enforce usage based on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ResetEntitlementUsageInput' + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value: + get: + operationId: getCustomerEntitlementValueV2 + summary: Get customer entitlement value + description: Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: time + in: query + required: false + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementValueV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v2/entitlements: + get: + operationId: listEntitlementsV2 + summary: List all entitlements + description: |- + List all entitlements for all the customers and features. This endpoint is intended for administrative purposes only. + To fetch the entitlements of a specific subject please use the /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: customerKeys + in: query + required: false + description: |- + Filtering by multiple customers. + + Usage: `?customerKeys=customer-1&customerKeys=customer-3` + schema: + type: array + items: + type: string + style: form + - name: customerIds + in: query + required: false + description: |- + Filtering by multiple customers. + + Usage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9` + schema: + type: array + items: + type: string + style: form + - name: entitlementType + in: query + required: false + description: |- + Filtering by multiple entitlement types. + + Usage: `?entitlementType=metered&entitlementType=boolean` + schema: + type: array + items: + $ref: '#/components/schemas/EntitlementType' + style: form + - name: excludeInactive + in: query + required: false + description: Exclude inactive entitlements in the response (those scheduled for later or earlier) + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.order' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v2/entitlements/{entitlementId}: + get: + operationId: getEntitlementByIdV2 + summary: Get entitlement by ID + description: Get entitlement by ID. + parameters: + - name: entitlementId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v2/events: + get: + operationId: listEventsV2 + summary: List ingested events + description: List ingested events with advanced filtering and cursor pagination. + parameters: + - $ref: '#/components/parameters/CursorPagination.cursor' + - $ref: '#/components/parameters/CursorPagination.limit' + - name: clientId + in: query + required: false + description: |- + Client ID + Useful to track progress of a query. + schema: + type: string + minLength: 1 + maxLength: 36 + explode: false + style: form + - name: filter + in: query + required: false + description: The filter for the events encoded as JSON string. + content: + application/json: + schema: + properties: + id: + $ref: '#/components/schemas/FilterString' + source: + $ref: '#/components/schemas/FilterString' + subject: + $ref: '#/components/schemas/FilterString' + customerId: + $ref: '#/components/schemas/FilterIDExact' + type: + $ref: '#/components/schemas/FilterString' + time: + $ref: '#/components/schemas/FilterTime' + ingestedAt: + $ref: '#/components/schemas/FilterTime' + format: application/json + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/IngestedEventCursorPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Events + /api/v2/grants: + get: + operationId: listGrantsV2 + summary: List grants + description: |- + List all grants for all the customers and entitlements. This endpoint is intended for administrative purposes only. + To fetch the grants of a specific entitlement please use the /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: customer + in: query + required: false + description: |- + Filtering by multiple customers (either by ID or key). + + Usage: `?customer=customer-1&customer=customer-2` + schema: + type: array + items: + $ref: '#/components/schemas/ULIDOrExternalKey' + style: form + - name: includeDeleted + in: query + required: false + description: Include deleted + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/GrantOrderByOrdering.order' + - $ref: '#/components/parameters/GrantOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/GrantV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements +security: + - CloudTokenAuth: [] + - CloudCookieAuth: [] +components: + parameters: + AddonOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + AddonOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/AddonOrderBy' + explode: false + style: form + BillingProfileCustomerOverrideOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + BillingProfileCustomerOverrideOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideOrderBy' + explode: false + style: form + BillingProfileListCustomerOverridesParams.billingProfile: + name: billingProfile + in: query + required: false + description: Filter by billing profile. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + BillingProfileListCustomerOverridesParams.customerId: + name: customerId + in: query + required: false + description: Filter by customer id. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + BillingProfileListCustomerOverridesParams.customerKey: + name: customerKey + in: query + required: false + description: Filter by customer key + schema: + type: string + explode: false + style: form + BillingProfileListCustomerOverridesParams.customerName: + name: customerName + in: query + required: false + description: Filter by customer name. + schema: + type: string + explode: false + style: form + BillingProfileListCustomerOverridesParams.customerPrimaryEmail: + name: customerPrimaryEmail + in: query + required: false + description: Filter by customer primary email + schema: + type: string + explode: false + style: form + BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile: + name: customersWithoutPinnedProfile + in: query + required: false + description: Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. + schema: + type: boolean + style: form + BillingProfileListCustomerOverridesParams.expand: + name: expand + in: query + required: false + description: Expand the response with additional details. + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileCustomerOverrideExpand' + style: form + BillingProfileListCustomerOverridesParams.includeAllCustomers: + name: includeAllCustomers + in: query + required: false + description: |- + Include customers without customer overrides. + + If set to false only the customers specifically associated with a billing profile will be returned. + + If set to true, in case of the default billing profile, all customers will be returned. + schema: + type: boolean + default: true + style: form + BillingProfileOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + BillingProfileOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/BillingProfileOrderBy' + explode: false + style: form + CursorPagination.cursor: + name: cursor + in: query + required: false + description: The cursor after which to start the pagination. + schema: + type: string + explode: false + style: form + CursorPagination.limit: + name: limit + in: query + required: false + description: The limit of the pagination. + schema: + type: integer + minimum: 1 + maximum: 100 + default: 100 + explode: false + style: form + CustomerOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + CustomerOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/CustomerOrderBy' + explode: false + style: form + CustomerSubscriptionOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + CustomerSubscriptionOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/CustomerSubscriptionOrderBy' + explode: false + style: form + EntitlementOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + EntitlementOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/EntitlementOrderBy' + explode: false + style: form + FeatureOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + FeatureOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/FeatureOrderBy' + explode: false + style: form + GrantOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + GrantOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/GrantOrderBy' + explode: false + style: form + InvoiceListParams.createdAfter: + name: createdAfter + in: query + required: false + description: |- + Filter by invoice created time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.createdBefore: + name: createdBefore + in: query + required: false + description: |- + Filter by invoice created time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.customers: + name: customers + in: query + required: false + description: Filter by customer ID + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + InvoiceListParams.expand: + name: expand + in: query + required: false + description: What parts of the list output to expand in listings + schema: + type: array + items: + $ref: '#/components/schemas/InvoiceExpand' + style: form + InvoiceListParams.extendedStatuses: + name: extendedStatuses + in: query + required: false + description: Filter by invoice extended statuses + schema: + type: array + items: + type: string + style: form + InvoiceListParams.includeDeleted: + name: includeDeleted + in: query + required: false + description: Include deleted invoices + schema: + type: boolean + explode: false + style: form + InvoiceListParams.issuedAfter: + name: issuedAfter + in: query + required: false + description: |- + Filter by invoice issued time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.issuedBefore: + name: issuedBefore + in: query + required: false + description: |- + Filter by invoice issued time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.periodStartAfter: + name: periodStartAfter + in: query + required: false + description: |- + Filter by period start time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.periodStartBefore: + name: periodStartBefore + in: query + required: false + description: |- + Filter by period start time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.statuses: + name: statuses + in: query + required: false + description: Filter by the invoice status. + schema: + type: array + items: + $ref: '#/components/schemas/InvoiceStatus' + style: form + InvoiceOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + InvoiceOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/InvoiceOrderBy' + explode: false + style: form + LimitOffset.limit: + name: limit + in: query + required: false + description: |- + Number of items to return. + + Default is 100. + schema: + type: integer + minimum: 1 + maximum: 1000 + default: 100 + explode: false + style: form + LimitOffset.offset: + name: offset + in: query + required: false + description: |- + Number of items to skip. + + Default is 0. + schema: + type: integer + minimum: 0 + default: 0 + explode: false + style: form + MarketplaceApiKeyInstallRequest.type: + name: type + in: path + required: true + description: The type of the app to install. + schema: + $ref: '#/components/schemas/AppType' + MarketplaceInstallRequest.type: + name: type + in: path + required: true + description: The type of the app to install. + schema: + $ref: '#/components/schemas/AppType' + MarketplaceOAuth2InstallAuthorizeRequest.type: + name: type + in: path + required: true + description: The type of the app to install. + schema: + $ref: '#/components/schemas/AppType' + MeterOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + MeterOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/MeterOrderBy' + explode: false + style: form + MeterQuery.advancedMeterGroupByFilters: + name: advancedMeterGroupByFilters + in: query + required: false + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + content: + application/json: + schema: + additionalProperties: + $ref: '#/components/schemas/FilterString' + title: Advanced meter group by filters + format: application/json + MeterQuery.clientId: + name: clientId + in: query + required: false + description: |- + Client ID + Useful to track progress of a query. + schema: + type: string + minLength: 1 + maxLength: 36 + explode: false + style: form + MeterQuery.filterCustomerId: + name: filterCustomerId + in: query + required: false + description: |- + Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + schema: + type: array + items: + type: string + maxItems: 100 + style: form + MeterQuery.filterGroupBy: + name: filterGroupBy + in: query + required: false + description: |- + Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + schema: + type: object + additionalProperties: + type: string + style: deepObject + deprecated: true + MeterQuery.from: + name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + MeterQuery.groupBy: + name: groupBy + in: query + required: false + description: |- + If not specified a single aggregate will be returned for each subject and time window. + `subject` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model + schema: + type: array + items: + type: string + style: form + MeterQuery.subject: + name: subject + in: query + required: false + description: |- + Filtering by multiple subjects. + + For example: ?subject=subject-1&subject=subject-2 + schema: + type: array + items: + type: string + style: form + MeterQuery.to: + name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + MeterQuery.windowSize: + name: windowSize + in: query + required: false + description: |- + If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY + schema: + $ref: '#/components/schemas/WindowSize' + explode: false + style: form + MeterQuery.windowTimeZone: + name: windowTimeZone + in: query + required: false + description: |- + The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC + schema: + type: string + default: UTC + explode: false + style: form + NotificationChannelOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + NotificationChannelOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/NotificationChannelOrderBy' + explode: false + style: form + NotificationEventOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + NotificationEventOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/NotificationEventOrderBy' + explode: false + style: form + NotificationRuleOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + NotificationRuleOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/NotificationRuleOrderBy' + explode: false + style: form + OAuth2AuthorizationCodeGrantErrorParams.error: + name: error + in: query + required: false + description: |- + Error code. + Required with the error response. + schema: + $ref: '#/components/schemas/OAuth2AuthorizationCodeGrantErrorType' + explode: false + style: form + OAuth2AuthorizationCodeGrantErrorParams.error_description: + name: error_description + in: query + required: false + description: |- + Optional human-readable text providing additional information, + used to assist the client developer in understanding the error that occurred. + schema: + type: string + explode: false + style: form + OAuth2AuthorizationCodeGrantErrorParams.error_uri: + name: error_uri + in: query + required: false + description: |- + Optional uri identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error + schema: + type: string + explode: false + style: form + OAuth2AuthorizationCodeGrantSuccessParams.code: + name: code + in: query + required: false + description: |- + Authorization code which the client will later exchange for an access token. + Required with the success response. + schema: + type: string + explode: false + style: form + OAuth2AuthorizationCodeGrantSuccessParams.state: + name: state + in: query + required: false + description: |- + Required if the "state" parameter was present in the client authorization request. + The exact value received from the client: + + Unique, randomly generated, opaque, and non-guessable string that is sent + when starting an authentication request and validated when processing the response. + schema: + type: string + explode: false + style: form + Pagination.page: + name: page + in: query + required: false + description: |- + Page index. + + Default is 1. + schema: + type: integer + minimum: 1 + default: 1 + explode: false + style: form + Pagination.pageSize: + name: pageSize + in: query + required: false + description: |- + The maximum number of items per page. + + Default is 100. + schema: + type: integer + minimum: 1 + maximum: 1000 + default: 100 + explode: false + style: form + PlanAddonOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + PlanAddonOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/PlanAddonOrderBy' + explode: false + style: form + PlanOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + PlanOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/PlanOrderBy' + explode: false + style: form + listCustomerAppDataParams.type: + name: type + in: query + required: false + description: Filter customer data by app type. + schema: + $ref: '#/components/schemas/AppType' + explode: false + style: form + queryCustomerGet: + name: expand + in: query + required: false + description: What parts of the customer output to expand + schema: + type: array + items: + $ref: '#/components/schemas/CustomerExpand' + style: form + queryCustomerList.expand: + name: expand + in: query + required: false + description: What parts of the list output to expand in listings + schema: + type: array + items: + $ref: '#/components/schemas/CustomerExpand' + style: form + queryCustomerList.includeDeleted: + name: includeDeleted + in: query + required: false + description: Include deleted customers. + schema: + type: boolean + default: false + explode: false + style: form + queryCustomerList.key: + name: key + in: query + required: false + description: |- + Filter customers by key. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryCustomerList.name: + name: name + in: query + required: false + description: |- + Filter customers by name. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryCustomerList.planKey: + name: planKey + in: query + required: false + description: Filter customers by the plan key of their susbcription. + schema: + type: string + explode: false + style: form + queryCustomerList.primaryEmail: + name: primaryEmail + in: query + required: false + description: |- + Filter customers by primary email. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryCustomerList.subject: + name: subject + in: query + required: false + description: |- + Filter customers by usage attribution subject. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryMeterList.includeDeleted: + name: includeDeleted + in: query + required: false + description: Include deleted meters. + schema: + type: boolean + default: false + explode: false + style: form + schemas: + Addon: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - version + - instanceType + - currency + - status + - rateCards + - validationErrors + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + version: + type: integer + minimum: 1 + description: Version of the add-on. Incremented when the add-on is updated. + title: Version + default: 1 + readOnly: true + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instanceType of the add-ons. Can be "single" or "multiple". + title: InstanceType + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the add-on. + title: Currency + default: USD + effectiveFrom: + type: string + format: date-time + description: The date and time when the add-on becomes effective. When not specified, the add-on is a draft. + example: '2023-01-01T01:01:01.001Z' + title: Effective start date + readOnly: true + effectiveTo: + type: string + format: date-time + description: The date and time when the add-on is no longer effective. When not specified, the add-on is effective indefinitely. + example: '2023-01-01T01:01:01.001Z' + title: Effective end date + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AddonStatus' + description: |- + The status of the add-on. + Computed based on the effective start and end dates: + - draft = no effectiveFrom + - active = effectiveFrom <= now < effectiveTo + - archived = effectiveTo <= now + title: Status + readOnly: true + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the add-on. + title: Rate cards + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + nullable: true + description: List of validation errors. + title: Validation errors + readOnly: true + description: Add-on allows extending subscriptions with compatible plans with additional ratecards. + AddonCreate: + type: object + required: + - name + - key + - instanceType + - currency + - rateCards + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instanceType of the add-ons. Can be "single" or "multiple". + title: InstanceType + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the add-on. + title: Currency + default: USD + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the add-on. + title: Rate cards + description: Resource create operation model. + AddonInstanceType: + type: string + enum: + - single + - multiple + description: |- + The instanceType of the add-on. + Single instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once. + AddonOrderBy: + type: string + enum: + - id + - key + - version + - created_at + - updated_at + description: Order by options for add-ons. + AddonPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Addon' + description: The items in the current page. + description: Paginated response + AddonReplaceUpdate: + type: object + required: + - name + - instanceType + - rateCards + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instanceType of the add-ons. Can be "single" or "multiple". + title: InstanceType + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the add-on. + title: Rate cards + description: Resource update operation model. + AddonStatus: + type: string + enum: + - draft + - active + - archived + description: The status of the add-on defined by the effectiveFrom and effectiveTo properties. + Address: + type: object + properties: + country: + allOf: + - $ref: '#/components/schemas/CountryCode' + description: Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format. + postalCode: + type: string + description: Postal code. + state: + type: string + description: State or province. + city: + type: string + description: City. + line1: + type: string + description: First line of the address. + line2: + type: string + description: Second line of the address. + phoneNumber: + type: string + description: Phone number. + description: Address + Alignment: + type: object + properties: + billablesMustAlign: + type: boolean + description: |- + Whether all Billable items and RateCards must align. + Alignment means the Price's BillingCadence must align for both duration and anchor time. + deprecated: true + description: Alignment configuration for a plan or subscription. + deprecated: true + Annotations: + type: object + additionalProperties: {} + description: Set of key-value pairs managed by the system. Cannot be modified by user. + example: + externalId: 019142cc-a016-796a-8113-1a942fecd26d + App: + type: object + oneOf: + - $ref: '#/components/schemas/StripeApp' + - $ref: '#/components/schemas/SandboxApp' + - $ref: '#/components/schemas/CustomInvoicingApp' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeApp' + sandbox: '#/components/schemas/SandboxApp' + custom_invoicing: '#/components/schemas/CustomInvoicingApp' + description: |- + App. + One of: stripe + AppCapability: + type: object + required: + - type + - key + - name + - description + properties: + type: + allOf: + - $ref: '#/components/schemas/AppCapabilityType' + description: The capability type. + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: Key + name: + type: string + description: The capability name. + description: + type: string + description: The capability description. + description: |- + App capability. + + Capabilities only exist in config so they don't extend the Resource model. + example: + type: collectPayments + key: stripe_collect_payment + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + AppCapabilityType: + type: string + enum: + - reportUsage + - reportEvents + - calculateTax + - invoiceCustomers + - collectPayments + description: App capability type. + AppPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/App' + description: The items in the current page. + description: Paginated response + AppReference: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the app. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: |- + App reference + + Can be used as a short reference to an app if the full app object is not needed. + AppReplaceUpdate: + type: object + oneOf: + - $ref: '#/components/schemas/StripeAppReplaceUpdate' + - $ref: '#/components/schemas/SandboxAppReplaceUpdate' + - $ref: '#/components/schemas/CustomInvoicingAppReplaceUpdate' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeAppReplaceUpdate' + sandbox: '#/components/schemas/SandboxAppReplaceUpdate' + custom_invoicing: '#/components/schemas/CustomInvoicingAppReplaceUpdate' + description: App ReplaceUpdate Model + AppStatus: + type: string + enum: + - ready + - unauthorized + description: App installed status. + AppType: + type: string + enum: + - stripe + - sandbox + - custom_invoicing + description: Type of the app. + BadRequestProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + BalanceHistoryWindow: + type: object + required: + - period + - usage + - balanceAtStart + properties: + period: + $ref: '#/components/schemas/Period' + usage: + type: number + format: double + description: The total usage of the feature in the period. + example: 100 + readOnly: true + balanceAtStart: + type: number + format: double + description: The entitlement balance at the start of the period. + example: 100 + readOnly: true + description: The balance history window. + BillingCustomerProfile: + type: object + required: + - supplier + - workflow + - apps + properties: + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + readOnly: true + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The billing workflow settings for this profile + readOnly: true + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsOrReference' + description: |- + The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + readOnly: true + description: |- + Customer specific merged profile. + + This profile is calculated from the customer override and the billing profile it references or the default. + + Thus this does not have any kind of resource fields, only the calculated values. + BillingDiscountPercentage: + type: object + required: + - percentage + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + minimum: 0 + maximum: 100 + description: The percentage of the discount. + title: Percentage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: A percentage discount. + BillingDiscountReason: + type: object + oneOf: + - $ref: '#/components/schemas/DiscountReasonMaximumSpend' + - $ref: '#/components/schemas/DiscountReasonRatecardPercentage' + - $ref: '#/components/schemas/DiscountReasonRatecardUsage' + discriminator: + propertyName: type + mapping: + maximum_spend: '#/components/schemas/DiscountReasonMaximumSpend' + ratecard_percentage: '#/components/schemas/DiscountReasonRatecardPercentage' + ratecard_usage: '#/components/schemas/DiscountReasonRatecardUsage' + description: The reason for the discount. + BillingDiscountUsage: + type: object + required: + - quantity + properties: + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the usage discount. + + Must be positive. + title: Usage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: A usage discount. + BillingDiscounts: + type: object + properties: + percentage: + allOf: + - $ref: '#/components/schemas/BillingDiscountPercentage' + description: The percentage discount. + usage: + allOf: + - $ref: '#/components/schemas/BillingDiscountUsage' + description: The usage discount. + description: A discount by type. + BillingInvoiceCustomerExtendedDetails: + type: object + required: + - usageAttribution + properties: + id: + type: string + description: Unique identifier for the party (if available) + readOnly: true + key: + type: string + minLength: 1 + maxLength: 256 + description: An optional unique key of the party (if available) + title: Key + name: + type: string + description: Legal name or representation of the organization. + taxId: + allOf: + - $ref: '#/components/schemas/BillingPartyTaxIdentity' + description: |- + The entity's legal ID code used for tax purposes. They may have + other numbers, but we're only interested in those valid for tax purposes. + addresses: + type: array + items: + $ref: '#/components/schemas/Address' + maxItems: 1 + description: Regular post addresses for where information should be sent if needed. + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: Mapping to attribute metered usage to the customer + title: Usage Attribution + description: |- + BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the billing party details for invoices. + + These fields contain the OpenMeter specific details for the customer, that are not strictly required for the invoice itself. + BillingParty: + type: object + properties: + id: + type: string + description: Unique identifier for the party (if available) + readOnly: true + key: + type: string + minLength: 1 + maxLength: 256 + description: An optional unique key of the party (if available) + title: Key + name: + type: string + description: Legal name or representation of the organization. + taxId: + allOf: + - $ref: '#/components/schemas/BillingPartyTaxIdentity' + description: |- + The entity's legal ID code used for tax purposes. They may have + other numbers, but we're only interested in those valid for tax purposes. + addresses: + type: array + items: + $ref: '#/components/schemas/Address' + maxItems: 1 + description: Regular post addresses for where information should be sent if needed. + description: Party represents a person or business entity. + BillingPartyReplaceUpdate: + type: object + properties: + key: + type: string + minLength: 1 + maxLength: 256 + description: An optional unique key of the party (if available) + title: Key + name: + type: string + description: Legal name or representation of the organization. + taxId: + allOf: + - $ref: '#/components/schemas/BillingPartyTaxIdentity' + description: |- + The entity's legal ID code used for tax purposes. They may have + other numbers, but we're only interested in those valid for tax purposes. + addresses: + type: array + items: + $ref: '#/components/schemas/Address' + maxItems: 1 + description: Regular post addresses for where information should be sent if needed. + description: Resource update operation model. + BillingPartyTaxIdentity: + type: object + properties: + code: + allOf: + - $ref: '#/components/schemas/BillingTaxIdentificationCode' + description: Normalized tax code shown on the original identity document. + description: Identity stores the details required to identify an entity for tax purposes in a specific country. + BillingProfile: + type: object + required: + - id + - name + - createdAt + - updatedAt + - supplier + - workflow + - apps + - default + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The billing workflow settings for this profile + readOnly: true + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsOrReference' + description: |- + The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + readOnly: true + default: + type: boolean + description: Is this the default profile? + description: BillingProfile represents a billing profile + BillingProfileAppReferences: + type: object + required: + - tax + - invoicing + - payment + properties: + tax: + allOf: + - $ref: '#/components/schemas/AppReference' + description: The tax app used for this workflow + readOnly: true + invoicing: + allOf: + - $ref: '#/components/schemas/AppReference' + description: The invoicing app used for this workflow + readOnly: true + payment: + allOf: + - $ref: '#/components/schemas/AppReference' + description: The payment app used for this workflow + readOnly: true + description: BillingProfileAppReferences represents the references (id, type) to the apps used by a billing profile + BillingProfileApps: + type: object + required: + - tax + - invoicing + - payment + properties: + tax: + allOf: + - $ref: '#/components/schemas/App' + description: The tax app used for this workflow + readOnly: true + invoicing: + allOf: + - $ref: '#/components/schemas/App' + description: The invoicing app used for this workflow + readOnly: true + payment: + allOf: + - $ref: '#/components/schemas/App' + description: The payment app used for this workflow + readOnly: true + description: BillingProfileApps represents the applications used by a billing profile + BillingProfileAppsCreate: + type: object + required: + - tax + - invoicing + - payment + properties: + tax: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The tax app used for this workflow + example: 01G65Z755AFWAKHE12NY0CQ9FH + x-go-type: string + invoicing: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The invoicing app used for this workflow + example: 01G65Z755AFWAKHE12NY0CQ9FH + x-go-type: string + payment: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The payment app used for this workflow + example: 01G65Z755AFWAKHE12NY0CQ9FH + x-go-type: string + description: BillingProfileAppsCreate represents the input for creating a billing profile's apps + BillingProfileAppsOrReference: + anyOf: + - $ref: '#/components/schemas/BillingProfileApps' + - $ref: '#/components/schemas/BillingProfileAppReferences' + description: |- + ProfileAppsOrReference represents the union of ProfileApps and ProfileAppReferences + for a billing profile. + BillingProfileCreate: + type: object + required: + - name + - supplier + - default + - workflow + - apps + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + default: + type: boolean + description: Is this the default profile? + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCreate' + description: The billing workflow settings for this profile. + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsCreate' + description: The apps used by this billing profile. + description: BillingProfileCreate represents the input for creating a billing profile + BillingProfileCustomerOverride: + type: object + required: + - createdAt + - updatedAt + - customerId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + billingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The billing profile this override is associated with. + + If empty the default profile is looked up dynamically. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer id this override is associated with. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Customer override values. + BillingProfileCustomerOverrideCreate: + type: object + properties: + billingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The billing profile this override is associated with. + + If not provided, the default billing profile is chosen if available. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Payload for creating a new or updating an existing customer override. + BillingProfileCustomerOverrideExpand: + type: string + enum: + - apps + - customer + description: CustomerOverrideExpand specifies the parts of the profile to expand. + BillingProfileCustomerOverrideOrderBy: + type: string + enum: + - customerId + - customerName + - customerKey + - customerPrimaryEmail + - customerCreatedAt + description: Order by options for customers. + BillingProfileCustomerOverrideWithDetails: + type: object + required: + - baseBillingProfileId + properties: + customerOverride: + allOf: + - $ref: '#/components/schemas/BillingProfileCustomerOverride' + description: |- + The customer override values. + + If empty the merged values are calculated based on the default profile. + baseBillingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The billing profile the customerProfile is associated with at the time of query. + + customerOverride contains the explicit mapping set in the customer override object. If that is + empty, then the baseBillingProfileId is the default profile. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerProfile: + allOf: + - $ref: '#/components/schemas/BillingCustomerProfile' + description: Merged billing profile with the customer specific overrides. + customer: + allOf: + - $ref: '#/components/schemas/Customer' + description: The customer this override belongs to. + description: Customer specific workflow overrides. + BillingProfileCustomerOverrideWithDetailsPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetails' + description: The items in the current page. + description: Paginated response + BillingProfileExpand: + type: string + enum: + - apps + description: BillingProfileExpand details what profile fields to expand + BillingProfileOrderBy: + type: string + enum: + - createdAt + - updatedAt + - default + - name + description: BillingProfileOrderBy specifies the ordering options for profiles + BillingProfilePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/BillingProfile' + description: The items in the current page. + description: Paginated response + BillingProfileReplaceUpdateWithWorkflow: + type: object + required: + - name + - supplier + - default + - workflow + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + default: + type: boolean + description: Is this the default profile? + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The billing workflow settings for this profile. + description: |- + BillingProfileReplaceUpdate represents the input for updating a billing profile + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + BillingSettlementMode: + type: string + enum: + - credit_then_invoice + - credit_only + description: |- + The settlement mode of a plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + BillingTaxIdentificationCode: + type: string + minLength: 1 + maxLength: 32 + description: TaxIdentificationCode is a normalized tax code shown on the original identity document. + BillingWorkflow: + type: object + properties: + collection: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionSettings' + description: The collection settings for this workflow + invoicing: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSettings' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + tax: + allOf: + - $ref: '#/components/schemas/BillingWorkflowTaxSettings' + description: The tax settings for this workflow + description: BillingWorkflow represents the settings for a billing workflow. + BillingWorkflowCollectionAlignment: + type: object + oneOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionAlignmentSubscription' + - $ref: '#/components/schemas/BillingWorkflowCollectionAlignmentAnchored' + discriminator: + propertyName: type + mapping: + subscription: '#/components/schemas/BillingWorkflowCollectionAlignmentSubscription' + anchored: '#/components/schemas/BillingWorkflowCollectionAlignmentAnchored' + description: |- + The alignment for collecting the pending line items into an invoice. + + Defaults to subscription, which means that we are to create a new invoice every time the + a subscription period starts (for in advance items) or ends (for in arrears items). + BillingWorkflowCollectionAlignmentAnchored: + type: object + required: + - type + - recurringPeriod + properties: + type: + type: string + enum: + - anchored + description: The type of alignment. + recurringPeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodV2' + description: The recurring period for the alignment. + description: |- + BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items + into an invoice. + BillingWorkflowCollectionAlignmentSubscription: + type: object + required: + - type + properties: + type: + type: string + enum: + - subscription + description: The type of alignment. + description: |- + BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items + into an invoice. + BillingWorkflowCollectionSettings: + type: object + properties: + alignment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionAlignment' + description: The alignment for collecting the pending line items into an invoice. + default: + type: subscription + interval: + type: string + format: ISO8601 + description: |- + This grace period can be used to delay the collection of the pending line items specified in + alignment. + + This is useful, in case of multiple subscriptions having slightly different billing periods. + example: P1D + default: PT1H + description: Workflow collection specifies how to collect the pending line items for an invoice + BillingWorkflowCreate: + type: object + properties: + collection: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionSettings' + description: The collection settings for this workflow + invoicing: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSettings' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + tax: + allOf: + - $ref: '#/components/schemas/BillingWorkflowTaxSettings' + description: The tax settings for this workflow + description: Resource create operation model. + BillingWorkflowInvoicingSettings: + type: object + properties: + autoAdvance: + type: boolean + description: Whether to automatically issue the invoice after the draftPeriod has passed. + default: true + draftPeriod: + type: string + format: ISO8601 + description: The period for the invoice to be kept in draft status for manual reviews. + example: P1D + default: P0D + dueAfter: + type: string + format: ISO8601 + description: |- + The period after which the invoice is due. + With some payment solutions it's only applicable for manual collection method. + example: P30D + default: P30D + progressiveBilling: + type: boolean + description: Should progressive billing be allowed for this workflow? + default: true + subscriptionEndProrationMode: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSubscriptionEndProrationMode' + description: Controls how subscription-ending shortened service periods are billed. + default: bill_actual_period + defaultTaxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + Default tax configuration to apply to the invoices. + + Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and `behavior` remains + fully supported. + description: BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow + title: Workflow invoice settings + BillingWorkflowInvoicingSubscriptionEndProrationMode: + type: string + enum: + - bill_full_period + - bill_actual_period + description: Billing workflow subscription end proration mode. + BillingWorkflowPaymentSettings: + type: object + properties: + collectionMethod: + allOf: + - $ref: '#/components/schemas/CollectionMethod' + description: The payment method for the invoice. + default: charge_automatically + description: BillingWorkflowPaymentSettings represents the payment settings for a billing workflow + title: Workflow payment settings + BillingWorkflowTaxSettings: + type: object + properties: + enabled: + type: boolean + description: |- + Enable automatic tax calculation when tax is supported by the app. + For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + default: true + enforced: + type: boolean + description: |- + Enforce tax calculation when tax is supported by the app. + When enabled, OpenMeter will not allow to create an invoice without tax calculation. + Enforcement is different per apps, for example, Stripe app requires customer + to have a tax location when starting a paid subscription. + default: false + description: BillingWorkflowTaxSettings represents the tax settings for a billing workflow + title: Workflow tax settings + CheckoutSessionCustomTextAfterSubmitParams: + type: object + properties: + afterSubmit: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed after the payment confirmation button. + shippingAddress: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed alongside shipping address collection. + submit: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed alongside the payment confirmation button. + termsOfServiceAcceptance: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed in place of the default terms of service agreement text. + description: Stripe CheckoutSession.custom_text + CheckoutSessionUIMode: + type: string + enum: + - embedded + - hosted + description: Stripe CheckoutSession.ui_mode + ClientAppStartResponse: + type: object + required: + - url + properties: + url: + type: string + description: The URL to start the OAuth2 authorization code grant flow. + description: Response from the client app (OpenMeter backend) to start the OAuth2 flow. + CollectionMethod: + type: string + enum: + - charge_automatically + - send_invoice + description: CollectionMethod specifies how the invoice should be collected (automatic vs manual) + title: Collection method + ConflictProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The request could not be completed due to a conflict with the current state of the target resource. + CountryCode: + type: string + minLength: 2 + maxLength: 2 + pattern: ^[A-Z]{2}$ + description: |- + [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. + Custom two-letter country codes are also supported for convenience. + example: US + CreateCheckoutSessionTaxIdCollection: + type: object + required: + - enabled + properties: + enabled: + type: boolean + description: Enable tax ID collection during checkout. Defaults to false. + required: + allOf: + - $ref: '#/components/schemas/CreateCheckoutSessionTaxIdCollectionRequired' + description: Describes whether a tax ID is required during checkout. Defaults to never. + description: Create Stripe checkout session tax ID collection. + CreateCheckoutSessionTaxIdCollectionRequired: + type: string + enum: + - if_supported + - never + description: Create Stripe checkout session tax ID collection required. + CreateStripeCheckoutSessionBillingAddressCollection: + type: string + enum: + - auto + - required + description: Specify whether Checkout should collect the customer’s billing address. + CreateStripeCheckoutSessionConsentCollection: + type: object + properties: + paymentMethodReuseAgreement: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement' + description: |- + Determines the position and visibility of the payment method reuse agreement in the UI. + When set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI. + promotions: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionPromotions' + description: |- + If set to auto, enables the collection of customer consent for promotional communications. + The Checkout Session will determine whether to display an option to opt into promotional + communication from the merchant depending on the customer’s locale. Only available to US merchants. + termsOfService: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionTermsOfService' + description: |- + If set to required, it requires customers to check a terms of service checkbox before being able to pay. + There must be a valid terms of service URL set in your Stripe Dashboard settings. + https://dashboard.stripe.com/settings/public + description: Configure fields for the Checkout Session to gather active consent from customers. + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement: + type: object + properties: + position: + $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition' + description: Create Stripe checkout session payment method reuse agreement. + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition: + type: string + enum: + - auto + - hidden + description: Create Stripe checkout session consent collection agreement position. + CreateStripeCheckoutSessionConsentCollectionPromotions: + type: string + enum: + - auto + - none + description: Create Stripe checkout session consent collection promotions. + CreateStripeCheckoutSessionConsentCollectionTermsOfService: + type: string + enum: + - none + - required + description: Create Stripe checkout session consent collection terms of service. + CreateStripeCheckoutSessionCustomerUpdate: + type: object + properties: + address: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdateBehavior' + description: |- + Describes whether Checkout saves the billing address onto customer.address. + To always collect a full billing address, use billing_address_collection. + Defaults to never. + name: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdateBehavior' + description: |- + Describes whether Checkout saves the name onto customer.name. + Defaults to never. + shipping: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdateBehavior' + description: |- + Describes whether Checkout saves shipping information onto customer.shipping. + To collect shipping information, use shipping_address_collection. + Defaults to never. + description: Controls what fields on Customer can be updated by the Checkout Session. + CreateStripeCheckoutSessionCustomerUpdateBehavior: + type: string + enum: + - auto + - never + description: Create Stripe checkout session customer update behavior. + CreateStripeCheckoutSessionRedirectOnCompletion: + type: string + enum: + - always + - if_required + - never + description: Create Stripe checkout session redirect on completion. + CreateStripeCheckoutSessionRequest: + type: object + required: + - customer + - options + properties: + appId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: If not provided, the default Stripe app is used if any. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customer: + anyOf: + - $ref: '#/components/schemas/CustomerId' + - $ref: '#/components/schemas/CustomerKey' + - $ref: '#/components/schemas/CustomerCreate' + description: |- + Provide a customer ID or key to use an existing OpenMeter customer. + or provide a customer object to create a new customer. + stripeCustomerId: + type: string + description: |- + Stripe customer ID. + If not provided OpenMeter creates a new Stripe customer or + uses the OpenMeter customer's default Stripe customer ID. + options: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionRequestOptions' + description: Options passed to Stripe when creating the checkout session. + description: Create Stripe checkout session request. + example: + customer: + name: ACME, Inc. + currency: USD + usageAttribution: + subjectKeys: + - my-identifier + options: + currency: USD + successURL: http://example.com + billingAddressCollection: required + taxIdCollection: + enabled: true + required: if_supported + customerUpdate: + name: auto + address: auto + CreateStripeCheckoutSessionRequestOptions: + type: object + properties: + billingAddressCollection: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionBillingAddressCollection' + description: Specify whether Checkout should collect the customer’s billing address. Defaults to auto. + cancelURL: + type: string + description: |- + If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + This parameter is not allowed if ui_mode is embedded. + clientReferenceID: + type: string + description: A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + customerUpdate: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdate' + description: Controls what fields on Customer can be updated by the Checkout Session. + consentCollection: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollection' + description: Configure fields for the Checkout Session to gather active consent from customers. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: Three-letter ISO currency code, in lowercase. + customText: + allOf: + - $ref: '#/components/schemas/CheckoutSessionCustomTextAfterSubmitParams' + description: Display additional text for your customers using custom text. + expiresAt: + type: integer + format: int64 + description: |- + The Epoch time in seconds at which the Checkout Session will expire. + It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + locale: + type: string + metadata: + type: object + additionalProperties: + type: string + description: |- + Set of key-value pairs that you can attach to an object. + This can be useful for storing additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to metadata. + returnURL: + type: string + description: |- + The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site. + This parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session. + successURL: + type: string + description: |- + The URL to which Stripe should send customers when payment or setup is complete. + This parameter is not allowed if ui_mode is embedded. + If you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page: + https://docs.stripe.com/payments/checkout/custom-success-page + uiMode: + allOf: + - $ref: '#/components/schemas/CheckoutSessionUIMode' + description: The UI mode of the Session. Defaults to hosted. + paymentMethodTypes: + type: array + items: + type: string + description: A list of the types of payment methods (e.g., card) this Checkout Session can accept. + redirectOnCompletion: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionRedirectOnCompletion' + description: |- + This parameter applies to ui_mode: embedded. Defaults to always. + Learn more about the redirect behavior of embedded sessions at + https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + taxIdCollection: + allOf: + - $ref: '#/components/schemas/CreateCheckoutSessionTaxIdCollection' + description: Controls tax ID collection during checkout. + description: |- + Create Stripe checkout session options + See https://docs.stripe.com/api/checkout/sessions/create + CreateStripeCheckoutSessionResult: + type: object + required: + - customerId + - stripeCustomerId + - sessionId + - setupIntentId + - createdAt + - mode + properties: + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The OpenMeter customer ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + stripeCustomerId: + type: string + description: The Stripe customer ID. + sessionId: + type: string + description: The checkout session ID. + setupIntentId: + type: string + description: The checkout session setup intent ID. + clientSecret: + type: string + description: |- + The client secret of the checkout session. + This can be used to initialize Stripe.js for your client-side implementation. + clientReferenceId: + type: string + description: |- + A unique string to reference the Checkout Session. + This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + customerEmail: + type: string + description: Customer's email address provided to Stripe. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: Three-letter ISO currency code, in lowercase. + createdAt: + type: string + format: date-time + description: Timestamp at which the checkout session was created. + example: '2023-01-01T01:01:01.001Z' + expiresAt: + type: string + format: date-time + description: Timestamp at which the checkout session will expire. + example: '2023-01-01T01:01:01.001Z' + metadata: + type: object + additionalProperties: + type: string + description: Set of key-value pairs attached to the checkout session. + status: + type: string + description: The status of the checkout session. + url: + type: string + description: URL to show the checkout session. + mode: + allOf: + - $ref: '#/components/schemas/StripeCheckoutSessionMode' + description: |- + Mode + Always `setup` for now. + cancelURL: + type: string + description: Cancel URL. + successURL: + type: string + description: Success URL. + returnURL: + type: string + description: Return URL. + description: Create Stripe Checkout Session response. + CreateStripeCustomerPortalSessionParams: + type: object + properties: + configurationId: + type: string + description: |- + The ID of an existing configuration to use for this session, + describing its functionality and features. + If not specified, the session uses the default configuration. + + See https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration + title: Configuration + locale: + type: string + description: |- + The IETF language tag of the locale customer portal is displayed in. + If blank or auto, the customer’s preferred_locales or browser’s locale is used. + + See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale + title: Locale + returnUrl: + type: string + description: |- + The URL to redirect the customer to after they have completed + their requested actions. + + See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url + title: ReturnUrl + description: Stripe customer portal request params. + CreditNoteOriginalInvoiceRef: + type: object + required: + - type + - url + properties: + type: + type: string + enum: + - credit_note_original_invoice + description: Type of the invoice. + issuedAt: + type: string + format: date-time + description: IssueAt reflects the time the document was issued. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: (Serial) Number of the referenced document. + readOnly: true + url: + type: string + format: uri + description: Link to the source document. + readOnly: true + allOf: + - $ref: '#/components/schemas/InvoiceGenericDocumentRef' + description: CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is based on. + Currency: + type: object + required: + - code + - name + - symbol + - subunits + properties: + code: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency ISO code. + name: + type: string + description: The currency name. + symbol: + type: string + description: The currency symbol. + subunits: + type: integer + format: uint32 + description: Subunit of the currency. + description: Currency describes a currency supported by OpenMeter. + CurrencyCode: + type: string + minLength: 3 + maxLength: 3 + pattern: ^[A-Z]{3}$ + description: |- + Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. + Custom three-letter currency codes are also supported for convenience. + example: USD + CustomInvoicingApp: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + - enableDraftSyncHook + - enableIssuingSyncHook + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - custom_invoicing + description: The app's type is CustomInvoicing. + enableDraftSyncHook: + type: boolean + description: |- + Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + enableIssuingSyncHook: + type: boolean + description: |- + Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + description: |- + Custom Invoicing app can be used for interface with any invoicing or payment system. + + This app provides ways to manipulate invoices and payments, however the integration + must rely on Notifications API to get notified about invoice changes. + CustomInvoicingAppReplaceUpdate: + type: object + required: + - name + - type + - enableDraftSyncHook + - enableIssuingSyncHook + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + type: + type: string + enum: + - custom_invoicing + description: The app's type is CustomInvoicing. + enableDraftSyncHook: + type: boolean + description: |- + Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + enableIssuingSyncHook: + type: boolean + description: |- + Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + description: Resource update operation model. + CustomInvoicingCustomerAppData: + type: object + required: + - type + properties: + app: + allOf: + - $ref: '#/components/schemas/CustomInvoicingApp' + description: The installed custom invoicing app this data belongs to. + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - custom_invoicing + description: The app name. + title: App Type + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Metadata to be used by the custom invoicing provider. + description: Custom Invoicing Customer App Data. + CustomInvoicingDraftSynchronizedRequest: + type: object + properties: + invoicing: + allOf: + - $ref: '#/components/schemas/CustomInvoicingSyncResult' + description: The result of the synchronization. + description: Information to finalize the draft details of an invoice. + CustomInvoicingFinalizedInvoicingRequest: + type: object + properties: + invoiceNumber: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: If set the invoice's number will be set to this value. + sentToCustomerAt: + type: string + format: date-time + description: If set the invoice's sent to customer at will be set to this value. + example: '2023-01-01T01:01:01.001Z' + description: Information to finalize the invoicing details of an invoice. + CustomInvoicingFinalizedPaymentRequest: + type: object + properties: + externalId: + type: string + description: If set the invoice's payment external ID will be set to this value. + description: Information to finalize the payment details of an invoice. + CustomInvoicingFinalizedRequest: + type: object + properties: + invoicing: + allOf: + - $ref: '#/components/schemas/CustomInvoicingFinalizedInvoicingRequest' + description: The result of the synchronization. + payment: + allOf: + - $ref: '#/components/schemas/CustomInvoicingFinalizedPaymentRequest' + description: The result of the payment synchronization. + description: |- + Information to finalize the invoice. + + If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix). + CustomInvoicingLineDiscountExternalIdMapping: + type: object + required: + - lineDiscountId + - externalId + properties: + lineDiscountId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The line discount ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + externalId: + type: string + description: The external ID (e.g. custom invoicing system's ID). + description: Mapping between line discounts and external IDs. + CustomInvoicingLineExternalIdMapping: + type: object + required: + - lineId + - externalId + properties: + lineId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The line ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + externalId: + type: string + description: The external ID (e.g. custom invoicing system's ID). + description: Mapping between lines and external IDs. + CustomInvoicingPaymentTrigger: + type: string + enum: + - paid + - payment_failed + - payment_uncollectible + - payment_overdue + - action_required + - void + description: Payment trigger to execute on a finalized invoice. + CustomInvoicingSyncResult: + type: object + properties: + invoiceNumber: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: If set the invoice's number will be set to this value. + externalId: + type: string + description: If set the invoice's invoicing external ID will be set to this value. + lineExternalIds: + type: array + items: + $ref: '#/components/schemas/CustomInvoicingLineExternalIdMapping' + description: |- + If set the invoice's line external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice. + lineDiscountExternalIds: + type: array + items: + $ref: '#/components/schemas/CustomInvoicingLineDiscountExternalIdMapping' + description: |- + If set the invoice's line discount external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice. + description: |- + Information to synchronize the invoice. + + Can be used to store external app's IDs on the invoice or lines. + CustomInvoicingTaxConfig: + type: object + required: + - code + properties: + code: + type: string + description: |- + Tax code. + + The tax code should be interpreted by the custom invoicing provider. + title: Tax code + description: Custom invoicing tax config. + CustomInvoicingUpdatePaymentStatusRequest: + type: object + required: + - trigger + properties: + trigger: + allOf: + - $ref: '#/components/schemas/CustomInvoicingPaymentTrigger' + description: The trigger to be executed on the invoice. + description: |- + Update payment status request. + + Can be used to manipulate invoice's payment status (when custominvoicing app is being used). + CustomPlanInput: + type: object + allOf: + - type: object + required: + - name + - currency + - billingCadence + - phases + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the plan. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + description: The template for omitting properties. + description: Plan input for custom subscription creation (without key and version). + CustomSubscriptionChange: + type: object + required: + - timing + - customPlan + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + For changing a subscription, the accepted values depend on the subscription configuration. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + example: '2023-01-01T01:01:01.001Z' + customPlan: + allOf: + - $ref: '#/components/schemas/CustomPlanInput' + description: The custom plan description which defines the Subscription. + description: Change a custom subscription. + CustomSubscriptionCreate: + type: object + required: + - customPlan + properties: + customPlan: + allOf: + - $ref: '#/components/schemas/CustomPlanInput' + description: The custom plan description which defines the Subscription. + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + The default is immediate. + default: immediate + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the customer. Provide either the key or ID. Has presedence over the key. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerKey: + type: string + minLength: 1 + maxLength: 256 + description: The key of the customer. Provide either the key or ID. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + example: '2023-01-01T01:01:01.001Z' + description: Create a custom subscription. + title: Create custom + Customer: + type: object + required: + - id + - name + - createdAt + - updatedAt + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 256 + description: |- + An optional unique key of the customer. + Either key or usageAttribution.subjectKeys must be provided. + Useful to reference the customer in external systems. + For example, your database ID. + title: Key + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: |- + Mapping to attribute metered usage to the customer + Either key or usageAttribution.subjectKeys must be provided. + title: Usage Attribution + primaryEmail: + type: string + description: The primary email address of the customer. + title: Primary Email + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency of the customer. + Used for billing, tax and invoicing. + title: Currency + billingAddress: + allOf: + - $ref: '#/components/schemas/Address' + description: |- + The billing address of the customer. + Used for tax and invoicing. + title: Billing Address + currentSubscriptionId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the Subscription if the customer has one. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: Current Subscription ID + readOnly: true + subscriptions: + type: array + items: + $ref: '#/components/schemas/Subscription' + description: |- + The subscriptions of the customer. + Only with the `subscriptions` expand option. + title: Subscriptions + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + description: A customer object. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + name: ACME Inc. + usageAttribution: + subjectKeys: + - my_subject_key + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + CustomerAccess: + type: object + required: + - entitlements + properties: + entitlements: + type: object + additionalProperties: + $ref: '#/components/schemas/EntitlementValue' + description: |- + Map of entitlements the customer has access to. + The key is the feature key, the value is the entitlement value + the entitlement ID. + readOnly: true + description: CustomerAccess describes what features the customer has access to. + CustomerAppData: + type: object + oneOf: + - $ref: '#/components/schemas/StripeCustomerAppData' + - $ref: '#/components/schemas/SandboxCustomerAppData' + - $ref: '#/components/schemas/CustomInvoicingCustomerAppData' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeCustomerAppData' + sandbox: '#/components/schemas/SandboxCustomerAppData' + custom_invoicing: '#/components/schemas/CustomInvoicingCustomerAppData' + description: |- + CustomerAppData + Stores the app specific data for the customer. + One of: stripe, sandbox, custom_invoicing + CustomerAppDataCreateOrUpdateItem: + type: object + oneOf: + - $ref: '#/components/schemas/StripeCustomerAppDataCreateOrUpdateItem' + - $ref: '#/components/schemas/SandboxCustomerAppData' + - $ref: '#/components/schemas/CustomInvoicingCustomerAppData' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeCustomerAppDataCreateOrUpdateItem' + sandbox: '#/components/schemas/SandboxCustomerAppData' + custom_invoicing: '#/components/schemas/CustomInvoicingCustomerAppData' + description: |- + CustomerAppData + Stores the app specific data for the customer. + One of: stripe, sandbox, custom_invoicing + CustomerAppDataPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/CustomerAppData' + description: The items in the current page. + description: Paginated response + CustomerCreate: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 256 + description: |- + An optional unique key of the customer. + Either key or usageAttribution.subjectKeys must be provided. + Useful to reference the customer in external systems. + For example, your database ID. + title: Key + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: |- + Mapping to attribute metered usage to the customer + Either key or usageAttribution.subjectKeys must be provided. + title: Usage Attribution + primaryEmail: + type: string + description: The primary email address of the customer. + title: Primary Email + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency of the customer. + Used for billing, tax and invoicing. + title: Currency + billingAddress: + allOf: + - $ref: '#/components/schemas/Address' + description: |- + The billing address of the customer. + Used for tax and invoicing. + title: Billing Address + description: Resource create operation model. + CustomerExpand: + type: string + enum: + - subscriptions + description: CustomerExpand specifies the parts of the customer to expand in the list output. + CustomerId: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Create Stripe checkout session with customer ID. + CustomerKey: + type: object + required: + - key + properties: + key: + type: string + description: Create Stripe checkout session with customer key. + CustomerOrderBy: + type: string + enum: + - id + - name + - createdAt + description: Order by options for customers. + CustomerPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Customer' + description: The items in the current page. + description: Paginated response + CustomerReplaceUpdate: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 256 + description: |- + An optional unique key of the customer. + Either key or usageAttribution.subjectKeys must be provided. + Useful to reference the customer in external systems. + For example, your database ID. + title: Key + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: |- + Mapping to attribute metered usage to the customer + Either key or usageAttribution.subjectKeys must be provided. + title: Usage Attribution + primaryEmail: + type: string + description: The primary email address of the customer. + title: Primary Email + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency of the customer. + Used for billing, tax and invoicing. + title: Currency + billingAddress: + allOf: + - $ref: '#/components/schemas/Address' + description: |- + The billing address of the customer. + Used for tax and invoicing. + title: Billing Address + description: Resource update operation model. + CustomerSubscriptionOrderBy: + type: string + enum: + - activeFrom + - activeTo + description: Order by options for customer subscriptions. + CustomerUsageAttribution: + type: object + required: + - subjectKeys + properties: + subjectKeys: + type: array + items: + type: string + minLength: 1 + description: SubjectKey is a key that is used to identify a subject. + minItems: 0 + description: |- + The subjects that are attributed to the customer. + Can be empty when no subjects are associated with the customer. + title: SubjectKeys + description: |- + Mapping to attribute metered usage to the customer. + One customer can have zero or more subjects, + but one subject can only belong to one customer. + DiscountPercentage: + type: object + required: + - percentage + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + minimum: 0 + maximum: 100 + description: The percentage of the discount. + title: Percentage + description: Percentage discount. + DiscountReasonMaximumSpend: + type: object + required: + - type + properties: + type: + type: string + enum: + - maximum_spend + description: The reason for the discount is a maximum spend. + DiscountReasonRatecardPercentage: + type: object + required: + - type + - percentage + properties: + type: + type: string + enum: + - ratecard_percentage + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + minimum: 0 + maximum: 100 + description: The percentage of the discount. + title: Percentage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: The reason for the discount is a ratecard percentage. + DiscountReasonRatecardUsage: + type: object + required: + - type + - quantity + properties: + type: + type: string + enum: + - ratecard_usage + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the usage discount. + + Must be positive. + title: Usage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: The reason for the discount is a ratecard usage. + DiscountUsage: + type: object + required: + - quantity + properties: + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the usage discount. + + Must be positive. + title: Usage + description: |- + Usage discount. + + Usage discount means that the first N items are free. From billing perspective + this means that any usage on a specific feature is considered 0 until this discount + is exhausted. + Discounts: + type: object + properties: + percentage: + allOf: + - $ref: '#/components/schemas/DiscountPercentage' + description: The percentage discount. + usage: + allOf: + - $ref: '#/components/schemas/DiscountUsage' + description: The usage discount. + description: Discount by type on a price + DynamicPriceWithCommitments: + type: object + required: + - type + properties: + type: + type: string + enum: + - dynamic + description: The type of the price. + multiplier: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The multiplier to apply to the base price to get the dynamic price. + + Examples: + - 0.0: the price is zero + - 0.5: the price is 50% of the base price + - 1.0: the price is the same as the base price + - 1.5: the price is 150% of the base price + title: The multiplier to apply to the base price to get the dynamic price + default: '1' + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Dynamic price with spend commitments. + EditSubscriptionAddItem: + type: object + required: + - op + - phaseKey + - rateCard + properties: + op: + type: string + enum: + - add_item + phaseKey: + type: string + rateCard: + $ref: '#/components/schemas/RateCard' + description: Add a new item to a phase. + EditSubscriptionAddPhase: + type: object + required: + - op + - phase + properties: + op: + type: string + enum: + - add_phase + phase: + $ref: '#/components/schemas/SubscriptionPhaseCreate' + description: Add a new phase + EditSubscriptionRemoveItem: + type: object + required: + - op + - phaseKey + - itemKey + properties: + op: + type: string + enum: + - remove_item + phaseKey: + type: string + itemKey: + type: string + description: Remove an item from a phase. + EditSubscriptionRemovePhase: + type: object + required: + - op + - phaseKey + - shift + properties: + op: + type: string + enum: + - remove_phase + phaseKey: + type: string + shift: + $ref: '#/components/schemas/RemovePhaseShifting' + description: Remove a phase + EditSubscriptionStretchPhase: + type: object + required: + - op + - phaseKey + - extendBy + properties: + op: + type: string + enum: + - stretch_phase + phaseKey: + type: string + extendBy: + type: string + format: duration + description: Stretch a phase + EditSubscriptionUnscheduleEdit: + type: object + required: + - op + properties: + op: + type: string + enum: + - unschedule_edit + description: Unschedules any edits from the current phase. + Entitlement: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMetered' + - $ref: '#/components/schemas/EntitlementStatic' + - $ref: '#/components/schemas/EntitlementBoolean' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMetered' + static: '#/components/schemas/EntitlementStatic' + boolean: '#/components/schemas/EntitlementBoolean' + description: |- + Entitlement templates are used to define the entitlements of a plan. + Features are omitted from the entitlement template, as they are defined in the rate card. + deprecated: true + EntitlementBoolean: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - subjectKey + - featureKey + - featureId + properties: + type: + type: string + enum: + - boolean + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + description: Entitlement template of a boolean entitlement. + deprecated: true + EntitlementBooleanCreateInputs: + type: object + required: + - type + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + type: + type: string + enum: + - boolean + description: Create inputs for boolean entitlement + deprecated: true + EntitlementBooleanV2: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - featureKey + - featureId + - customerId + properties: + type: + type: string + enum: + - boolean + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: Entitlement template of a boolean entitlement. + EntitlementCreateInputs: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMeteredCreateInputs' + - $ref: '#/components/schemas/EntitlementStaticCreateInputs' + - $ref: '#/components/schemas/EntitlementBooleanCreateInputs' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMeteredCreateInputs' + static: '#/components/schemas/EntitlementStaticCreateInputs' + boolean: '#/components/schemas/EntitlementBooleanCreateInputs' + description: Create inputs for entitlement + EntitlementGrant: + type: object + required: + - createdAt + - updatedAt + - amount + - effectiveAt + - expiration + - id + - entitlementId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + entitlementId: + type: string + description: The unique entitlement ULID that the grant is associated with. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + nextRecurrence: + type: string + format: date-time + description: The next time the grant will recurr. + example: '2023-01-01T01:01:01.001Z' + expiresAt: + type: string + format: date-time + description: The time the grant expires. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + voidedAt: + type: string + format: date-time + description: The time the grant was voided. + example: '2023-01-01T01:01:01.001Z' + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The recurrence period of the grant. + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Grant annotations + example: + issueAfterReset: true + description: The grant. + deprecated: true + EntitlementGrantCreateInput: + type: object + required: + - amount + - effectiveAt + - expiration + properties: + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The subject of the grant. + description: The grant creation input. + deprecated: true + EntitlementGrantCreateInputV2: + type: object + required: + - amount + - effectiveAt + properties: + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The subject of the grant. + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Grant annotations + example: + internal_reference: internal_reference + description: The grant creation input. + EntitlementGrantV2: + type: object + required: + - createdAt + - updatedAt + - amount + - effectiveAt + - id + - entitlementId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Grant annotations + example: + internal_reference: internal_reference + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + entitlementId: + type: string + description: The unique entitlement ULID that the grant is associated with. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + nextRecurrence: + type: string + format: date-time + description: The next time the grant will recurr. + example: '2023-01-01T01:01:01.001Z' + expiresAt: + type: string + format: date-time + description: The time the grant expires. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + voidedAt: + type: string + format: date-time + description: The time the grant was voided. + example: '2023-01-01T01:01:01.001Z' + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The recurrence period of the grant. + description: The grant. + EntitlementMetered: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - subjectKey + - featureKey + - featureId + - lastReset + - currentUsagePeriod + - measureUsageFrom + - usagePeriod + properties: + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + isUnlimited: + type: boolean + description: Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + deprecated: true + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + default: 1 + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + lastReset: + type: string + format: date-time + description: The time the last reset happened. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + readOnly: true + measureUsageFrom: + type: string + format: date-time + description: The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: THe usage period of the entitlement. + readOnly: true + description: |- + Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + deprecated: true + EntitlementMeteredCreateInputs: + type: object + required: + - type + - usagePeriod + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + isUnlimited: + type: boolean + description: Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + deprecated: true + default: false + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + measureUsageFrom: + allOf: + - $ref: '#/components/schemas/MeasureUsageFrom' + description: Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + default: 1 + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + description: Create inpurs for metered entitlement + deprecated: true + EntitlementMeteredV2: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - featureKey + - featureId + - lastReset + - currentUsagePeriod + - measureUsageFrom + - usagePeriod + - customerId + properties: + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + deprecated: true + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + deprecated: true + default: 1 + issue: + allOf: + - $ref: '#/components/schemas/IssueAfterReset' + description: Issue after reset + title: Issue after reset + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + lastReset: + type: string + format: date-time + description: The time the last reset happened. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + readOnly: true + measureUsageFrom: + type: string + format: date-time + description: The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: THe usage period of the entitlement. + readOnly: true + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: |- + Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + EntitlementMeteredV2CreateInputs: + type: object + required: + - type + - usagePeriod + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + measureUsageFrom: + allOf: + - $ref: '#/components/schemas/MeasureUsageFrom' + description: Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + deprecated: true + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + deprecated: true + default: 1 + issue: + allOf: + - $ref: '#/components/schemas/IssueAfterReset' + description: Issue after reset + title: Issue after reset + grants: + type: array + items: + $ref: '#/components/schemas/EntitlementGrantCreateInputV2' + description: Grants + title: Grants + description: Create inputs for metered entitlement + EntitlementOrderBy: + type: string + enum: + - createdAt + - updatedAt + description: Order by options for entitlements. + EntitlementPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Entitlement' + description: The items in the current page. + description: Paginated response + EntitlementStatic: + type: object + required: + - type + - config + - createdAt + - updatedAt + - activeFrom + - id + - subjectKey + - featureKey + - featureId + properties: + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + description: A static entitlement. + deprecated: true + EntitlementStaticCreateInputs: + type: object + required: + - type + - config + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + description: Create inputs for static entitlement + deprecated: true + EntitlementStaticV2: + type: object + required: + - type + - config + - createdAt + - updatedAt + - activeFrom + - id + - featureKey + - featureId + - customerId + properties: + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: A static entitlement. + EntitlementType: + type: string + enum: + - metered + - boolean + - static + description: Type of the entitlement. + deprecated: true + x-go-type: string + EntitlementV2: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMeteredV2' + - $ref: '#/components/schemas/EntitlementStaticV2' + - $ref: '#/components/schemas/EntitlementBooleanV2' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMeteredV2' + static: '#/components/schemas/EntitlementStaticV2' + boolean: '#/components/schemas/EntitlementBooleanV2' + description: |- + Entitlement templates are used to define the entitlements of a plan. + Features are omitted from the entitlement template, as they are defined in the rate card. + EntitlementV2CreateInputs: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMeteredV2CreateInputs' + - $ref: '#/components/schemas/EntitlementStaticCreateInputs' + - $ref: '#/components/schemas/EntitlementBooleanCreateInputs' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMeteredV2CreateInputs' + static: '#/components/schemas/EntitlementStaticCreateInputs' + boolean: '#/components/schemas/EntitlementBooleanCreateInputs' + description: Create inputs for entitlement + EntitlementV2PaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/EntitlementV2' + description: The items in the current page. + description: Paginated response + EntitlementValue: + type: object + required: + - hasAccess + properties: + hasAccess: + type: boolean + description: Whether the subject has access to the feature. Shared accross all entitlement types. + example: true + readOnly: true + balance: + type: number + format: double + description: Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + example: 100 + readOnly: true + usage: + type: number + format: double + description: Only available for metered entitlements. Returns the total feature usage in the current period. + example: 50 + readOnly: true + overage: + type: number + format: double + description: Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + example: 0 + readOnly: true + totalAvailableGrantAmount: + type: number + format: double + description: Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + example: 100 + readOnly: true + config: + type: string + description: Only available for static entitlements. The JSON parsable config of the entitlement. + example: '{ key: "value" }' + readOnly: true + description: Entitlements are the core of OpenMeter access management. They define access to features for subjects. Entitlements can be metered, boolean, or static. + EntitlementValueV2: + type: object + required: + - hasAccess + properties: + hasAccess: + type: boolean + description: Whether the subject has access to the feature. Shared accross all entitlement types. + example: true + readOnly: true + balance: + type: number + format: double + description: Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + example: 100 + readOnly: true + usage: + type: number + format: double + description: Only available for metered entitlements. Returns the total feature usage in the current period. + example: 50 + readOnly: true + overage: + type: number + format: double + description: Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + example: 0 + readOnly: true + totalAvailableGrantAmount: + type: number + format: double + description: Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + example: 100 + readOnly: true + config: + type: string + description: Only available for static entitlements. The JSON parsable config of the entitlement. + example: '{ key: "value" }' + readOnly: true + grantBalances: + type: object + additionalProperties: + type: number + format: double + description: |- + Only available for metered entitlements. The closing balance of each active grant at query time. + The key is the grant ID and the value is the remaining balance. + readOnly: true + description: EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 APIs. + ErrorExtension: + type: object + required: + - field + - code + - message + properties: + field: + type: string + description: The path to the field. + example: addons/pro/ratecards/token/featureKey + readOnly: true + code: + type: string + description: The machine readable description of the error. + example: invalid_feature_key + readOnly: true + message: + type: string + description: The human readable description of the error. + example: not found feature by key + readOnly: true + additionalProperties: {} + description: Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode] + Event: + type: object + required: + - id + - source + - specversion + - type + - subject + properties: + id: + type: string + minLength: 1 + description: Identifies the event. + example: 5c10fade-1c9e-4d6c-8275-c52c36731d3c + source: + type: string + minLength: 1 + format: uri-reference + description: Identifies the context in which an event happened. + example: service-name + specversion: + type: string + minLength: 1 + description: The version of the CloudEvents specification which the event uses. + example: '1.0' + default: '1.0' + type: + type: string + minLength: 1 + description: Contains a value describing the type of event related to the originating occurrence. + example: com.example.someevent + datacontenttype: + type: string + enum: + - application/json + nullable: true + description: Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP. + example: application/json + dataschema: + type: string + format: uri + nullable: true + minLength: 1 + description: Identifies the schema that data adheres to. + subject: + type: string + minLength: 1 + description: Describes the subject of the event in the context of the event producer (identified by source). + example: customer-id + time: + type: string + format: date-time + description: Timestamp of when the occurrence happened. Must adhere to RFC 3339. + example: '2023-01-01T01:01:01.001Z' + nullable: true + data: + type: object + additionalProperties: {} + nullable: true + description: |- + The event payload. + Optional, if present it must be a JSON object. + description: |- + CloudEvents Specification JSON Schema + + Optional properties are nullable according to the CloudEvents specification: + OPTIONAL not omitted attributes MAY be represented as a null JSON value. + example: + id: 5c10fade-1c9e-4d6c-8275-c52c36731d3c + source: service-name + specversion: '1.0' + type: prompt + subject: customer-id + time: '2023-01-01T01:01:01.001Z' + x-go-type-import: + path: github.com/cloudevents/sdk-go/v2/event + x-go-type: event.Event + EventDeliveryAttemptResponse: + type: object + required: + - body + - durationMs + properties: + statusCode: + type: integer + description: Status code of the response if available. + title: Status Code + readOnly: true + body: + type: string + description: The body of the response. + title: Response Body + readOnly: true + durationMs: + type: integer + description: The duration of the response in milliseconds. + title: Response Duration + readOnly: true + url: + type: string + description: URL where the event was sent in case of notification channel with webhook type. + title: URL + readOnly: true + description: The response of the event delivery attempt. + ExpirationDuration: + type: string + enum: + - HOUR + - DAY + - WEEK + - MONTH + - YEAR + description: The expiration duration enum + ExpirationPeriod: + type: object + required: + - duration + - count + properties: + duration: + allOf: + - $ref: '#/components/schemas/ExpirationDuration' + description: The unit of time for the expiration period. + count: + type: integer + format: uint32 + minimum: 1 + maximum: 1000 + description: The number of time units in the expiration period. + example: 12 + description: The grant expiration definition + Feature: + type: object + required: + - createdAt + - updatedAt + - key + - name + - id + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + archivedAt: + type: string + format: date-time + description: Timestamp of when the resource was archived. + example: '2023-01-01T01:01:01.001Z' + title: Archival Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: The unique key of the feature + name: + type: string + title: The human-readable name of the feature + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + title: Optional metadata + example: + key: value + meterSlug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: Meter slug + example: tokens_total + meterGroupByFilters: + type: object + additionalProperties: + type: string + description: |- + Optional meter group by filters. + Useful if the meter scope is broader than what feature tracks. + Example scenario would be a meter tracking all token use with groupBy fields for the model, + then the feature could filter for model=gpt-4. + + ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + title: Meter group by filters + deprecated: true + example: + model: gpt-4 + type: input + advancedMeterGroupByFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/FilterString' + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + title: Advanced meter group by filters + example: + model: + $in: + - gpt-4 + - gpt-4o + type: + $eq: input + unitCost: + allOf: + - $ref: '#/components/schemas/FeatureUnitCost' + description: |- + Optional per-unit cost configuration. + Use "manual" for a fixed per-unit cost, or "llm" to look up cost + from the LLM cost database based on meter group-by properties. + title: Unit cost + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + description: |- + Represents a feature that can be enabled or disabled for a plan. + Used both for product catalog and entitlements. + FeatureCreateInputs: + type: object + required: + - key + - name + properties: + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: The unique key of the feature + name: + type: string + title: The human-readable name of the feature + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + title: Optional metadata + example: + key: value + meterSlug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: Meter slug + example: tokens_total + meterGroupByFilters: + type: object + additionalProperties: + type: string + description: |- + Optional meter group by filters. + Useful if the meter scope is broader than what feature tracks. + Example scenario would be a meter tracking all token use with groupBy fields for the model, + then the feature could filter for model=gpt-4. + + ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + title: Meter group by filters + deprecated: true + example: + model: gpt-4 + type: input + advancedMeterGroupByFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/FilterString' + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + title: Advanced meter group by filters + example: + model: + $in: + - gpt-4 + - gpt-4o + type: + $eq: input + unitCost: + allOf: + - $ref: '#/components/schemas/FeatureUnitCost' + description: |- + Optional per-unit cost configuration. + Use "manual" for a fixed per-unit cost, or "llm" to look up cost + from the LLM cost database based on meter group-by properties. + title: Unit cost + description: |- + Represents a feature that can be enabled or disabled for a plan. + Used both for product catalog and entitlements. + FeatureLLMUnitCost: + type: object + required: + - type + properties: + type: + type: string + enum: + - llm + providerProperty: + type: string + description: |- + Meter group-by property that holds the LLM provider. + Use this when the meter has a group-by dimension for provider. + Mutually exclusive with `provider`. + title: Provider property + provider: + type: string + description: |- + Static LLM provider value (e.g., "openai", "anthropic"). + Use this when the feature tracks a single provider. + Mutually exclusive with `providerProperty`. + title: Provider + modelProperty: + type: string + description: |- + Meter group-by property that holds the model ID. + Use this when the meter has a group-by dimension for model. + Mutually exclusive with `model`. + title: Model property + model: + type: string + description: |- + Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). + Use this when the feature tracks a single model. + Mutually exclusive with `modelProperty`. + title: Model + tokenTypeProperty: + type: string + description: |- + Meter group-by property that holds the token type. + Use this when the meter has a group-by dimension for token type. + Mutually exclusive with `tokenType`. + title: Token type property + tokenType: + type: string + description: |- + Static token type value. + Use this when the feature tracks a single token type (e.g., only input tokens). + Expected values: input, output, cache_read, reasoning, cache_write, request, response. + `request` is an alias for `input`, `response` is an alias for `output`. + Mutually exclusive with `tokenTypeProperty`. + title: Token type + pricing: + allOf: + - $ref: '#/components/schemas/FeatureLLMUnitCostPricing' + description: |- + Resolved per-token pricing from the LLM cost database. + Only populated in responses when the feature's meter group-by filters + specify exact provider and model values. + title: Resolved pricing + readOnly: true + description: |- + LLM cost lookup configuration. + Maps meter group-by dimensions to LLM cost database fields. + FeatureLLMUnitCostPricing: + type: object + required: + - inputPerToken + - outputPerToken + properties: + inputPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per input token in USD. + title: Input per token + outputPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per output token in USD. + title: Output per token + cacheReadPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per cache read token in USD. + title: Cache read per token + reasoningPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per reasoning token in USD. + title: Reasoning per token + cacheWritePerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per cache write token in USD. + title: Cache write per token + description: Resolved per-token pricing from the LLM cost database. + FeatureManualUnitCost: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - manual + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Fixed per-unit cost amount in USD. + description: A fixed per-unit cost amount. + FeatureMeta: + type: object + required: + - id + - key + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Unique identifier of a feature. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Feature Unique Identifier + key: + type: string + description: |- + The key is an immutable unique identifier of the feature used throughout the API, + for example when interacting with a subject's entitlements. + title: Feature Key + example: gpt4_tokens + description: Limited representation of a feature resource which includes only its unique identifiers (id, key). + FeatureOrderBy: + type: string + enum: + - id + - key + - name + - createdAt + - updatedAt + description: Order by options for features. + FeaturePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Feature' + description: The items in the current page. + description: Paginated response + FeatureUnitCost: + type: object + oneOf: + - $ref: '#/components/schemas/FeatureManualUnitCost' + - $ref: '#/components/schemas/FeatureLLMUnitCost' + discriminator: + propertyName: type + mapping: + manual: '#/components/schemas/FeatureManualUnitCost' + llm: '#/components/schemas/FeatureLLMUnitCost' + description: |- + Per-unit cost configuration for a feature. + Either a fixed manual amount or a dynamic LLM cost lookup. + FilterIDExact: + type: object + properties: + $in: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + nullable: true + description: The field must be in the provided list of values. + x-omitempty: true + description: A filter for a ID (ULID) field allowing only equality or inclusion. + FilterString: + type: object + properties: + $eq: + type: string + nullable: true + description: The field must be equal to the provided value. + x-omitempty: true + $ne: + type: string + nullable: true + description: The field must not be equal to the provided value. + x-omitempty: true + $in: + type: array + items: + type: string + nullable: true + description: The field must be in the provided list of values. + x-omitempty: true + $nin: + type: array + items: + type: string + nullable: true + description: The field must not be in the provided list of values. + x-omitempty: true + $like: + type: string + nullable: true + description: The field must match the provided value. + x-omitempty: true + $nlike: + type: string + nullable: true + description: The field must not match the provided value. + x-omitempty: true + $ilike: + type: string + nullable: true + description: The field must match the provided value, ignoring case. + x-omitempty: true + $nilike: + type: string + nullable: true + description: The field must not match the provided value, ignoring case. + x-omitempty: true + $gt: + type: string + nullable: true + description: The field must be greater than the provided value. + x-omitempty: true + $gte: + type: string + nullable: true + description: The field must be greater than or equal to the provided value. + x-omitempty: true + $lt: + type: string + nullable: true + description: The field must be less than the provided value. + x-omitempty: true + $lte: + type: string + nullable: true + description: The field must be less than or equal to the provided value. + x-omitempty: true + $and: + type: array + items: + $ref: '#/components/schemas/FilterString' + nullable: true + description: Provide a list of filters to be combined with a logical AND. + x-omitempty: true + $or: + type: array + items: + $ref: '#/components/schemas/FilterString' + nullable: true + description: Provide a list of filters to be combined with a logical OR. + x-omitempty: true + description: A filter for a string field. + FilterTime: + type: object + properties: + $gt: + type: string + format: date-time + nullable: true + description: The field must be greater than the provided value. + x-omitempty: true + $gte: + type: string + format: date-time + nullable: true + description: The field must be greater than or equal to the provided value. + x-omitempty: true + $lt: + type: string + format: date-time + nullable: true + description: The field must be less than the provided value. + x-omitempty: true + $lte: + type: string + format: date-time + nullable: true + description: The field must be less than or equal to the provided value. + x-omitempty: true + $and: + type: array + items: + $ref: '#/components/schemas/FilterTime' + nullable: true + description: Provide a list of filters to be combined with a logical AND. + x-omitempty: true + $or: + type: array + items: + $ref: '#/components/schemas/FilterTime' + nullable: true + description: Provide a list of filters to be combined with a logical OR. + x-omitempty: true + description: A filter for a time field. + FlatPrice: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - flat + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the flat price. + description: Flat price. + FlatPriceWithPaymentTerm: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - flat + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the flat price. + paymentTerm: + allOf: + - $ref: '#/components/schemas/PricePaymentTerm' + description: |- + The payment term of the flat price. + Defaults to in advance. + default: in_advance + description: Flat price with payment term. + ForbiddenProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server understood the request but refuses to authorize it. + GatewayTimeoutProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. + GrantBurnDownHistorySegment: + type: object + required: + - period + - usage + - overage + - balanceAtStart + - grantBalancesAtStart + - balanceAtEnd + - grantBalancesAtEnd + - grantUsages + properties: + period: + allOf: + - $ref: '#/components/schemas/Period' + description: The period of the segment. + usage: + type: number + format: double + description: The total usage of the grant in the period. + example: 100 + readOnly: true + overage: + type: number + format: double + description: Overuse that wasn't covered by grants. + example: 100 + readOnly: true + balanceAtStart: + type: number + format: double + description: entitlement balance at the start of the period. + example: 100 + readOnly: true + grantBalancesAtStart: + type: object + additionalProperties: + type: number + format: double + description: 'The balance breakdown of each active grant at the start of the period: GrantID: Balance' + example: + 01G65Z755AFWAKHE12NY0CQ9FH: 100 + readOnly: true + balanceAtEnd: + type: number + format: double + description: The entitlement balance at the end of the period. + example: 100 + readOnly: true + grantBalancesAtEnd: + type: object + additionalProperties: + type: number + format: double + description: 'The balance breakdown of each active grant at the end of the period: GrantID: Balance' + example: + 01G65Z755AFWAKHE12NY0CQ9FH: 100 + readOnly: true + grantUsages: + type: array + items: + $ref: '#/components/schemas/GrantUsageRecord' + description: Which grants were actually burnt down in the period and by what amount. + readOnly: true + description: |- + A segment of the grant burn down history. + + A given segment represents the usage of a grant between events that changed either the grant burn down priority order or the usag period. + GrantOrderBy: + type: string + enum: + - id + - createdAt + - updatedAt + description: Order by options for grants. + GrantPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/EntitlementGrant' + description: The items in the current page. + description: Paginated response + GrantUsageRecord: + type: object + required: + - grantId + - usage + properties: + grantId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The id of the grant + example: 01G65Z755AFWAKHE12NY0CQ9FH + usage: + type: number + format: double + description: The usage in the period + example: 100 + description: Usage Record + GrantV2PaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/EntitlementGrantV2' + description: The items in the current page. + description: Paginated response + IDResource: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + description: IDResource is a resouce with an ID. + IngestEventsBody: + anyOf: + - $ref: '#/components/schemas/Event' + - type: array + items: + $ref: '#/components/schemas/Event' + description: |- + The body of the events request. + Either a single event or a batch of events. + IngestedEvent: + type: object + required: + - event + - ingestedAt + - storedAt + properties: + event: + allOf: + - $ref: '#/components/schemas/Event' + description: The original event ingested. + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID if the event is associated with a customer. + example: 01G65Z755AFWAKHE12NY0CQ9FH + validationError: + type: string + description: The validation error if the event failed validation. + ingestedAt: + type: string + format: date-time + description: The date and time the event was ingested. + example: '2023-01-01T01:01:01.001Z' + storedAt: + type: string + format: date-time + description: The date and time the event was stored. + example: '2023-01-01T01:01:01.001Z' + description: An ingested event with optional validation error. + example: + event: + id: 5c10fade-1c9e-4d6c-8275-c52c36731d3c + source: service-name + specversion: '1.0' + type: prompt + subject: customer-id + time: '2023-01-01T01:01:01.001Z' + ingestedAt: '2023-01-01T01:01:01.001Z' + storedAt: '2023-01-01T01:01:02.001Z' + IngestedEventCursorPaginatedResponse: + type: object + required: + - items + properties: + items: + type: array + items: + $ref: '#/components/schemas/IngestedEvent' + maxItems: 100 + description: The items in the response. + nextCursor: + type: string + description: The cursor of the last item in the list. + description: A response for cursor pagination. + InstallMethod: + type: string + enum: + - with_oauth2 + - with_api_key + - no_credentials_required + description: Install method of the application. + InternalServerErrorProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + Invoice: + type: object + required: + - id + - createdAt + - updatedAt + - type + - supplier + - customer + - number + - currency + - totals + - status + - statusDetails + - workflow + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/InvoiceType' + description: |- + Type of the invoice. + + The type of invoice determines the purpose of the invoice and how it should be handled. + + Supported types: + - standard: A regular commercial invoice document between a supplier and customer. + - credit_note: Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + readOnly: true + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The taxable entity supplying the goods or services. + customer: + allOf: + - $ref: '#/components/schemas/BillingInvoiceCustomerExtendedDetails' + description: Legal entity receiving the goods or services. + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: |- + Number specifies the human readable key used to reference this Invoice. + + The invoice number can change in the draft phases, as we are allocating temporary draft + invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + + Please note that the number is (depending on the upstream settings) either unique for the + whole organization or unique for the customer, or in multi (stripe) account setups unique for the + account. + readOnly: true + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency for all invoice line items. + + Multi currency invoices are not supported yet. + preceding: + type: array + items: + $ref: '#/components/schemas/InvoiceDocumentRef' + description: Key information regarding previous invoices and potentially details as to why they were corrected. + readOnly: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Summary of all the invoice totals, including taxes (calculated). + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceStatus' + description: |- + The status of the invoice. + + This field only conatins a simplified status, for more detailed information use the statusDetails field. + readOnly: true + statusDetails: + allOf: + - $ref: '#/components/schemas/InvoiceStatusDetails' + description: The details of the current invoice status. + readOnly: true + issuedAt: + type: string + format: date-time + description: |- + The time the invoice was issued. + + Depending on the status of the invoice this can mean multiple things: + - draft, gathering: The time the invoice will be issued based on the workflow settings. + - issued: The time the invoice was issued. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + draftUntil: + type: string + format: date-time + description: |- + The time until the invoice is in draft status. + + On draft invoice creation it is calculated from the workflow settings. + + If manual approval is required, the draftUntil time is set. + example: '2023-01-01T01:01:01.001Z' + quantitySnapshotedAt: + type: string + format: date-time + description: The time when the quantity snapshots on the invoice lines were taken. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + collectionAt: + type: string + format: date-time + description: The time when the invoice will be/has been collected. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + dueAt: + type: string + format: date-time + description: Due time of the fulfillment of the invoice (if available). + example: '2023-01-01T01:01:01.001Z' + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: The period the invoice covers. If the invoice has no line items, it's not set. + voidedAt: + type: string + format: date-time + description: |- + The time the invoice was voided. + + If the invoice was voided, this field will be set to the time the invoice was voided. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + sentToCustomerAt: + type: string + format: date-time + description: The time the invoice was sent to customer. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + workflow: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowSettings' + description: |- + The workflow associated with the invoice. + + It is always a snapshot of the workflow settings at the time of invoice creation. The + field is optional as it should be explicitly requested with expand options. + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceLine' + description: List of invoice lines representing each of the items sold to the customer. + payment: + allOf: + - $ref: '#/components/schemas/InvoicePaymentTerms' + description: Information on when, how, and to whom the invoice should be paid. + readOnly: true + validationIssues: + type: array + items: + $ref: '#/components/schemas/ValidationIssue' + description: Validation issues reported by the invoice workflow. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + description: Invoice represents an invoice in the system. + InvoiceAppExternalIds: + type: object + properties: + invoicing: + type: string + description: The external ID of the invoice in the invoicing app if available. + readOnly: true + tax: + type: string + description: The external ID of the invoice in the tax app if available. + readOnly: true + payment: + type: string + description: The external ID of the invoice in the payment app if available. + readOnly: true + description: InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + InvoiceAvailableActionDetails: + type: object + required: + - resultingState + properties: + resultingState: + type: string + description: |- + The state the invoice will reach if the action is activated and + all intermediate steps are successful. + + For example advancing a draft_created invoice will result in a draft_manual_approval_needed invoice. + readOnly: true + description: |- + InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + non-gathering invoices. + InvoiceAvailableActionInvoiceDetails: + type: object + description: |- + InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + gathering invoices. + InvoiceAvailableActions: + type: object + properties: + advance: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Advance the invoice to the next status. + readOnly: true + approve: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Approve an invoice that requires manual approval. + readOnly: true + delete: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Delete the invoice (only non-issued invoices can be deleted). + readOnly: true + retry: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Retry an invoice issuing step that failed. + readOnly: true + snapshotQuantities: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Snapshot quantities for usage based line items. + readOnly: true + void: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Void an already issued invoice. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionInvoiceDetails' + description: Invoice a gathering invoice + readOnly: true + description: InvoiceAvailableActions represents the actions that can be performed on the invoice. + InvoiceDetailedLine: + type: object + required: + - name + - createdAt + - updatedAt + - id + - managedBy + - status + - currency + - totals + - period + - invoiceAt + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + managedBy: + allOf: + - $ref: '#/components/schemas/InvoiceLineManagedBy' + description: managedBy specifies if the line is manually added via the api or managed by OpenMeter. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceLineStatus' + description: |- + Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. + readOnly: true + discounts: + allOf: + - $ref: '#/components/schemas/InvoiceLineDiscounts' + description: |- + Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + readOnly: true + creditAllocations: + type: array + items: + $ref: '#/components/schemas/InvoiceLineCreditAllocation' + description: |- + Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceReference' + description: The invoice this item belongs to. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of this line. + taxes: + type: array + items: + $ref: '#/components/schemas/InvoiceLineTaxItem' + description: Taxes applied to the invoice totals. + readOnly: true + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Totals for this line. + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + subscription: + allOf: + - $ref: '#/components/schemas/InvoiceLineSubscriptionReference' + description: Subscription are the references to the subscritpions that this line is related to. + readOnly: true + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + deprecated: true + type: + type: string + enum: + - flat_fee + description: Type of the line. + deprecated: true + readOnly: true + perUnitAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Price of the item being sold. + deprecated: true + paymentTerm: + allOf: + - $ref: '#/components/schemas/PricePaymentTerm' + description: Payment term of the line. + deprecated: true + default: in_advance + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Quantity of the item being sold. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceDetailedLineRateCard' + description: The rate card that is used for this line. + category: + allOf: + - $ref: '#/components/schemas/InvoiceDetailedLineCostCategory' + description: Category of the flat fee. + default: regular + readOnly: true + description: InvoiceDetailedLine represents a line item that is sold to the customer as a manually added fee. + InvoiceDetailedLineCostCategory: + type: string + enum: + - regular + - commitment + description: |- + InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a + commitment. + InvoiceDetailedLineRateCard: + type: object + required: + - price + properties: + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + price: + type: object + allOf: + - $ref: '#/components/schemas/FlatPriceWithPaymentTerm' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + title: Price + example: + type: flat + amount: '100' + paymentTerm: in_arrears + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + Quantity of the item being sold. + + Default: 1 + discounts: + allOf: + - $ref: '#/components/schemas/BillingDiscounts' + description: The discounts that are applied to the line. + description: InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. + InvoiceDocumentRef: + type: object + allOf: + - $ref: '#/components/schemas/CreditNoteOriginalInvoiceRef' + description: InvoiceDocumentRef is used to describe a reference to an existing document (invoice). + InvoiceDocumentRefType: + type: string + enum: + - credit_note_original_invoice + description: InvoiceDocumentRefType defines the type of document that is being referenced. + InvoiceExpand: + type: string + enum: + - lines + - preceding + - workflow.apps + description: InvoiceExpand specifies the parts of the invoice to expand in the list output. + InvoiceGenericDocumentRef: + type: object + required: + - type + properties: + type: + allOf: + - $ref: '#/components/schemas/InvoiceDocumentRefType' + description: Type of the document referenced. + readOnly: true + reason: + type: string + description: Human readable description on why this reference is here or needs to be used. + readOnly: true + description: + type: string + description: Additional details about the document. + readOnly: true + description: |- + Omitted fields: + period: Tax period in which the referred document had an effect required by some tax regimes and formats. + stamps: Seals of approval from other organisations that may need to be listed. + ext: Extensions for additional codes that may be required. + title: InvoiceGenericDocumentRef is used to describe an existing document or a specific part of it's contents. + InvoiceLine: + type: object + required: + - name + - createdAt + - updatedAt + - id + - managedBy + - status + - currency + - totals + - period + - invoiceAt + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + managedBy: + allOf: + - $ref: '#/components/schemas/InvoiceLineManagedBy' + description: managedBy specifies if the line is manually added via the api or managed by OpenMeter. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceLineStatus' + description: |- + Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. + readOnly: true + discounts: + allOf: + - $ref: '#/components/schemas/InvoiceLineDiscounts' + description: |- + Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + readOnly: true + creditAllocations: + type: array + items: + $ref: '#/components/schemas/InvoiceLineCreditAllocation' + description: |- + Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceReference' + description: The invoice this item belongs to. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of this line. + taxes: + type: array + items: + $ref: '#/components/schemas/InvoiceLineTaxItem' + description: Taxes applied to the invoice totals. + readOnly: true + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Totals for this line. + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + subscription: + allOf: + - $ref: '#/components/schemas/InvoiceLineSubscriptionReference' + description: Subscription are the references to the subscritpions that this line is related to. + readOnly: true + type: + type: string + enum: + - usage_based + description: Type of the line. + deprecated: true + readOnly: true + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + children: + type: array + items: + $ref: '#/components/schemas/InvoiceDetailedLine' + description: The lines detailing the item or service sold. + readOnly: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the item being sold. + + Any usage discounts applied previously are deducted from this quantity. + readOnly: true + meteredQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity of the item that has been metered for the period before any discounts were applied. + readOnly: true + preLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the item used before this line's period. + + It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + + Any usage discounts applied previously are deducted from this quantity. + readOnly: true + meteredPreLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The metered quantity of the item used in before this line's period without any discounts applied. + + It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + readOnly: true + description: InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. + InvoiceLineAmountDiscount: + type: object + required: + - createdAt + - updatedAt + - id + - reason + - amount + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + reason: + allOf: + - $ref: '#/components/schemas/BillingDiscountReason' + description: Reason code. + readOnly: true + description: + type: string + description: Text description as to why the discount was applied. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Fixed discount amount to apply (calculated if percent present). + title: Amount in the currency of the invoice + readOnly: true + description: InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied before taxes. + InvoiceLineAppExternalIds: + type: object + properties: + invoicing: + type: string + description: The external ID of the invoice in the invoicing app if available. + readOnly: true + tax: + type: string + description: The external ID of the invoice in the tax app if available. + readOnly: true + description: InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + InvoiceLineCreditAllocation: + type: object + required: + - amount + properties: + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Amount allocated from credits. + title: Amount in the currency of the invoice + readOnly: true + description: + type: string + description: Text description as to why the credit was allocated. + readOnly: true + description: InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are applied. + InvoiceLineDiscounts: + type: object + properties: + amount: + type: array + items: + $ref: '#/components/schemas/InvoiceLineAmountDiscount' + description: |- + Amount based discounts applied to the line. + + Amount based discounts are deduced from the total price of the line. + usage: + type: array + items: + $ref: '#/components/schemas/InvoiceLineUsageDiscount' + description: |- + Usage based discounts applied to the line. + + Usage based discounts are deduced from the usage of the line before price calculations are applied. + description: InvoiceLineDiscounts represents the discounts applied to the invoice line by type. + InvoiceLineManagedBy: + type: string + enum: + - subscription + - system + - manual + description: InvoiceLineManagedBy specifies who manages the line. + InvoiceLineReplaceUpdate: + type: object + required: + - name + - period + - invoiceAt + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: |- + InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. + + This type makes ID optional to allow for creating new lines as part of the update. + InvoiceLineStatus: + type: string + enum: + - valid + - detailed + - split + description: Line status specifies the status of the line. + InvoiceLineSubscriptionReference: + type: object + required: + - subscription + - phase + - item + - billingPeriod + properties: + subscription: + allOf: + - $ref: '#/components/schemas/IDResource' + description: The subscription. + readOnly: true + phase: + allOf: + - $ref: '#/components/schemas/IDResource' + description: The phase of the subscription. + readOnly: true + item: + allOf: + - $ref: '#/components/schemas/IDResource' + description: The item this line is related to. + readOnly: true + billingPeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + The billing period of the subscription. In case the subscription item's billing period is different + from the subscription's billing period, this field will contain the billing period of the subscription itself. + + For example, in case of: + - A monthly billed subscription anchored to 2025-01-01 + - A subscription item billed daily + + An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed daily, but the subscription's billing period + will be 2025-01-01 to 2025-01-31. + readOnly: true + description: InvoiceLineSubscriptionReference contains the references to the subscription that this line is related to. + InvoiceLineTaxBehavior: + type: string + enum: + - inclusive + - exclusive + description: |- + InvoiceLineTaxBehavior details how the tax item is applied to the base amount. + + Inclusive means the tax is included in the base amount. + Exclusive means the tax is added to the base amount. + InvoiceLineTaxItem: + type: object + properties: + config: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax provider configuration. + readOnly: true + percent: + allOf: + - $ref: '#/components/schemas/Percentage' + description: |- + Percent defines the percentage set manually or determined from + the rate key (calculated if rate present). A nil percent implies that + this tax combo is **exempt** from tax.") + readOnly: true + surcharge: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Some countries require an additional surcharge (calculated if rate present). + readOnly: true + behavior: + allOf: + - $ref: '#/components/schemas/InvoiceLineTaxBehavior' + description: Is the tax item inclusive or exclusive of the base amount. + readOnly: true + description: TaxConfig stores the configuration for a tax line relative to an invoice line. + InvoiceLineUsageDiscount: + type: object + required: + - createdAt + - updatedAt + - id + - reason + - quantity + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + reason: + allOf: + - $ref: '#/components/schemas/BillingDiscountReason' + description: Reason code. + readOnly: true + description: + type: string + description: Text description as to why the discount was applied. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The usage to apply. + title: Usage quantity in the unit of the underlying meter + readOnly: true + preLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The usage discount already applied to the previous split lines. + + Only set if progressive billing is enabled and the line is a split line. + title: Usage quantity in the unit of the underlying meter + readOnly: true + description: |- + InvoiceLineUsageDiscount represents an usage-based discount applied to the line. + + The deduction is done before the pricing algorithm is applied. + InvoiceNumber: + type: string + minLength: 1 + maxLength: 256 + description: |- + InvoiceNumber is a unique identifier for the invoice, generated by the + invoicing app. + + The uniqueness depends on a lot of factors: + - app setting (unique per app or unique per customer) + - multiple app scenarios (multiple apps generating invoices with the same prefix) + example: INV-2024-01-01-01 + InvoiceOrderBy: + type: string + enum: + - customer.name + - issuedAt + - status + - createdAt + - updatedAt + - periodStart + description: InvoiceOrderBy specifies the ordering options for invoice listing. + InvoicePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Invoice' + description: The items in the current page. + description: Paginated response + InvoicePaymentTerms: + type: object + properties: + terms: + allOf: + - $ref: '#/components/schemas/PaymentTerms' + description: The terms of payment for the invoice. + description: Payment contains details as to how the invoice should be paid. + InvoicePendingLineCreate: + type: object + required: + - name + - period + - invoiceAt + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + description: InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage. + InvoicePendingLineCreateInput: + type: object + required: + - currency + - lines + properties: + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of the lines to be created. + lines: + type: array + items: + $ref: '#/components/schemas/InvoicePendingLineCreate' + minItems: 1 + description: The lines to be created. + description: InvoicePendingLineCreate represents the create model for a pending invoice line. + InvoicePendingLineCreateResponse: + type: object + required: + - lines + - invoice + - isInvoiceNew + properties: + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceLine' + description: The lines that were created. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/Invoice' + description: The invoice containing the created lines. + readOnly: true + isInvoiceNew: + type: boolean + description: Whether the invoice was newly created. + readOnly: true + description: InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. + InvoicePendingLinesActionFiltersInput: + type: object + properties: + lineIds: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: |- + The pending line items to include in the invoice, if not provided: + - all line items that have invoice_at < asOf will be included + - [progressive billing only] all usage based line items will be included up to asOf, new + usage-based line items will be staged for the rest of the billing cycle + + All lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail. + description: InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. + InvoicePendingLinesActionInput: + type: object + required: + - customerId + properties: + filters: + allOf: + - $ref: '#/components/schemas/InvoicePendingLinesActionFiltersInput' + description: Filters to apply when creating the invoice. + asOf: + type: string + format: date-time + description: |- + The time as of which the invoice is created. + + If not provided, the current time is used. + example: '2023-01-01T01:01:01.001Z' + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID for which to create the invoice. + example: 01G65Z755AFWAKHE12NY0CQ9FH + progressiveBillingOverride: + type: boolean + description: |- + Override the progressive billing setting of the customer. + + Can be used to disable/enable progressive billing in case the business logic + requires it, if not provided the billing profile's progressive billing setting will be used. + description: |- + BillingInvoiceActionInput is the input for creating an invoice. + + Invoice creation is always based on already pending line items created by the billingCreateLineByCustomer + operation. Empty invoices are not allowed. + InvoiceReference: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the invoice. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: The number of the invoice. + readOnly: true + description: Reference to an invoice. + InvoiceReplaceUpdate: + type: object + required: + - supplier + - customer + - lines + - workflow + properties: + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + supplier: + allOf: + - $ref: '#/components/schemas/BillingPartyReplaceUpdate' + description: The supplier of the lines included in the invoice. + customer: + allOf: + - $ref: '#/components/schemas/BillingPartyReplaceUpdate' + description: The customer the invoice is sent to. + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceLineReplaceUpdate' + description: The lines included in the invoice. + workflow: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowReplaceUpdate' + description: The workflow settings for the invoice. + description: InvoiceReplaceUpdate represents the update model for an invoice. + InvoiceSimulationInput: + type: object + required: + - currency + - lines + properties: + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: The number of the invoice. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency for all invoice line items. + + Multi currency invoices are not supported yet. + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceSimulationLine' + description: Lines to be included in the generated invoice. + description: InvoiceSimulationInput is the input for simulating an invoice. + InvoiceSimulationLine: + type: object + required: + - name + - period + - invoiceAt + - quantity + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity of the item being sold. + preLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity of the item used before this line's period, if the line is billed progressively. + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ID of the line. If not specified it will be auto-generated. + + When discounts are specified, this must be provided, so that the discount can reference it. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint. + InvoiceStatus: + type: string + enum: + - gathering + - draft + - issuing + - issued + - payment_processing + - overdue + - paid + - uncollectible + - voided + description: InvoiceStatus describes the status of an invoice. + InvoiceStatusDetails: + type: object + required: + - immutable + - failed + - extendedStatus + - availableActions + properties: + immutable: + type: boolean + description: Is the invoice editable? + readOnly: true + failed: + type: boolean + description: Is the invoice in a failed state? + readOnly: true + extendedStatus: + type: string + description: Extended status information for the invoice. + readOnly: true + availableActions: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActions' + description: The actions that can be performed on the invoice. + description: |- + InvoiceStatusDetails represents the details of the invoice status. + + API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine + the next steps of the invoice instead of the extendedStatus field. + InvoiceTotals: + type: object + required: + - amount + - chargesTotal + - discountsTotal + - creditsTotal + - taxesInclusiveTotal + - taxesExclusiveTotal + - taxesTotal + - total + properties: + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total value of the line before taxes, discounts and commitments. + readOnly: true + chargesTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of value of the line that are due to additional charges. + readOnly: true + discountsTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of value of the line that are due to discounts. + readOnly: true + creditsTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of value of the line that are due to credits. + readOnly: true + taxesInclusiveTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount of taxes that are included in the line. + readOnly: true + taxesExclusiveTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount of taxes that are added on top of amount from the line. + readOnly: true + taxesTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount of taxes for this line. + readOnly: true + total: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount value of the line after taxes, discounts and commitments. + readOnly: true + description: Totals contains the summaries of all calculations for the invoice. + InvoiceType: + type: string + enum: + - standard + - credit_note + description: |- + InvoiceType represents the type of invoice. + + The type of invoice determines the purpose of the invoice and how it should be handled. + InvoiceUsageBasedRateCard: + type: object + required: + - price + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the customer is entitled to use. + title: Feature key + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + discounts: + allOf: + - $ref: '#/components/schemas/BillingDiscounts' + description: The discounts that are applied to the line. + deprecated: true + description: InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. + InvoiceWorkflowInvoicingSettingsReplaceUpdate: + type: object + properties: + autoAdvance: + type: boolean + description: Whether to automatically issue the invoice after the draftPeriod has passed. + default: true + draftPeriod: + type: string + format: ISO8601 + description: The period for the invoice to be kept in draft status for manual reviews. + example: P1D + default: P0D + dueAfter: + type: string + format: ISO8601 + description: |- + The period after which the invoice is due. + With some payment solutions it's only applicable for manual collection method. + example: P30D + default: P30D + subscriptionEndProrationMode: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSubscriptionEndProrationMode' + description: Controls how subscription-ending shortened service periods are billed. + default: bill_actual_period + defaultTaxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + Default tax configuration to apply to the invoices. + + Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and `behavior` remains + fully supported. + description: InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow. + InvoiceWorkflowReplaceUpdate: + type: object + required: + - workflow + properties: + workflow: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowSettingsReplaceUpdate' + description: The workflow used for this invoice. + description: |- + InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. + + Fields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings. + InvoiceWorkflowSettings: + type: object + required: + - sourceBillingProfileId + - workflow + properties: + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsOrReference' + description: The apps that will be used to orchestrate the invoice's workflow. + readOnly: true + sourceBillingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + sourceBillingProfileID is the billing profile on which the workflow was based on. + + The profile is snapshotted on invoice creation, after which it can be altered independently + of the profile itself. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The workflow details used by this invoice. + description: |- + InvoiceWorkflowSettings represents the workflow settings used by the invoice. + + This is a clone of the billing profile's workflow settings at the time of invoice creation + with customer overrides considered. + InvoiceWorkflowSettingsReplaceUpdate: + type: object + required: + - invoicing + - payment + properties: + invoicing: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowInvoicingSettingsReplaceUpdate' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + description: |- + Mutable workflow settings for an invoice. + + Other fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow + at creation time. + IssueAfterReset: + type: object + required: + - amount + properties: + amount: + type: number + format: double + minimum: 0 + description: The initial grant amount + title: Initial grant amount + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: The priority of the issue after reset + title: Issue grant after reset priority + default: 1 + description: Issue after reset + ListEntitlementsResult: + oneOf: + - type: array + items: + $ref: '#/components/schemas/Entitlement' + - $ref: '#/components/schemas/EntitlementPaginatedResponse' + description: List entitlements result + ListFeaturesResult: + oneOf: + - type: array + items: + $ref: '#/components/schemas/Feature' + - $ref: '#/components/schemas/FeaturePaginatedResponse' + description: List features result + MarketplaceInstallRequestPayload: + type: object + properties: + name: + type: string + description: |- + Name of the application to install. + + If name is not provided defaults to the marketplace listing's name. + createBillingProfile: + type: boolean + description: |- + If true, a billing profile will be created for the app. + The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + default: true + description: Marketplace install request payload. + MarketplaceInstallResponse: + type: object + required: + - app + - defaultForCapabilityTypes + properties: + app: + $ref: '#/components/schemas/App' + defaultForCapabilityTypes: + type: array + items: + $ref: '#/components/schemas/AppCapabilityType' + description: Default for capabilities + description: Marketplace install response. + MarketplaceListing: + type: object + required: + - type + - name + - description + - capabilities + - installMethods + properties: + type: + allOf: + - $ref: '#/components/schemas/AppType' + description: The app's type + name: + type: string + description: The app's name. + description: + type: string + description: The app's description. + capabilities: + type: array + items: + $ref: '#/components/schemas/AppCapability' + description: The app's capabilities. + installMethods: + type: array + items: + $ref: '#/components/schemas/InstallMethod' + description: |- + Install methods. + + List of methods to install the app. + description: |- + A marketplace listing. + Represent an available app in the app marketplace that can be installed to the organization. + + Marketplace apps only exist in config so they don't extend the Resource model. + example: + type: stripe + name: Stripe + description: Stripe integration allows you to collect payments with Stripe. + capabilities: + - type: calculateTax + key: stripe_calculate_tax + name: Calculate Tax + description: Stripe Tax calculates tax portion of the invoices. + - type: invoiceCustomers + key: stripe_invoice_customers + name: Invoice Customers + description: Stripe invoices customers with due amount. + - type: collectPayments + key: stripe_collect_payments + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + installMethods: + - with_oauth2 + - with_api_key + MarketplaceListingPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/MarketplaceListing' + description: The items in the current page. + description: Paginated response + MeasureUsageFrom: + oneOf: + - $ref: '#/components/schemas/MeasureUsageFromPreset' + - $ref: '#/components/schemas/MeasureUsageFromTime' + description: Measure usage from + MeasureUsageFromPreset: + type: string + enum: + - CURRENT_PERIOD_START + - NOW + description: Start of measurement options + x-enum-varnames: + - CurrentPeriodStart + - Now + MeasureUsageFromTime: + type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + Metadata: + type: object + additionalProperties: + type: string + description: |- + Set of key-value pairs. + Metadata can be used to store additional information about a resource. + example: + externalId: 019142cc-a016-796a-8113-1a942fecd26d + x-go-type: map[string]string + Meter: + type: object + required: + - id + - createdAt + - updatedAt + - slug + - aggregation + - eventType + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: |- + Human-readable name for the resource. Between 1 and 256 characters. + Defaults to the slug if not specified. + title: Display name + slug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + A unique, human-readable identifier for the meter. + Must consist only alphanumeric and underscore characters. + example: tokens_total + aggregation: + allOf: + - $ref: '#/components/schemas/MeterAggregation' + description: The aggregation type to use for the meter. + example: SUM + eventType: + type: string + minLength: 1 + description: The event type to aggregate. + example: prompt + eventFrom: + type: string + format: date-time + description: |- + The date since the meter should include events. + Useful to skip old events. + If not specified, all historical events are included. + example: '2023-01-01T01:01:01.001Z' + valueProperty: + type: string + minLength: 1 + description: |- + JSONPath expression to extract the value from the ingested event's data property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + example: $.tokens + groupBy: + type: object + additionalProperties: + type: string + description: |- + Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + example: + type: $.type + annotations: + type: object + allOf: + - $ref: '#/components/schemas/Annotations' + nullable: true + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + description: A meter is a configuration that defines how to match and aggregate events. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + slug: tokens_total + name: Tokens Total + description: AI Token Usage + aggregation: SUM + eventType: prompt + valueProperty: $.tokens + groupBy: + model: $.model + type: $.type + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + MeterAggregation: + type: string + enum: + - SUM + - COUNT + - UNIQUE_COUNT + - AVG + - MIN + - MAX + - LATEST + description: The aggregation type to use for the meter. + x-enum-varnames: + - Sum + - Count + - UniqueCount + - Avg + - Min + - Max + - Latest + MeterCreate: + type: object + required: + - slug + - aggregation + - eventType + properties: + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + name: + type: string + minLength: 1 + maxLength: 256 + description: |- + Human-readable name for the resource. Between 1 and 256 characters. + Defaults to the slug if not specified. + title: Display name + slug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + A unique, human-readable identifier for the meter. + Must consist only alphanumeric and underscore characters. + example: tokens_total + aggregation: + allOf: + - $ref: '#/components/schemas/MeterAggregation' + description: The aggregation type to use for the meter. + example: SUM + eventType: + type: string + minLength: 1 + description: The event type to aggregate. + example: prompt + eventFrom: + type: string + format: date-time + description: |- + The date since the meter should include events. + Useful to skip old events. + If not specified, all historical events are included. + example: '2023-01-01T01:01:01.001Z' + valueProperty: + type: string + minLength: 1 + description: |- + JSONPath expression to extract the value from the ingested event's data property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + example: $.tokens + groupBy: + type: object + additionalProperties: + type: string + description: |- + Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + example: + type: $.type + description: A meter create model. + example: + slug: tokens_total + name: Tokens Total + description: AI Token Usage + aggregation: SUM + eventType: prompt + valueProperty: $.tokens + groupBy: + model: $.model + type: $.type + MeterOrderBy: + type: string + enum: + - key + - name + - aggregation + - createdAt + - updatedAt + description: Order by options for meters. + MeterQueryRequest: + type: object + properties: + clientId: + type: string + minLength: 1 + maxLength: 36 + description: |- + Client ID + Useful to track progress of a query. + example: f74e58ed-94ce-4041-ae06-cf45420451a3 + from: + type: string + format: date-time + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + example: '2023-01-01T01:01:01.001Z' + to: + type: string + format: date-time + description: |- + End date-time in RFC 3339 format. + + Inclusive. + example: '2023-01-01T01:01:01.001Z' + windowSize: + allOf: + - $ref: '#/components/schemas/WindowSize' + description: If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + example: DAY + windowTimeZone: + type: string + description: |- + The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + If not specified, the UTC timezone will be used. + example: UTC + default: UTC + subject: + type: array + items: + type: string + maxItems: 100 + description: Filtering by multiple subjects. + example: + - subject-1 + - subject-2 + filterCustomerId: + type: array + items: + type: string + maxItems: 100 + description: Filtering by multiple customers. + example: + - id-1 + - id-2 + filterGroupBy: + type: object + additionalProperties: + type: array + items: + type: string + description: Simple filter for group bys with exact match. + example: + model: + - gpt-4-turbo + - gpt-4o + type: + - prompt + advancedMeterGroupByFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/FilterString' + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + example: + model: + $in: + - gpt-4 + - gpt-4o + type: + $eq: input + groupBy: + type: array + items: + type: string + maxItems: 100 + description: |- + If not specified a single aggregate will be returned for each subject and time window. + `subject` is a reserved group by value. + example: + - model + - type + description: A meter query request. + MeterQueryResult: + type: object + required: + - data + properties: + from: + type: string + format: date-time + description: |- + The start of the period the usage is queried from. + If not specified, the usage is queried from the beginning of time. + example: '2023-01-01T01:01:01.001Z' + to: + type: string + format: date-time + description: |- + The end of the period the usage is queried to. + If not specified, the usage is queried up to the current time. + example: '2023-01-01T01:01:01.001Z' + windowSize: + allOf: + - $ref: '#/components/schemas/WindowSize' + description: |- + The window size that the usage is aggregated. + If not specified, the usage is aggregated over the entire period. + data: + type: array + items: + $ref: '#/components/schemas/MeterQueryRow' + description: |- + The usage data. + If no data is available, an empty array is returned. + description: The result of a meter query. + example: + from: '2023-01-01T00:00:00Z' + to: '2023-01-02T00:00:00Z' + windowSize: DAY + data: + - value: 12 + windowStart: '2023-01-01T00:00:00Z' + windowEnd: '2023-01-02T00:00:00Z' + subject: customer-1 + groupBy: + model: gpt-4-turbo + type: prompt + MeterQueryRow: + type: object + required: + - value + - windowStart + - windowEnd + - subject + - groupBy + properties: + value: + type: number + format: double + description: The aggregated value. + windowStart: + type: string + format: date-time + description: The start of the window the value is aggregated over. + example: '2023-01-01T01:01:01.001Z' + windowEnd: + type: string + format: date-time + description: The end of the window the value is aggregated over. + example: '2023-01-01T01:01:01.001Z' + subject: + type: string + nullable: true + description: |- + The subject the value is aggregated over. + If not specified, the value is aggregated over all subjects. + customerId: + type: string + description: The customer ID the value is aggregated over. + groupBy: + type: object + additionalProperties: + type: string + nullable: true + description: The group by values the value is aggregated over. + description: A row in the result of a meter query. + example: + value: 12 + windowStart: '2023-01-01T00:00:00Z' + windowEnd: '2023-01-02T00:00:00Z' + subject: customer-1 + groupBy: + model: gpt-4-turbo + type: prompt + MeterUpdate: + type: object + properties: + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + name: + type: string + minLength: 1 + maxLength: 256 + description: |- + Human-readable name for the resource. Between 1 and 256 characters. + Defaults to the slug if not specified. + title: Display name + groupBy: + type: object + additionalProperties: + type: string + description: |- + Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + example: + type: $.type + description: |- + A meter update model. + + Only the properties that can be updated are included. + For example, the slug and aggregation cannot be updated. + example: + name: Tokens Total + description: AI Token Usage + groupBy: + model: $.model + type: $.type + NotFoundProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + NotImplementedProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server does not support the functionality required to fulfill the request. + NotificationChannel: + type: object + allOf: + - $ref: '#/components/schemas/NotificationChannelWebhook' + description: Notification channel. + NotificationChannelCreateRequest: + type: object + allOf: + - $ref: '#/components/schemas/NotificationChannelWebhookCreateRequest' + description: Union type for requests creating new notification channel with certain type. + NotificationChannelMeta: + type: object + required: + - id + - type + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification channel. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Channel Unique Identifier + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/NotificationChannelType' + description: Notification channel type. + title: Channel Type + description: Metadata only fields of a notification channel. + NotificationChannelOrderBy: + type: string + enum: + - id + - type + - createdAt + - updatedAt + description: Order by options for notification channels. + NotificationChannelPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/NotificationChannel' + description: The items in the current page. + description: Paginated response + NotificationChannelType: + type: string + enum: + - WEBHOOK + description: Type of the notification channel. + x-enum-varnames: + - Webhook + NotificationChannelWebhook: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - url + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification channel. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Channel Unique Identifier + readOnly: true + type: + type: string + enum: + - WEBHOOK + description: Notification channel type. + title: Channel Type + name: + type: string + minLength: 1 + maxLength: 256 + description: User friendly name of the channel. + title: Channel Name + example: customer-webhook + disabled: + type: boolean + description: Whether the channel is disabled or not. + title: Channel Disabled + example: true + default: false + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + url: + type: string + description: Webhook URL where the notification is sent. + title: Webhook URL + example: https://example.com/webhook + customHeaders: + type: object + additionalProperties: + type: string + description: Custom HTTP headers sent as part of the webhook request. + title: Custom HTTP Headers + signingSecret: + type: string + pattern: ^(whsec_)?[a-zA-Z0-9+/=]{32,100}$ + description: |- + Signing secret used for webhook request validation on the receiving end. + + Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + title: Signing Secret + example: whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8 + description: Notification channel with webhook type. + NotificationChannelWebhookCreateRequest: + type: object + required: + - type + - name + - url + properties: + type: + type: string + enum: + - WEBHOOK + description: Notification channel type. + title: Channel Type + name: + type: string + minLength: 1 + maxLength: 256 + description: User friendly name of the channel. + title: Channel Name + example: customer-webhook + disabled: + type: boolean + description: Whether the channel is disabled or not. + title: Channel Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + url: + type: string + description: Webhook URL where the notification is sent. + title: Webhook URL + example: https://example.com/webhook + customHeaders: + type: object + additionalProperties: + type: string + description: Custom HTTP headers sent as part of the webhook request. + title: Custom HTTP Headers + signingSecret: + type: string + pattern: ^(whsec_)?[a-zA-Z0-9+/=]{32,100}$ + description: |- + Signing secret used for webhook request validation on the receiving end. + + Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + title: Signing Secret + example: whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8 + description: Request with input parameters for creating new notification channel with webhook type. + NotificationEvent: + type: object + required: + - id + - type + - createdAt + - rule + - deliveryStatus + - payload + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier of the notification event. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Event Identifier + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/NotificationEventType' + description: Type of the notification event. + title: Event Type + readOnly: true + createdAt: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + rule: + allOf: + - $ref: '#/components/schemas/NotificationRule' + description: The nnotification rule which generated this event. + readOnly: true + deliveryStatus: + type: array + items: + $ref: '#/components/schemas/NotificationEventDeliveryStatus' + description: The delivery status of the notification event. + title: Delivery Status + readOnly: true + payload: + allOf: + - $ref: '#/components/schemas/NotificationEventPayload' + description: Timestamp when the notification event was created in RFC 3339 format. + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + description: Type of the notification event. + NotificationEventBalanceThresholdPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - entitlements.balance.threshold + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/NotificationEventBalanceThresholdPayloadData' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `entitlements.balance.threshold` type. + NotificationEventBalanceThresholdPayloadData: + type: object + required: + - entitlement + - feature + - subject + - value + - threshold + properties: + entitlement: + allOf: + - $ref: '#/components/schemas/EntitlementMetered' + title: Entitlement + readOnly: true + feature: + allOf: + - $ref: '#/components/schemas/Feature' + title: Feature + readOnly: true + subject: + allOf: + - $ref: '#/components/schemas/Subject' + title: Subject + readOnly: true + value: + allOf: + - $ref: '#/components/schemas/EntitlementValue' + title: Entitlement Value + readOnly: true + customer: + allOf: + - $ref: '#/components/schemas/Customer' + title: Customer + readOnly: true + threshold: + allOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThresholdValue' + title: Threshold + readOnly: true + description: Data of the payload for notification event with `entitlements.balance.threshold` type. + NotificationEventDeliveryAttempt: + type: object + required: + - state + - response + - timestamp + properties: + state: + allOf: + - $ref: '#/components/schemas/NotificationEventDeliveryStatusState' + description: State of teh delivery attempt. + title: State of teh delivery attempt + example: SUCCESS + readOnly: true + response: + allOf: + - $ref: '#/components/schemas/EventDeliveryAttemptResponse' + description: Response returned by the notification event recipient. + title: Response returned by the notification event recipient + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp of the delivery attempt. + example: '2023-01-01T01:01:01.001Z' + title: Timestamp of the delivery attempt + readOnly: true + description: The delivery attempt of the notification event. + NotificationEventDeliveryStatus: + type: object + required: + - state + - reason + - updatedAt + - channel + - attempts + properties: + state: + allOf: + - $ref: '#/components/schemas/NotificationEventDeliveryStatusState' + description: Delivery state of the notification event to the channel. + example: SUCCESS + readOnly: true + reason: + type: string + description: The reason of the last deliverry state update. + title: State Reason + example: Failed to dispatch event due to provider error. + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the status was last updated in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + channel: + allOf: + - $ref: '#/components/schemas/NotificationChannelMeta' + description: Notification channel the delivery status associated with. + title: Notification Channel + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + nextAttempt: + type: string + format: date-time + description: Timestamp of the next delivery attempt. If null it means there will be no more delivery attempts. + example: '2023-01-01T01:01:01.001Z' + title: Timestamp of the next delivery attempt + readOnly: true + attempts: + type: array + items: + $ref: '#/components/schemas/NotificationEventDeliveryAttempt' + description: List of delivery attempts. + title: Delivery Attempts + readOnly: true + description: The delivery status of the notification event. + NotificationEventDeliveryStatusState: + type: string + enum: + - SUCCESS + - FAILED + - SENDING + - PENDING + - RESENDING + description: The delivery state of the notification event to the channel. + title: Delivery State + x-enum-varnames: + - Success + - Failed + - Sending + - Pending + - Resending + NotificationEventEntitlementValuePayloadBase: + type: object + required: + - entitlement + - feature + - subject + - value + properties: + entitlement: + allOf: + - $ref: '#/components/schemas/EntitlementMetered' + title: Entitlement + readOnly: true + feature: + allOf: + - $ref: '#/components/schemas/Feature' + title: Feature + readOnly: true + subject: + allOf: + - $ref: '#/components/schemas/Subject' + title: Subject + readOnly: true + value: + allOf: + - $ref: '#/components/schemas/EntitlementValue' + title: Entitlement Value + readOnly: true + customer: + allOf: + - $ref: '#/components/schemas/Customer' + title: Customer + readOnly: true + description: Base data for any payload with entitlement entitlement value. + NotificationEventInvoiceCreatedPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - invoice.created + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/Invoice' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `invoice.created` type. + NotificationEventInvoiceUpdatedPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - invoice.updated + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/Invoice' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `invoice.updated` type. + NotificationEventOrderBy: + type: string + enum: + - id + - createdAt + description: Order by options for notification channels. + NotificationEventPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/NotificationEvent' + description: The items in the current page. + description: Paginated response + NotificationEventPayload: + type: object + oneOf: + - $ref: '#/components/schemas/NotificationEventResetPayload' + - $ref: '#/components/schemas/NotificationEventBalanceThresholdPayload' + - $ref: '#/components/schemas/NotificationEventInvoiceCreatedPayload' + - $ref: '#/components/schemas/NotificationEventInvoiceUpdatedPayload' + discriminator: + propertyName: type + mapping: + entitlements.reset: '#/components/schemas/NotificationEventResetPayload' + entitlements.balance.threshold: '#/components/schemas/NotificationEventBalanceThresholdPayload' + invoice.created: '#/components/schemas/NotificationEventInvoiceCreatedPayload' + invoice.updated: '#/components/schemas/NotificationEventInvoiceUpdatedPayload' + description: The delivery status of the notification event. + NotificationEventResendRequest: + type: object + properties: + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Notification channels to which the event should be re-sent. + title: Channels + description: A notification event that will be re-sent. + NotificationEventResetPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - entitlements.reset + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/NotificationEventEntitlementValuePayloadBase' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `entitlements.reset` type. + NotificationEventType: + type: string + enum: + - entitlements.balance.threshold + - entitlements.reset + - invoice.created + - invoice.updated + description: Type of the notification event. + NotificationRule: + type: object + oneOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThreshold' + - $ref: '#/components/schemas/NotificationRuleEntitlementReset' + - $ref: '#/components/schemas/NotificationRuleInvoiceCreated' + - $ref: '#/components/schemas/NotificationRuleInvoiceUpdated' + discriminator: + propertyName: type + mapping: + entitlements.balance.threshold: '#/components/schemas/NotificationRuleBalanceThreshold' + entitlements.reset: '#/components/schemas/NotificationRuleEntitlementReset' + invoice.created: '#/components/schemas/NotificationRuleInvoiceCreated' + invoice.updated: '#/components/schemas/NotificationRuleInvoiceUpdated' + description: Notification Rule. + NotificationRuleBalanceThreshold: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + - thresholds + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - entitlements.balance.threshold + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + thresholds: + type: array + items: + $ref: '#/components/schemas/NotificationRuleBalanceThresholdValue' + minItems: 1 + maxItems: 10 + description: List of thresholds the rule suppose to be triggered. + title: Entitlement Balance Thresholds + features: + type: array + items: + $ref: '#/components/schemas/FeatureMeta' + minItems: 1 + description: Optional field containing list of features the rule applies to. + title: Features + description: Notification rule with entitlements.balance.threshold type. + NotificationRuleBalanceThresholdCreateRequest: + type: object + required: + - type + - name + - thresholds + - channels + properties: + type: + type: string + enum: + - entitlements.balance.threshold + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + thresholds: + type: array + items: + $ref: '#/components/schemas/NotificationRuleBalanceThresholdValue' + minItems: 1 + maxItems: 10 + description: List of thresholds the rule suppose to be triggered. + title: Entitlement Balance Thresholds + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + features: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ULID (Universally Unique Lexicographically Sortable Identifier). + A key is a unique string that is used to identify a resource. + + TODO: this is a temporary solution to support both ULID and Key in the same spec for codegen. + minItems: 1 + description: Optional field for defining the scope of notification by feature. It may contain features by id or key. + title: Features + description: Request with input parameters for creating new notification rule with entitlements.balance.threshold type. + NotificationRuleBalanceThresholdValue: + type: object + required: + - value + - type + properties: + value: + type: number + format: double + description: Value of the threshold. + title: Threshold Value + example: 100 + type: + allOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThresholdValueType' + description: Type of the threshold. + example: usage_value + description: Threshold value with multiple supported types. + NotificationRuleBalanceThresholdValueType: + type: string + enum: + - PERCENT + - NUMBER + - balance_value + - usage_percentage + - usage_value + description: |- + Type of the rule in the balance threshold specification: + * `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period + * `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period + * `usage_value`: threshold defined by the usage value in the current usage period + * `NUMBER` (**deprecated**): see `usage_value` + * `PERCENT` (**deprecated**): see `usage_percentage` + title: Notification balance threshold type + x-enum-varnames: + - Percent + - Number + - BalanceValue + - UsagePercentage + - UsageValue + NotificationRuleCreateRequest: + type: object + oneOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThresholdCreateRequest' + - $ref: '#/components/schemas/NotificationRuleEntitlementResetCreateRequest' + - $ref: '#/components/schemas/NotificationRuleInvoiceCreatedCreateRequest' + - $ref: '#/components/schemas/NotificationRuleInvoiceUpdatedCreateRequest' + discriminator: + propertyName: type + mapping: + entitlements.balance.threshold: '#/components/schemas/NotificationRuleBalanceThresholdCreateRequest' + entitlements.reset: '#/components/schemas/NotificationRuleEntitlementResetCreateRequest' + invoice.created: '#/components/schemas/NotificationRuleInvoiceCreatedCreateRequest' + invoice.updated: '#/components/schemas/NotificationRuleInvoiceUpdatedCreateRequest' + description: Union type for requests creating new notification rule with certain type. + NotificationRuleEntitlementReset: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - entitlements.reset + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + features: + type: array + items: + $ref: '#/components/schemas/FeatureMeta' + minItems: 1 + description: Optional field containing list of features the rule applies to. + title: Features + description: Notification rule with entitlements.reset type. + NotificationRuleEntitlementResetCreateRequest: + type: object + required: + - type + - name + - channels + properties: + type: + type: string + enum: + - entitlements.reset + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + features: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ULID (Universally Unique Lexicographically Sortable Identifier). + A key is a unique string that is used to identify a resource. + + TODO: this is a temporary solution to support both ULID and Key in the same spec for codegen. + minItems: 1 + description: Optional field for defining the scope of notification by feature. It may contain features by id or key. + title: Features + description: Request with input parameters for creating new notification rule with entitlements.reset type. + NotificationRuleInvoiceCreated: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - invoice.created + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + description: Notification rule with invoice.created type. + NotificationRuleInvoiceCreatedCreateRequest: + type: object + required: + - type + - name + - channels + properties: + type: + type: string + enum: + - invoice.created + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + description: Request with input parameters for creating new notification rule with invoice.created type. + NotificationRuleInvoiceUpdated: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - invoice.updated + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + description: Notification rule with invoice.updated type. + NotificationRuleInvoiceUpdatedCreateRequest: + type: object + required: + - type + - name + - channels + properties: + type: + type: string + enum: + - invoice.updated + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + description: Request with input parameters for creating new notification rule with invoice.updated type. + NotificationRuleOrderBy: + type: string + enum: + - id + - type + - createdAt + - updatedAt + description: Order by options for notification channels. + NotificationRulePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/NotificationRule' + description: The items in the current page. + description: Paginated response + Numeric: + type: string + pattern: ^\-?[0-9]+(\.[0-9]+)?$ + description: Numeric represents an arbitrary precision number. + OAuth2AuthorizationCodeGrantErrorType: + type: string + enum: + - invalid_request + - unauthorized_client + - access_denied + - unsupported_response_type + - invalid_scope + - server_error + - temporarily_unavailable + description: OAuth2 authorization code grant error types. + PackagePriceWithCommitments: + type: object + required: + - type + - amount + - quantityPerPackage + properties: + type: + type: string + enum: + - package + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The price of one package. + title: Amount + quantityPerPackage: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity per package. + title: Quantity per package + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Package price with spend commitments. + PaymentDueDate: + type: object + required: + - dueAt + - amount + properties: + dueAt: + type: string + format: date-time + description: When the payment is due. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + notes: + type: string + description: Other details to take into account for the due date. + readOnly: true + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: How much needs to be paid by the date. + readOnly: true + percent: + allOf: + - $ref: '#/components/schemas/Percentage' + description: Percentage of the total that should be paid by the date. + readOnly: true + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: If different from the parent document's base currency. + readOnly: true + description: PaymentDueDate contains an amount that should be paid by the given date. + PaymentTermDueDate: + type: object + required: + - type + - dueAt + properties: + type: + type: string + enum: + - due_date + description: Type of terms to be applied. + detail: + type: string + description: Text detail of the chosen payment terms. + readOnly: true + notes: + type: string + description: Description of the conditions for payment. + readOnly: true + dueAt: + type: array + items: + $ref: '#/components/schemas/PaymentDueDate' + minItems: 1 + description: When the payment is due. + readOnly: true + description: PaymentTermDueDate defines the terms for payment on a specific date. + PaymentTermInstant: + type: object + required: + - type + properties: + type: + type: string + enum: + - instant + description: Type of terms to be applied. + detail: + type: string + description: Text detail of the chosen payment terms. + readOnly: true + notes: + type: string + description: Description of the conditions for payment. + readOnly: true + description: PaymentTermInstant defines the terms for payment on receipt of invoice. + PaymentTerms: + anyOf: + - $ref: '#/components/schemas/PaymentTermInstant' + - $ref: '#/components/schemas/PaymentTermDueDate' + description: PaymentTerms defines the terms for payment. + Percentage: + type: number + format: double + description: |- + Numeric representation of a percentage + + 50% is represented as 50 + example: 50 + x-go-package: github.com/openmeterio/openmeter/pkg/models + x-go-type: models.Percentage + Period: + type: object + required: + - from + - to + properties: + from: + type: string + format: date-time + description: Period start time. + example: '2023-01-01T01:01:01.001Z' + to: + type: string + format: date-time + description: Period end time. + example: '2023-02-01T01:01:01.001Z' + description: A period with a start and end time. + Plan: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - version + - currency + - billingCadence + - status + - phases + - validationErrors + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + version: + type: integer + minimum: 1 + description: Version of the plan. Incremented when the plan is updated. + title: Version + default: 1 + readOnly: true + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the plan. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + effectiveFrom: + type: string + format: date-time + description: The date and time when the plan becomes effective. When not specified, the plan is a draft. + example: '2023-01-01T01:01:01.001Z' + title: Effective start date + readOnly: true + effectiveTo: + type: string + format: date-time + description: The date and time when the plan is no longer effective. When not specified, the plan is effective indefinitely. + example: '2023-01-01T01:01:01.001Z' + title: Effective end date + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/PlanStatus' + description: |- + The status of the plan. + Computed based on the effective start and end dates: + - draft = no effectiveFrom + - active = effectiveFrom <= now < effectiveTo + - archived / inactive = effectiveTo <= now + - scheduled = now < effectiveFrom < effectiveTo + title: Status + readOnly: true + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + nullable: true + description: List of validation errors. + title: Validation errors + readOnly: true + description: Plans provide a template for subscriptions. + PlanAddon: + type: object + required: + - createdAt + - updatedAt + - addon + - fromPlanPhase + - validationErrors + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the resource. + title: Metadata + addon: + allOf: + - $ref: '#/components/schemas/Addon' + description: Add-on object. + title: Addon + readOnly: true + fromPlanPhase: + type: string + description: The key of the plan phase from the add-on becomes available for purchase. + title: The plan phase from the add-on becomes purchasable + maxQuantity: + type: integer + description: |- + The maximum number of times the add-on can be purchased for the plan. + It is not applicable for add-ons with single instance type. + title: Max quantity of the add-on + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + nullable: true + description: List of validation errors. + title: Validation errors + readOnly: true + description: The PlanAddon describes the association between a plan and add-on. + PlanAddonCreate: + type: object + required: + - fromPlanPhase + - addonId + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the resource. + title: Metadata + fromPlanPhase: + type: string + description: The key of the plan phase from the add-on becomes available for purchase. + title: The plan phase from the add-on becomes purchasable + maxQuantity: + type: integer + description: |- + The maximum number of times the add-on can be purchased for the plan. + It is not applicable for add-ons with single instance type. + title: Max quantity of the add-on + addonId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The add-on unique identifier in ULID format. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: Add-on unique identifier + description: A plan add-on assignment create request. + PlanAddonOrderBy: + type: string + enum: + - id + - key + - version + - created_at + - updated_at + description: Order by options for plan add-on assignments. + PlanAddonPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/PlanAddon' + description: The items in the current page. + description: Paginated response + PlanAddonReplaceUpdate: + type: object + required: + - fromPlanPhase + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the resource. + title: Metadata + fromPlanPhase: + type: string + description: The key of the plan phase from the add-on becomes available for purchase. + title: The plan phase from the add-on becomes purchasable + maxQuantity: + type: integer + description: |- + The maximum number of times the add-on can be purchased for the plan. + It is not applicable for add-ons with single instance type. + title: Max quantity of the add-on + description: Resource update operation model. + PlanCreate: + type: object + required: + - name + - key + - currency + - billingCadence + - phases + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the plan. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + description: Resource create operation model. + PlanOrderBy: + type: string + enum: + - id + - key + - version + - created_at + - updated_at + description: Order by options for plans. + PlanPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Plan' + description: The items in the current page. + description: Paginated response + PlanPhase: + type: object + required: + - key + - name + - duration + - rateCards + properties: + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + duration: + type: string + format: duration + nullable: true + description: The duration of the phase. + title: Duration + example: P1Y + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the plan. + title: Rate cards + description: The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + PlanReference: + type: object + required: + - id + - key + - version + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The plan ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The plan key. + version: + type: integer + description: The plan version. + description: References an exact plan. + PlanReferenceInput: + type: object + required: + - key + properties: + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The plan key. + version: + type: integer + description: The plan version. + description: References an exact plan defaulting to the current active version. + PlanReplaceUpdate: + type: object + required: + - name + - billingCadence + - phases + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + description: Resource update operation model. + PlanStatus: + type: string + enum: + - draft + - active + - archived + - scheduled + description: The status of a plan. + PlanSubscriptionChange: + type: object + required: + - timing + - plan + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + For changing a subscription, the accepted values depend on the subscription configuration. + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: What alignment settings the subscription should have. + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Arbitrary metadata associated with the subscription. + plan: + allOf: + - $ref: '#/components/schemas/PlanReferenceInput' + description: The plan reference to change to. + startingPhase: + type: string + minLength: 1 + description: |- + The key of the phase to start the subscription in. + If not provided, the subscription will start in the first phase of the plan. + name: + type: string + description: The name of the Subscription. If not provided the plan name is used. + description: + type: string + description: Description for the Subscription. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + example: '2023-01-01T01:01:01.001Z' + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: The settlement mode of the subscription. + description: Change subscription based on plan. + PlanSubscriptionCreate: + type: object + required: + - plan + properties: + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: What alignment settings the subscription should have. + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Arbitrary metadata associated with the subscription. + plan: + allOf: + - $ref: '#/components/schemas/PlanReferenceInput' + description: The plan reference to change to. + startingPhase: + type: string + minLength: 1 + description: |- + The key of the phase to start the subscription in. + If not provided, the subscription will start in the first phase of the plan. + name: + type: string + description: The name of the Subscription. If not provided the plan name is used. + description: + type: string + description: Description for the Subscription. + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: The settlement mode of the subscription. + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + The default is immediate. + default: immediate + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the customer. Provide either the key or ID. Has presedence over the key. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerKey: + type: string + minLength: 1 + maxLength: 256 + description: The key of the customer. Provide either the key or ID. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + example: '2023-01-01T01:01:01.001Z' + description: Create subscription based on plan. + title: Create from plan + PortalToken: + type: object + required: + - subject + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + subject: + type: string + example: customer-1 + expiresAt: + type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + readOnly: true + expired: + type: boolean + readOnly: true + createdAt: + type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + readOnly: true + token: + type: string + description: The token is only returned at creation. + example: om_portal_IAnD3PpWW2A2Wr8m9jfzeHlGX8xmCXwG.y5q4S-AWqFu6qjfaFz0zQq4Ez28RsnyVwJffX5qxMvo + readOnly: true + allowedMeterSlugs: + type: array + items: + type: string + description: Optional, if defined only the specified meters will be allowed. + example: + - tokens_total + description: |- + A consumer portal token. + + Validator doesn't obey required for readOnly properties + See: https://github.com/stoplightio/spectral/issues/1274 + PreconditionFailedProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + PricePaymentTerm: + type: string + enum: + - in_advance + - in_arrears + description: |- + The payment term of a flat price. + One of: in_advance or in_arrears. + PriceTier: + type: object + required: + - flatPrice + - unitPrice + properties: + upToAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + Up to and including to this quantity will be contained in the tier. + If null, the tier is open-ended. + title: Up to quantity + flatPrice: + type: object + allOf: + - $ref: '#/components/schemas/FlatPrice' + nullable: true + description: The flat price component of the tier. + title: Flat price component + unitPrice: + type: object + allOf: + - $ref: '#/components/schemas/UnitPrice' + nullable: true + description: The unit price component of the tier. + title: Unit price component + description: |- + A price tier. + At least one price component is required in each tier. + ProRatingConfig: + type: object + required: + - enabled + - mode + properties: + enabled: + type: boolean + description: Whether pro-rating is enabled for this plan. + title: Enable pro-rating + default: true + mode: + allOf: + - $ref: '#/components/schemas/ProRatingMode' + description: How to handle pro-rating for billing period changes. + title: Pro-rating mode + default: prorate_prices + description: Configuration for pro-rating behavior. + ProRatingMode: + type: string + enum: + - prorate_prices + description: Pro-rating mode options for handling billing period changes. + Progress: + type: object + required: + - success + - failed + - total + - updatedAt + properties: + success: + type: integer + format: uint64 + description: Success is the number of items that succeeded + failed: + type: integer + format: uint64 + description: Failed is the number of items that failed + total: + type: integer + format: uint64 + description: The total number of items to process + updatedAt: + type: string + format: date-time + description: The time the progress was last updated + example: '2023-01-01T01:01:01.001Z' + description: Progress describes a progress of a task. + RateCard: + type: object + oneOf: + - $ref: '#/components/schemas/RateCardFlatFee' + - $ref: '#/components/schemas/RateCardUsageBased' + discriminator: + propertyName: type + mapping: + flat_fee: '#/components/schemas/RateCardFlatFee' + usage_based: '#/components/schemas/RateCardUsageBased' + description: A rate card defines the pricing and entitlement of a feature or service. + RateCardBooleanEntitlement: + type: object + required: + - type + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - boolean + description: Entitlement template of a boolean entitlement. + RateCardEntitlement: + type: object + oneOf: + - $ref: '#/components/schemas/RateCardMeteredEntitlement' + - $ref: '#/components/schemas/RateCardStaticEntitlement' + - $ref: '#/components/schemas/RateCardBooleanEntitlement' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/RateCardMeteredEntitlement' + static: '#/components/schemas/RateCardStaticEntitlement' + boolean: '#/components/schemas/RateCardBooleanEntitlement' + description: |- + Entitlement templates are used to define the entitlements of a plan. + Features are omitted from the entitlement template, as they are defined in the rate card. + RateCardFlatFee: + type: object + required: + - type + - key + - name + - billingCadence + - price + properties: + type: + type: string + enum: + - flat_fee + description: The type of the RateCard. + title: RateCard type + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the customer is entitled to use. + title: Feature key + entitlementTemplate: + allOf: + - $ref: '#/components/schemas/RateCardEntitlement' + description: |- + The entitlement of the rate card. + Only available when featureKey is set. + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + billingCadence: + type: string + format: duration + nullable: true + description: |- + The billing cadence of the rate card. + When null it means it is a one time fee. + title: Billing cadence + price: + type: object + allOf: + - $ref: '#/components/schemas/FlatPriceWithPaymentTerm' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + title: Price + example: + type: flat + amount: '100' + paymentTerm: in_arrears + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: |- + The discount of the rate card. For flat fee rate cards only percentage discounts are supported. + Only available when price is set. + title: Discounts + description: A flat fee rate card defines a one-time purchase or a recurring fee. + RateCardMeteredEntitlement: + type: object + required: + - type + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + default: 1 + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + usagePeriod: + type: string + format: duration + description: |- + The interval of the metered entitlement. + Defaults to the billing cadence of the rate card. + title: Usage Period + description: The entitlement template with a metered entitlement. + RateCardStaticEntitlement: + type: object + required: + - type + - config + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + description: Entitlement template of a static entitlement. + RateCardUsageBased: + type: object + required: + - type + - key + - name + - billingCadence + - price + properties: + type: + type: string + enum: + - usage_based + description: The type of the RateCard. + title: RateCard type + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the customer is entitled to use. + title: Feature key + entitlementTemplate: + allOf: + - $ref: '#/components/schemas/RateCardEntitlement' + description: |- + The entitlement of the rate card. + Only available when featureKey is set. + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + billingCadence: + type: string + format: duration + description: The billing cadence of the rate card. + title: Billing cadence + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: |- + The discounts of the rate card. + + Flat fee rate cards only support percentage discounts. + title: Discounts + description: A usage-based rate card defines a price based on usage. + RateCardUsageBasedPrice: + type: object + oneOf: + - $ref: '#/components/schemas/FlatPriceWithPaymentTerm' + - $ref: '#/components/schemas/UnitPriceWithCommitments' + - $ref: '#/components/schemas/TieredPriceWithCommitments' + - $ref: '#/components/schemas/DynamicPriceWithCommitments' + - $ref: '#/components/schemas/PackagePriceWithCommitments' + discriminator: + propertyName: type + mapping: + flat: '#/components/schemas/FlatPriceWithPaymentTerm' + unit: '#/components/schemas/UnitPriceWithCommitments' + tiered: '#/components/schemas/TieredPriceWithCommitments' + dynamic: '#/components/schemas/DynamicPriceWithCommitments' + package: '#/components/schemas/PackagePriceWithCommitments' + description: The price of the usage based rate card. + RecurringPeriod: + type: object + required: + - interval + - anchor + - intervalISO + properties: + interval: + allOf: + - $ref: '#/components/schemas/RecurringPeriodInterval' + description: The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + title: Interval + anchor: + type: string + format: date-time + description: A date-time anchor to base the recurring period on. + example: '2023-01-01T01:01:01.001Z' + title: Anchor time + intervalISO: + type: string + format: duration + description: The unit of time for the interval in ISO8601 format. + description: Recurring period with an interval and an anchor. + deprecated: true + example: + interval: DAY + intervalISO: P1D + anchor: '2023-01-01T01:01:01.001Z' + RecurringPeriodCreateInput: + type: object + required: + - interval + properties: + interval: + allOf: + - $ref: '#/components/schemas/RecurringPeriodInterval' + description: The unit of time for the interval. + title: Interval + anchor: + type: string + format: date-time + description: A date-time anchor to base the recurring period on. + example: '2023-01-01T01:01:01.001Z' + title: Anchor time + description: Recurring period with an interval and an anchor. + example: + interval: DAY + anchor: '2023-01-01T01:01:01.001Z' + RecurringPeriodInterval: + anyOf: + - type: string + pattern: ^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$ + - $ref: '#/components/schemas/RecurringPeriodIntervalEnum' + description: Period duration for the recurrence + RecurringPeriodIntervalEnum: + type: string + enum: + - DAY + - WEEK + - MONTH + - YEAR + description: |- + The unit of time for the interval. + One of: `day`, `week`, `month`, or `year`. + RecurringPeriodV2: + type: object + required: + - interval + - anchor + properties: + interval: + allOf: + - $ref: '#/components/schemas/RecurringPeriodInterval' + description: The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + title: Interval + anchor: + type: string + format: date-time + description: A date-time anchor to base the recurring period on. + example: '2023-01-01T01:01:01.001Z' + title: Anchor time + description: Recurring period with an interval and an anchor. + RemovePhaseShifting: + type: string + enum: + - next + - prev + description: The direction of the phase shift when a phase is removed. + ResetEntitlementUsageInput: + type: object + properties: + effectiveAt: + type: string + format: date-time + description: The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored. + example: '2023-01-01T01:01:01.001Z' + retainAnchor: + type: boolean + description: |- + Determines whether the usage period anchor is retained or reset to the effectiveAt time. + - If true, the usage period anchor is retained. + - If false, the usage period anchor is reset to the effectiveAt time. + preserveOverage: + type: boolean + description: |- + Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior. + - If true, the overage is preserved. + - If false, the overage is forgiven. + description: Reset parameters + SandboxApp: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - sandbox + description: The app's type is Sandbox. + description: |- + Sandbox app can be used for testing OpenMeter features. + + The app is not creating anything in external systems, thus it is safe to use for + verifying OpenMeter features. + SandboxAppReplaceUpdate: + type: object + required: + - name + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + type: + type: string + enum: + - sandbox + description: The app's type is Sandbox. + description: Resource update operation model. + SandboxCustomerAppData: + type: object + required: + - type + properties: + app: + allOf: + - $ref: '#/components/schemas/SandboxApp' + description: The installed sandbox app this data belongs to. + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - sandbox + description: The app name. + title: App Type + description: Sandbox Customer App Data. + ServiceUnavailableProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + SortOrder: + type: string + enum: + - ASC + - DESC + description: The order direction. + StripeAPIKeyInput: + type: object + required: + - secretAPIKey + properties: + secretAPIKey: + type: string + description: |- + The Stripe API key input. + Used to authenticate with the Stripe API. + StripeApp: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + - stripeAccountId + - livemode + - maskedAPIKey + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - stripe + description: The app's type is Stripe. + stripeAccountId: + type: string + description: The Stripe account ID. + readOnly: true + livemode: + type: boolean + description: Livemode, true if the app is in production mode. + readOnly: true + maskedAPIKey: + type: string + description: |- + The masked API key. + Only shows the first 8 and last 3 characters. + readOnly: true + description: A installed Stripe app object. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + type: stripe + name: Stripe + status: ready + listing: + type: stripe + name: Stripe + description: Stripe integration allows you to collect payments with Stripe. + capabilities: + - type: calculateTax + key: stripe_calculate_tax + name: Calculate Tax + description: Stripe Tax calculates tax portion of the invoices. + - type: invoiceCustomers + key: stripe_invoice_customers + name: Invoice Customers + description: Stripe invoices customers with due amount. + - type: collectPayments + key: stripe_collect_payments + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + installMethods: + - with_oauth2 + - with_api_key + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + stripeAccountId: acct_123456789 + livemode: true + maskedAPIKey: sk_live_************abc + StripeAppReplaceUpdate: + type: object + required: + - name + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + type: + type: string + enum: + - stripe + description: The app's type is Stripe. + secretAPIKey: + type: string + format: password + description: The Stripe API key. + description: Resource update operation model. + StripeCheckoutSessionMode: + type: string + enum: + - setup + description: Stripe CheckoutSession.mode + StripeCustomerAppData: + type: object + required: + - type + - stripeCustomerId + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - stripe + description: The app name. + title: App Type + stripeCustomerId: + type: string + description: The Stripe customer ID. + stripeDefaultPaymentMethodId: + type: string + description: The Stripe default payment method ID. + app: + allOf: + - $ref: '#/components/schemas/StripeApp' + description: The installed stripe app this data belongs to. + readOnly: true + description: Stripe Customer App Data. + example: + type: stripe + stripeCustomerId: cus_xxxxxxxxxxxxxx + StripeCustomerAppDataBase: + type: object + required: + - stripeCustomerId + properties: + stripeCustomerId: + type: string + description: The Stripe customer ID. + stripeDefaultPaymentMethodId: + type: string + description: The Stripe default payment method ID. + description: Stripe Customer App Data Base. + StripeCustomerAppDataCreateOrUpdateItem: + type: object + required: + - type + - stripeCustomerId + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - stripe + description: The app name. + title: App Type + stripeCustomerId: + type: string + description: The Stripe customer ID. + stripeDefaultPaymentMethodId: + type: string + description: The Stripe default payment method ID. + description: Stripe Customer App Data. + example: + type: stripe + stripeCustomerId: cus_xxxxxxxxxxxxxx + StripeCustomerPortalSession: + type: object + required: + - id + - stripeCustomerId + - configurationId + - livemode + - createdAt + - returnUrl + - locale + - url + properties: + id: + type: string + description: |- + The ID of the customer portal session. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + stripeCustomerId: + type: string + description: The ID of the stripe customer. + configurationId: + type: string + description: |- + Configuration used to customize the customer portal. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + livemode: + type: boolean + description: |- + Livemode. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + createdAt: + type: string + format: date-time + description: |- + Created at. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + example: '2023-01-01T01:01:01.001Z' + returnUrl: + type: string + description: |- + Return URL. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + locale: + type: string + description: |- + Status. + /** + The IETF language tag of the locale customer portal is displayed in. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + url: + type: string + description: |- + /** + The ID of the customer.The URL to redirect the customer to after they have completed + their requested actions. + description: |- + Stripe customer portal session. + + See: https://docs.stripe.com/api/customer_portal/sessions/object + StripeTaxConfig: + type: object + required: + - code + properties: + code: + type: string + pattern: ^txcd_\d{8}$ + description: |- + Product tax code. + + See: https://docs.stripe.com/tax/tax-codes + title: Tax code + example: txcd_10000000 + description: The tax config for Stripe. + StripeWebhookEvent: + type: object + required: + - id + - type + - livemode + - created + - data + properties: + id: + type: string + description: The event ID. + type: + type: string + description: The event type. + livemode: + type: boolean + description: Live mode. + created: + type: integer + format: int32 + description: The event created timestamp. + data: + type: object + properties: + object: {} + required: + - object + description: The event data. + description: Stripe webhook event. + StripeWebhookResponse: + type: object + required: + - namespaceId + - appId + properties: + namespaceId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + appId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + message: + type: string + description: Stripe webhook response. + Subject: + type: object + required: + - createdAt + - updatedAt + - id + - key + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the subject. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + key: + type: string + description: |- + A unique, human-readable identifier for the subject. + This is typically a database ID or a customer key. + example: customer-db-id-123 + displayName: + type: string + nullable: true + description: A human-readable display name for the subject. + example: Customer Name + metadata: + type: object + additionalProperties: {} + nullable: true + description: Metadata for the subject. + example: + hubspotId: '123456' + currentPeriodStart: + type: string + format: date-time + description: The start of the current period for the subject. + example: '2023-01-01T00:00:00Z' + deprecated: true + currentPeriodEnd: + type: string + format: date-time + description: The end of the current period for the subject. + example: '2023-02-01T00:00:00Z' + deprecated: true + stripeCustomerId: + type: string + nullable: true + description: The Stripe customer ID for the subject. + deprecated: true + example: cus_JMOlctsKV8 + description: |- + A subject is a unique identifier for a usage attribution by its key. + Subjects only exist in the concept of metering. + Subjects are optional to create and work as an enrichment for the subject key like displayName, metadata, etc. + Subjects are useful when you are reporting usage events with your own database ID but want to enrich the subject with a human-readable name or metadata. + For most use cases, a subject is equivalent to a customer. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + deprecated: true + example: + createdAt: '2025-01-01T01:01:01.001Z' + updatedAt: '2025-02-01T01:01:01.001Z' + deletedAt: '2025-03-01T01:01:01.001Z' + id: 01G65Z755AFWAKHE12NY0CQ9FH + key: customer-id + displayName: Customer Name + metadata: + hubspotId: '123456' + stripeCustomerId: cus_JMOlctsKV8 + SubjectUpsert: + type: object + required: + - key + properties: + key: + type: string + description: |- + A unique, human-readable identifier for the subject. + This is typically a database ID or a customer key. + example: customer-db-id-123 + displayName: + type: string + nullable: true + description: A human-readable display name for the subject. + example: Customer Name + metadata: + type: object + additionalProperties: {} + nullable: true + description: Metadata for the subject. + example: + hubspotId: '123456' + currentPeriodStart: + type: string + format: date-time + description: The start of the current period for the subject. + example: '2023-01-01T00:00:00Z' + deprecated: true + currentPeriodEnd: + type: string + format: date-time + description: The end of the current period for the subject. + example: '2023-02-01T00:00:00Z' + deprecated: true + stripeCustomerId: + type: string + nullable: true + description: The Stripe customer ID for the subject. + deprecated: true + example: cus_JMOlctsKV8 + description: |- + A subject is a unique identifier for a user or entity. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + deprecated: true + example: + key: customer-id + displayName: Customer Name + metadata: + hubspotId: '123456' + stripeCustomerId: cus_JMOlctsKV8 + Subscription: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - status + - customerId + - currency + - billingCadence + - billingAnchor + - settlementMode + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + status: + allOf: + - $ref: '#/components/schemas/SubscriptionStatus' + description: The status of the subscription. + readOnly: true + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID of the subscription. + example: 01G65Z755AFWAKHE12NY0CQ9FH + plan: + allOf: + - $ref: '#/components/schemas/PlanReference' + description: The plan of the subscription. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + The currency code of the subscription. + Will be revised once we add multi currency support. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The billing cadence for the subscriptions. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + readOnly: true + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: The pro-rating configuration for the subscriptions. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + readOnly: true + billingAnchor: + type: string + format: date-time + description: The normalizedbilling anchor of the subscription. + example: '2023-01-01T01:01:01.001Z' + title: Billing anchor + readOnly: true + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the subscription. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + readOnly: true + description: Subscription is an exact subscription instance. + SubscriptionAddon: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - addon + - quantityAt + - quantity + - timeline + - subscriptionId + - rateCards + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + addon: + type: object + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the add-on. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + readOnly: true + version: + type: integer + minimum: 1 + description: The version of the Add-on which templates this instance. + title: Version + default: 1 + readOnly: true + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instance type of the add-on. + title: InstanceType + readOnly: true + required: + - id + - key + - version + - instanceType + description: Partially populated add-on properties. + title: Addon + quantityAt: + type: string + format: date-time + description: For which point in time the quantity was resolved to. + example: '2025-01-05T00:00:00Z' + title: QuantityAt + readOnly: true + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on. Always 1 for single instance add-ons. + title: Quantity + example: 1 + timeline: + type: array + items: + $ref: '#/components/schemas/SubscriptionAddonTimelineSegment' + description: The timeline of the add-on. The returned periods are sorted and continuous. + title: Timeline + example: + - quantity: 1 + activeFrom: '2025-01-01T00:00:00Z' + activeTo: '2025-01-02T00:00:00Z' + - quantity: 0 + activeFrom: '2025-01-02T00:00:00Z' + activeTo: '2025-01-03T00:00:00Z' + - quantity: 1 + activeFrom: '2025-01-03T00:00:00Z' + readOnly: true + subscriptionId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the subscription. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: SubscriptionID + readOnly: true + rateCards: + type: array + items: + $ref: '#/components/schemas/SubscriptionAddonRateCard' + description: The rate cards of the add-on. + title: Rate cards + readOnly: true + description: A subscription add-on, represents concrete instances of an add-on for a given subscription. + SubscriptionAddonCreate: + type: object + required: + - name + - quantity + - timing + - addon + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on. Always 1 for single instance add-ons. + title: Quantity + example: 1 + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: The timing of the operation. After the create or update, a new entry will be created in the timeline. + title: Timing + addon: + type: object + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the add-on. + example: 01G65Z755AFWAKHE12NY0CQ9FH + required: + - id + description: The add-on to create. + title: Addon + description: A subscription add-on create body. + SubscriptionAddonRateCard: + type: object + required: + - rateCard + - affectedSubscriptionItemIds + properties: + rateCard: + allOf: + - $ref: '#/components/schemas/RateCard' + description: The rate card. + title: Rate card + affectedSubscriptionItemIds: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: The IDs of the subscription items that this rate card belongs to. + title: Affected subscription item IDs + readOnly: true + description: A rate card for a subscription add-on. + SubscriptionAddonTimelineSegment: + type: object + required: + - activeFrom + - quantity + properties: + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on for the given period. + title: Quantity + example: 1 + readOnly: true + description: A subscription add-on event. + SubscriptionAddonUpdate: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on. Always 1 for single instance add-ons. + title: Quantity + example: 1 + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: The timing of the operation. After the create or update, a new entry will be created in the timeline. + title: Timing + description: Resource create or update operation model. + SubscriptionAlignment: + type: object + properties: + billablesMustAlign: + type: boolean + description: |- + Whether all Billable items and RateCards must align. + Alignment means the Price's BillingCadence must align for both duration and anchor time. + deprecated: true + currentAlignedBillingPeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current billing period. Only has value if the subscription is aligned and active. + description: Alignment details enriched with the current billing period. + SubscriptionBadRequestErrorResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + allOf: + - $ref: '#/components/schemas/SubscriptionErrorExtensions' + description: Additional properties specific to the problem type may be present. + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + SubscriptionChange: + oneOf: + - $ref: '#/components/schemas/PlanSubscriptionChange' + - $ref: '#/components/schemas/CustomSubscriptionChange' + description: Change a subscription. + SubscriptionChangeResponseBody: + type: object + required: + - current + - next + properties: + current: + allOf: + - $ref: '#/components/schemas/Subscription' + description: The current subscription before the change. + title: Current subscription + next: + allOf: + - $ref: '#/components/schemas/SubscriptionExpanded' + description: The new state of the subscription after the change. + title: The subscription it will be changed to + description: Response body for subscription change. + SubscriptionConflictErrorResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + allOf: + - $ref: '#/components/schemas/SubscriptionErrorExtensions' + description: Additional properties specific to the problem type may be present. + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + SubscriptionCreate: + oneOf: + - $ref: '#/components/schemas/PlanSubscriptionCreate' + - $ref: '#/components/schemas/CustomSubscriptionCreate' + description: Create a subscription. + SubscriptionEdit: + type: object + required: + - customizations + properties: + customizations: + type: array + items: + $ref: '#/components/schemas/SubscriptionEditOperation' + maxItems: 100 + description: |- + Batch processing commands for manipulating running subscriptions. + The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: Whether the billing period should be restarted.Timing configuration to allow for the changes to take effect at different times. + description: Subscription edit input. + SubscriptionEditOperation: + type: object + oneOf: + - $ref: '#/components/schemas/EditSubscriptionAddItem' + - $ref: '#/components/schemas/EditSubscriptionRemoveItem' + - $ref: '#/components/schemas/EditSubscriptionAddPhase' + - $ref: '#/components/schemas/EditSubscriptionRemovePhase' + - $ref: '#/components/schemas/EditSubscriptionStretchPhase' + - $ref: '#/components/schemas/EditSubscriptionUnscheduleEdit' + discriminator: + propertyName: op + mapping: + add_item: '#/components/schemas/EditSubscriptionAddItem' + remove_item: '#/components/schemas/EditSubscriptionRemoveItem' + add_phase: '#/components/schemas/EditSubscriptionAddPhase' + remove_phase: '#/components/schemas/EditSubscriptionRemovePhase' + stretch_phase: '#/components/schemas/EditSubscriptionStretchPhase' + unschedule_edit: '#/components/schemas/EditSubscriptionUnscheduleEdit' + description: The operation to be performed on the subscription. + SubscriptionErrorExtensions: + type: object + properties: + validationErrors: + type: array + items: + $ref: '#/components/schemas/ErrorExtension' + required: + - validationErrors + description: Error extensions for the Subscription Errors. + SubscriptionExpanded: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - status + - customerId + - currency + - billingCadence + - billingAnchor + - settlementMode + - phases + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/SubscriptionStatus' + description: The status of the subscription. + readOnly: true + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID of the subscription. + example: 01G65Z755AFWAKHE12NY0CQ9FH + plan: + allOf: + - $ref: '#/components/schemas/PlanReference' + description: The plan of the subscription. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + The currency code of the subscription. + Will be revised once we add multi currency support. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The billing cadence for the subscriptions. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + readOnly: true + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: The pro-rating configuration for the subscriptions. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + readOnly: true + billingAnchor: + type: string + format: date-time + description: The normalizedbilling anchor of the subscription. + example: '2023-01-01T01:01:01.001Z' + title: Billing anchor + readOnly: true + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the subscription. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + readOnly: true + alignment: + allOf: + - $ref: '#/components/schemas/SubscriptionAlignment' + description: Alignment details enriched with the current billing period. + phases: + type: array + items: + $ref: '#/components/schemas/SubscriptionPhaseExpanded' + description: The phases of the subscription. + description: Expanded subscription + SubscriptionItem: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - key + - billingCadence + - price + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier of the RateCard. + SubscriptionItem/RateCard can be identified, it has a reference: + + 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across versions) + 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version of a Feature + + 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + + We say "referenced by the Price" regardless of how a price itself is referenced, it colloquially makes sense to say "paying the same price for the same thing". In practice this should be derived from what's printed on the invoice line-item. + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature's key (if present). + billingCadence: + type: string + format: duration + nullable: true + description: |- + The billing cadence of the rate card. + When null, the rate card is a one-time purchase. + title: Billing cadence + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + title: Price + example: + type: flat + amount: '100' + paymentTerm: in_arrears + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts applied to the rate card. + title: Discounts + included: + allOf: + - $ref: '#/components/schemas/SubscriptionItemIncluded' + description: Describes what access is gained via the SubscriptionItem + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the Subscription Item. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + description: The actual contents of the Subscription, what the user gets, what they pay, etc... + SubscriptionItemIncluded: + type: object + required: + - feature + properties: + feature: + allOf: + - $ref: '#/components/schemas/Feature' + description: The feature the customer is entitled to use. + entitlement: + allOf: + - $ref: '#/components/schemas/Entitlement' + description: The entitlement of the Subscription Item. + description: Included contents like Entitlement, or the Feature. + SubscriptionPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Subscription' + description: The items in the current page. + description: Paginated response + SubscriptionPhaseCreate: + type: object + required: + - startAfter + - key + - name + properties: + startAfter: + type: string + format: duration + nullable: true + description: |- + Interval after the subscription starts to transition to the phase. + When null, the phase starts immediately after the subscription starts. + title: Start after + example: P1Y + duration: + type: string + format: duration + description: |- + The intended duration of the new phase. + Duration is required when the phase will not be the last phase. + title: Duration + example: P1M + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts on the plan. + title: Discounts + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A locally unique identifier for the phase. + name: + type: string + description: The name of the phase. + description: + type: string + description: The description of the phase. + description: Subscription phase create input. + SubscriptionPhaseExpanded: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - activeFrom + - items + - itemTimelines + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A locally unique identifier for the resource. + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts on the plan. + title: Discounts + activeFrom: + type: string + format: date-time + description: The time from which the phase is active. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The until which the Phase is active. + example: '2023-01-01T01:01:01.001Z' + items: + type: array + items: + $ref: '#/components/schemas/SubscriptionItem' + description: |- + The items of the phase. The structure is flattened to better conform to the Plan API. + The timelines are flattened according to the following rules: + - for the current phase, the `items` contains only the active item for each key + - for past phases, the `items` contains only the last item for each key + - for future phases, the `items` contains only the first version of the item for each key + itemTimelines: + type: object + additionalProperties: + type: array + items: + $ref: '#/components/schemas/SubscriptionItem' + description: Includes all versions of the items on each key, including all edits, scheduled changes, etc... + description: Expanded subscription phase + SubscriptionStatus: + type: string + enum: + - active + - inactive + - canceled + - scheduled + description: Subscription status. + SubscriptionTiming: + oneOf: + - $ref: '#/components/schemas/SubscriptionTimingEnum' + - type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + description: |- + Subscription edit timing defined when the changes should take effect. + If the provided configuration is not supported by the subscription, an error will be returned. + SubscriptionTimingEnum: + type: string + enum: + - immediate + - next_billing_cycle + description: |- + Subscription edit timing. + When immediate, the requested changes take effect immediately. + When nextBillingCycle, the requested changes take effect at the next billing cycle. + TaxBehavior: + type: string + enum: + - inclusive + - exclusive + description: |- + Tax behavior. + + This enum is used to specify whether tax is included in the price or excluded from the price. + TaxConfig: + type: object + properties: + behavior: + allOf: + - $ref: '#/components/schemas/TaxBehavior' + description: |- + Tax behavior. + + If not specified the billing profile is used to determine the tax behavior. + If not specified in the billing profile, the provider's default behavior is used. + title: Tax behavior + stripe: + allOf: + - $ref: '#/components/schemas/StripeTaxConfig' + description: Stripe tax config. + title: Stripe tax config + deprecated: true + customInvoicing: + allOf: + - $ref: '#/components/schemas/CustomInvoicingTaxConfig' + description: Custom invoicing tax config. + title: Custom invoicing tax config + deprecated: true + taxCodeId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Tax code reference. + + When both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence: + the referenced tax code entity is used and `stripe.code` is ignored. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: Tax code ID + description: Set of provider specific tax configs. + TieredPriceMode: + type: string + enum: + - volume + - graduated + description: The mode of the tiered price. + TieredPriceWithCommitments: + type: object + required: + - type + - mode + - tiers + properties: + type: + type: string + enum: + - tiered + description: |- + The type of the price. + + One of: flat, unit, or tiered. + mode: + allOf: + - $ref: '#/components/schemas/TieredPriceMode' + description: |- + Defines if the tiering mode is volume-based or graduated: + - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + - In `graduated` tiering, pricing can change as the quantity grows. + title: Mode + tiers: + type: array + items: + $ref: '#/components/schemas/PriceTier' + minItems: 1 + description: |- + The tiers of the tiered price. + At least one price component is required in each tier. + title: Tiers + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Tiered price with spend commitments. + ULIDOrExternalKey: + anyOf: + - type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + - type: string + minLength: 1 + maxLength: 256 + description: ExternalKey is a looser version of key. + description: ULID (Universally Unique Lexicographically Sortable Identifier) or external unique key. + x-go-type: string + UnauthorizedProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + UnexpectedProblemResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + type: object + additionalProperties: {} + description: Additional properties specific to the problem type may be present. + example: + validationErrors: + - code: validation_error + message: Validation error + otherAttribute: otherValue + additionalProperties: {} + description: |- + A Problem Details object (RFC 7807). + Additional properties specific to the problem type may be present. + x-go-type-import: + path: github.com/openmeterio/openmeter/pkg/models + x-go-type: models.StatusProblem + UnitPrice: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - unit + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the unit price. + description: Unit price. + UnitPriceWithCommitments: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - unit + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the unit price. + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Unit price with spend commitments. + ValidationError: + type: object + required: + - field + - code + - message + properties: + field: + type: string + description: The path to the field. + example: addons/pro/ratecards/token/featureKey + readOnly: true + code: + type: string + description: The machine readable description of the error. + example: invalid_feature_key + readOnly: true + message: + type: string + description: The human readable description of the error. + example: not found feature by key + readOnly: true + attributes: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Additional attributes. + readOnly: true + description: Validation errors providing detailed description of the issue. + ValidationIssue: + type: object + required: + - createdAt + - updatedAt + - id + - severity + - component + - message + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + severity: + allOf: + - $ref: '#/components/schemas/ValidationIssueSeverity' + description: The severity of the issue. + readOnly: true + field: + type: string + description: The field that the issue is related to, if available in JSON path format. + readOnly: true + code: + type: string + description: Machine indentifiable code for the issue, if available. + readOnly: true + component: + type: string + description: Component reporting the issue. + readOnly: true + message: + type: string + description: A human-readable description of the issue. + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional context for the issue. + readOnly: true + description: |- + ValidationIssue captures any validation issues related to the invoice. + + Issues with severity "critical" will prevent the invoice from being issued. + ValidationIssueSeverity: + type: string + enum: + - critical + - warning + description: |- + ValidationIssueSeverity describes the severity of a validation issue. + + Issues with severity "critical" will prevent the invoice from being issued. + VoidInvoiceActionCreate: + type: object + required: + - percentage + - action + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + description: How much of the total line items to be voided? (e.g. 100% means all charges are voided) + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceLineActionCreate' + description: The action to take on the line items. + description: InvoiceVoidAction describes how to handle the voided line items. + VoidInvoiceActionCreateItem: + type: object + required: + - percentage + - action + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + description: How much of the total line items to be voided? (e.g. 100% means all charges are voided) + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceLineActionCreateItem' + description: The action to take on the line items. + description: InvoiceVoidAction describes how to handle the voided line items. + VoidInvoiceActionInput: + type: object + required: + - action + - reason + properties: + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceActionCreate' + description: The action to take on the voided line items. + reason: + type: string + description: The reason for voiding the invoice. + overrides: + type: array + items: + $ref: '#/components/schemas/VoidInvoiceActionLineOverride' + nullable: true + description: |- + Per line item overrides for the action. + + If not specified, the `action` will be applied to all line items. + description: Request to void an invoice + VoidInvoiceActionLineOverride: + type: object + required: + - lineId + - action + properties: + lineId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The line item ID to override. + example: 01G65Z755AFWAKHE12NY0CQ9FH + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceActionCreateItem' + description: The action to take on the line item. + description: VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding. + VoidInvoiceLineActionCreate: + type: object + oneOf: + - $ref: '#/components/schemas/VoidInvoiceLineDiscardAction' + - $ref: '#/components/schemas/VoidInvoiceLinePendingActionCreate' + discriminator: + propertyName: type + mapping: + discard: '#/components/schemas/VoidInvoiceLineDiscardAction' + pending: '#/components/schemas/VoidInvoiceLinePendingActionCreate' + description: VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. + VoidInvoiceLineActionCreateItem: + type: object + oneOf: + - $ref: '#/components/schemas/VoidInvoiceLineDiscardAction' + - $ref: '#/components/schemas/VoidInvoiceLinePendingActionCreateItem' + discriminator: + propertyName: type + mapping: + discard: '#/components/schemas/VoidInvoiceLineDiscardAction' + pending: '#/components/schemas/VoidInvoiceLinePendingActionCreateItem' + description: VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. + VoidInvoiceLineDiscardAction: + type: object + required: + - type + properties: + type: + type: string + enum: + - discard + description: The action to take on the line item. + description: VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. + VoidInvoiceLinePendingActionCreate: + type: object + required: + - type + properties: + type: + type: string + enum: + - pending + description: The action to take on the line item. + nextInvoiceAt: + type: string + format: date-time + description: |- + The time at which the line item should be invoiced again. + + If not provided, the line item will be re-invoiced now. + example: '2023-01-01T01:01:01.001Z' + description: VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. + VoidInvoiceLinePendingActionCreateItem: + type: object + required: + - type + properties: + type: + type: string + enum: + - pending + description: The action to take on the line item. + nextInvoiceAt: + type: string + format: date-time + description: |- + The time at which the line item should be invoiced again. + + If not provided, the line item will be re-invoiced now. + example: '2023-01-01T01:01:01.001Z' + description: VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. + WindowSize: + type: string + enum: + - MINUTE + - HOUR + - DAY + - MONTH + description: Aggregation window size. + x-enum-varnames: + - Minute + - Hour + - Day + - Month + WindowedBalanceHistory: + type: object + required: + - windowedHistory + - burndownHistory + properties: + windowedHistory: + type: array + items: + $ref: '#/components/schemas/BalanceHistoryWindow' + description: |- + The windowed balance history. + - It only returns rows for windows where there was usage. + - The windows are inclusive at their start and exclusive at their end. + - The last window may be smaller than the window size and is inclusive at both ends. + burndownHistory: + type: array + items: + $ref: '#/components/schemas/GrantBurnDownHistorySegment' + description: Grant burndown history. + description: The windowed balance history. + securitySchemes: + CloudTokenAuth: + type: http + scheme: Bearer + description: Cloud API token. + CloudCookieAuth: + type: apiKey + in: cookie + name: __session + description: Cloud API web app cookie. + CloudPortalTokenAuth: + type: http + scheme: Bearer + description: Cloud consumer portal token. +servers: + - url: https://openmeter.cloud + description: Cloud + variables: {} + - url: https://127.0.0.1:8888 + description: Local + variables: {} diff --git a/api/openapi.yaml b/api/openapi.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab748cdc466102838ac4c1ba360687d070be78b5 --- /dev/null +++ b/api/openapi.yaml @@ -0,0 +1,26569 @@ +openapi: 3.0.0 +info: + title: OpenMeter API + version: 1.0.0 + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + description: |- + OpenMeter is a cloud native usage metering service. + The OpenMeter API allows you to ingest events, query meter usage, and manage resources. +tags: + - name: Subscriptions + description: With Subscriptions, you can easily start, cancel, and manage customer subscriptions. For example, provisioning them on a specific plan or assigning custom rate cards. + - name: Subjects + description: |- + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + + Subjects are entities that consume resources you wish to meter. These can range from users, servers, and services to devices. The design of subjects is intentionally generic, enabling flexible application across various metering scenarios. Typically, a subject acts as a unique identifier within your system for a user or customer. Meters are aggregating events for each subject. + - name: Product Catalog + description: 'Configure and manage your product plans, pricing tiers, and subscription offerings. ' + - name: Portal + description: With the Consumer Portal, you can build in-app user-facing dashboards where your users can track their usage in real-time. Subject scoped portal tokens can be generated on your behalf to allow restricted access to the OpenMeter API. + - name: Notifications + description: Notifications provide automated triggers when specific entitlement balances and usage thresholds are reached, ensuring that your customers and sales teams are always informed. Notify customers and internal teams when specific conditions are met, like reaching 75%, 100%, and 150% of their monthly usage allowance. [Read more](https://openmeter.io/docs/guides/notifications/overview). + - name: Meters + description: Meters specify how to aggregate events for billing and analytics purposes. Meters can be configured with multiple aggregation methods and groupings. Multiple meters can be created for the same event type, enabling flexible metering scenarios. + - name: Lookup Information + description: Lookup information for static data like currencies + - name: Events + description: Events are used to track usage of your product or service. Events are processed asynchronously by the meters, so they may not be immediately available for querying. + - name: Entitlements + description: With Entitlements, you can define and enforce usage limits, implement quota-based pricing, and manage access to features in your application. + - name: Debug + description: Debugging and testing endpoints. + - name: Customers + description: 'Manage customer subscription lifecycles and plan assignments. ' + - name: Billing + description: 'Manage your billing profiles and invoices. ' + - name: 'App: Custom Invoicing' + description: Interface third party invoicing and payment systems. + - name: 'App: Stripe' + description: Support for Stripe billing. + - name: Apps + description: "Manage integrations for extending OpenMeter's functionality. " +paths: + /api/v1/addons: + get: + operationId: listAddons + summary: List add-ons + description: List all add-ons. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted add-ons in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: id + in: query + required: false + description: Filter by addon.id attribute + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: key + in: query + required: false + description: Filter by addon.key attribute + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + style: form + - name: keyVersion + in: query + required: false + description: Filter by addon.key and addon.version attributes + schema: + type: object + additionalProperties: + type: array + items: + type: integer + style: deepObject + - name: status + in: query + required: false + description: |- + Only return add-ons with the given status. + + Usage: + - `?status=active`: return only the currently active add-ons + - `?status=draft`: return only the draft add-ons + - `?status=archived`: return only the archived add-ons + schema: + type: array + items: + $ref: '#/components/schemas/AddonStatus' + style: form + - name: currency + in: query + required: false + description: Filter by addon.currency attribute + schema: + type: array + items: + $ref: '#/components/schemas/CurrencyCode' + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/AddonOrderByOrdering.order' + - $ref: '#/components/parameters/AddonOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/AddonPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createAddon + summary: Create an add-on + description: Create a new add-on. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AddonCreate' + /api/v1/addons/{addonId}: + put: + operationId: updateAddon + summary: Update add-on + description: Update add-on by id. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AddonReplaceUpdate' + get: + operationId: getAddon + summary: Get add-on + description: Get add-on by id or key. The latest published version is returned if latter is used. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + x-go-type: string + x-go-type: string + - name: includeLatest + in: query + required: false + description: |- + Include latest version of the add-on instead of the version in active state. + + Usage: `?includeLatest=true` + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deleteAddon + summary: Delete add-on + description: |- + Soft delete add-on by id. + + Once a add-on is deleted it cannot be undeleted. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/addons/{addonId}/archive: + post: + operationId: archiveAddon + summary: Archive add-on version + description: Archive a add-on version. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/addons/{addonId}/publish: + post: + operationId: publishAddon + summary: Publish add-on + description: Publish a add-on version. + parameters: + - name: addonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Addon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/apps: + get: + operationId: listApps + summary: List apps + description: List apps. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/AppPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized: + post: + operationId: appCustomInvoicingDraftSynchronized + summary: Submit draft synchronization results + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Custom Invoicing' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomInvoicingDraftSynchronizedRequest' + /api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized: + post: + operationId: appCustomInvoicingIssuingSynchronized + summary: Submit issuing synchronization results + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Custom Invoicing' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomInvoicingFinalizedRequest' + /api/v1/apps/custom-invoicing/{invoiceId}/payment/status: + post: + operationId: appCustomInvoicingUpdatePaymentStatus + summary: Update payment status + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Custom Invoicing' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomInvoicingUpdatePaymentStatusRequest' + /api/v1/apps/{id}: + get: + operationId: getApp + summary: Get app + description: Get the app. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/App' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + put: + operationId: updateApp + summary: Update app + description: Update an app. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/App' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AppReplaceUpdate' + delete: + operationId: uninstallApp + summary: Uninstall app + description: Uninstall an app. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/apps/{id}/stripe/api-key: + put: + operationId: updateStripeAPIKey + summary: Update Stripe API key + description: |- + Update the Stripe API key. + + ⚠️ __Deprecated__: Use [`PUT /api/v1/apps/{id}`](#tag/apps/put/api/v1/apps/{id}) instead. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Stripe' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/StripeAPIKeyInput' + deprecated: true + /api/v1/apps/{id}/stripe/webhook: + post: + operationId: appStripeWebhook + summary: Stripe webhook + description: Handle stripe webhooks for apps. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeWebhookResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Stripe' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/StripeWebhookEvent' + security: + - {} + /api/v1/billing/customers: + get: + operationId: listBillingProfileCustomerOverrides + summary: List customer overrides + description: |- + List customer overrides using the specified filters. + + The response will include the customer override values and the merged billing profile values. + + If the includeAllCustomers is set to true, the list contains all customers. This mode is + useful for getting the current effective billing workflow settings for all users regardless + if they have customer orverrides or not. + parameters: + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.billingProfile' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.includeAllCustomers' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerId' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerName' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerKey' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.customerPrimaryEmail' + - $ref: '#/components/parameters/BillingProfileListCustomerOverridesParams.expand' + - $ref: '#/components/parameters/BillingProfileCustomerOverrideOrderByOrdering.order' + - $ref: '#/components/parameters/BillingProfileCustomerOverrideOrderByOrdering.orderBy' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetailsPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/customers/{customerId}: + put: + operationId: upsertBillingProfileCustomerOverride + summary: Create a new or update a customer override + description: |- + The customer override can be used to pin a given customer to a billing profile + different from the default one. + + This can be used to test the effect of different billing profiles before making them + the default ones or have different workflow settings for example for enterprise customers. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetails' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideCreate' + get: + operationId: getBillingProfileCustomerOverride + summary: Get a customer override + description: |- + Get a customer override by customer id. + + The response will include the customer override values and the merged billing profile values. + + If the customer override is not found, the default billing profile's values are returned. This behavior + allows for getting a merged profile regardless of the customer override existence. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileCustomerOverrideExpand' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetails' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + delete: + operationId: deleteBillingProfileCustomerOverride + summary: Delete a customer override + description: |- + Delete a customer override by customer id. + + This will remove the customer override and the customer will be subject to the default + billing profile's settings again. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/customers/{customerId}/invoices/pending-lines: + post: + operationId: createPendingInvoiceLine + summary: Create pending line items + description: |- + Create a new pending line item (charge). + + This call is used to create a new pending line item for the customer if required a new + gathering invoice will be created. + + A new invoice will be created if: + - there is no invoice in gathering state + - the currency of the line item doesn't match the currency of any invoices in gathering state + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePendingLineCreateResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePendingLineCreateInput' + /api/v1/billing/customers/{customerId}/invoices/simulate: + post: + operationId: simulateInvoice + summary: Simulate an invoice for a customer + description: |- + Simulate an invoice for a customer. + + This call will simulate an invoice for a customer based on the pending line items. + + The call will return the total amount of the invoice and the line items that will be included in the invoice. + parameters: + - name: customerId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoiceSimulationInput' + /api/v1/billing/invoices: + get: + operationId: listInvoices + summary: List invoices + description: |- + List invoices based on the specified filters. + + The expand option can be used to include additional information (besides the invoice header and totals) + in the response. For example by adding the expand=lines option the invoice lines will be included in the response. + + Gathering invoices will always show the current usage calculated on the fly. + parameters: + - $ref: '#/components/parameters/InvoiceListParams.statuses' + - $ref: '#/components/parameters/InvoiceListParams.extendedStatuses' + - $ref: '#/components/parameters/InvoiceListParams.issuedAfter' + - $ref: '#/components/parameters/InvoiceListParams.issuedBefore' + - $ref: '#/components/parameters/InvoiceListParams.periodStartAfter' + - $ref: '#/components/parameters/InvoiceListParams.periodStartBefore' + - $ref: '#/components/parameters/InvoiceListParams.createdAfter' + - $ref: '#/components/parameters/InvoiceListParams.createdBefore' + - $ref: '#/components/parameters/InvoiceListParams.expand' + - $ref: '#/components/parameters/InvoiceListParams.customers' + - $ref: '#/components/parameters/InvoiceListParams.includeDeleted' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/InvoiceOrderByOrdering.order' + - $ref: '#/components/parameters/InvoiceOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/invoice: + post: + operationId: invoicePendingLinesAction + summary: Invoice a customer based on the pending line items + description: |- + Create a new invoice from the pending line items. + + This should be only called if for some reason we need to invoice a customer outside of the normal billing cycle. + + When creating an invoice, the pending line items will be marked as invoiced and the invoice will be created with the total amount of the pending items. + + New pending line items will be created for the period between now() and the next billing cycle's begining date for any metered item. + + The call can return multiple invoices if the pending line items are in different currencies. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoicePendingLinesActionInput' + /api/v1/billing/invoices/{invoiceId}: + get: + operationId: getInvoice + summary: Get an invoice + description: |- + Get an invoice by ID. + + Gathering invoices will always show the current usage calculated on the fly. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/InvoiceExpand' + default: + - lines + style: form + - name: includeDeletedLines + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + delete: + operationId: deleteInvoice + summary: Delete an invoice + description: |- + Delete an invoice + + Only invoices that are in the draft (or earlier) status can be deleted. + + Invoices that are post finalization can only be voided. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + put: + operationId: updateInvoice + summary: Update an invoice + description: |- + Update an invoice + + Only invoices in draft or earlier status can be updated. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvoiceReplaceUpdate' + /api/v1/billing/invoices/{invoiceId}/advance: + post: + operationId: advanceInvoiceAction + summary: Advance the invoice's state to the next status + description: |- + Advance the invoice's state to the next status. + + The call doesn't "approve the invoice", it only advances the invoice to the next status if the transition would be automatic. + + The action can be called when the invoice's statusDetails' actions field contain the "advance" action. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/approve: + post: + operationId: approveInvoiceAction + summary: Send the invoice to the customer + description: |- + Approve an invoice and start executing the payment workflow. + + This call instantly sends the invoice to the customer using the configured billing profile app. + + This call is valid in two invoice statuses: + - `draft`: the invoice will be sent to the customer, the invluce state becomes issued + - `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes issued + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/retry: + post: + operationId: retryInvoiceAction + summary: Retry advancing the invoice after a failed attempt. + description: |- + Retry advancing the invoice after a failed attempt. + + The action can be called when the invoice's statusDetails' actions field contain the "retry" action. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/snapshot-quantities: + post: + operationId: snapshotQuantitiesInvoiceAction + summary: Snapshot quantities for usage based line items + description: |- + Snapshot quantities for usage based line items. + + This call will snapshot the quantities for all usage based line items in the invoice. + + This call is only valid in `draft.waiting_for_collection` status, where the collection period + can be skipped using this action. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/taxes/recalculate: + post: + operationId: recalculateInvoiceTaxAction + summary: Recalculate an invoice's tax amounts + description: |- + Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + + Note: charges might apply, depending on the tax provider. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + /api/v1/billing/invoices/{invoiceId}/void: + post: + operationId: voidInvoiceAction + summary: Void an invoice + description: |- + Void an invoice + + Only invoices that have been alread issued can be voided. + + Voiding an invoice will mark it as voided, the user can specify how to handle the voided line items. + parameters: + - name: invoiceId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Invoice' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/VoidInvoiceActionInput' + /api/v1/billing/profiles: + get: + operationId: listBillingProfiles + summary: List billing profiles + description: |- + List all billing profiles matching the specified filters. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing profile + will be included in the response. + parameters: + - name: includeArchived + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileExpand' + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/BillingProfileOrderByOrdering.order' + - $ref: '#/components/parameters/BillingProfileOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfilePaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + post: + operationId: createBillingProfile + summary: Create a new billing profile + description: |- + Create a new billing profile + + Billing profiles are representations of a customer's billing information. Customer overrides + can be applied to a billing profile to customize the billing behavior for a specific customer. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfile' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileCreate' + /api/v1/billing/profiles/{id}: + delete: + operationId: deleteBillingProfile + summary: Delete a billing profile + description: |- + Delete a billing profile by id. + + Only such billing profiles can be deleted that are: + - not the default one + - not pinned to any customer using customer overrides + - only have finalized invoices + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + get: + operationId: getBillingProfile + summary: Get a billing profile + description: |- + Get a billing profile by id. + + The expand option can be used to include additional information (besides the billing profile) + in the response. For example by adding the expand=apps option the apps used by the billing profile + will be included in the response. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: expand + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileExpand' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfile' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + put: + operationId: updateBillingProfile + summary: Update a billing profile + description: |- + Update a billing profile by id. + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + parameters: + - name: id + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfile' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Billing + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/BillingProfileReplaceUpdateWithWorkflow' + /api/v1/customers: + post: + operationId: createCustomer + summary: Create customer + description: Create a new customer. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Customer' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerCreate' + get: + operationId: listCustomers + summary: List customers + description: List customers. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/CustomerOrderByOrdering.order' + - $ref: '#/components/parameters/CustomerOrderByOrdering.orderBy' + - $ref: '#/components/parameters/queryCustomerList.includeDeleted' + - $ref: '#/components/parameters/queryCustomerList.key' + - $ref: '#/components/parameters/queryCustomerList.name' + - $ref: '#/components/parameters/queryCustomerList.primaryEmail' + - $ref: '#/components/parameters/queryCustomerList.subject' + - $ref: '#/components/parameters/queryCustomerList.planKey' + - $ref: '#/components/parameters/queryCustomerList.expand' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + /api/v1/customers/{customerIdOrKey}: + get: + operationId: getCustomer + summary: Get customer + description: Get a customer by ID or key. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - $ref: '#/components/parameters/queryCustomerGet' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Customer' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + put: + operationId: updateCustomer + summary: Update customer + description: Update a customer by ID. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Customer' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerReplaceUpdate' + delete: + operationId: deleteCustomer + summary: Delete customer + description: Delete a customer by ID. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + /api/v1/customers/{customerIdOrKey}/access: + get: + operationId: getCustomerAccess + summary: Get customer access + description: Get the overall access of a customer. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerAccess' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v1/customers/{customerIdOrKey}/apps: + get: + operationId: listCustomerAppData + summary: List customer app data + description: List customers app data. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/listCustomerAppDataParams.type' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/CustomerAppDataPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + put: + operationId: upsertCustomerAppData + summary: Upsert customer app data + description: Upsert customer app data. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CustomerAppData' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/CustomerAppDataCreateOrUpdateItem' + /api/v1/customers/{customerIdOrKey}/apps/{appId}: + delete: + operationId: deleteCustomerAppData + summary: Delete customer app data + description: Delete customer app data. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: appId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + /api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}/value: + get: + operationId: getCustomerEntitlementValue + summary: Get customer entitlement value + description: Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: featureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + - name: time + in: query + required: false + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementValue' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v1/customers/{customerIdOrKey}/stripe: + get: + operationId: getCustomerStripeAppData + summary: Get customer stripe app data + description: |- + Get stripe app data for a customer. + Only returns data if the customer billing profile is linked to a stripe app. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerAppData' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + put: + operationId: upsertCustomerStripeAppData + summary: Upsert customer stripe app data + description: |- + Upsert stripe app data for a customer. + Only updates data if the customer billing profile is linked to a stripe app. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerAppData' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerAppDataBase' + /api/v1/customers/{customerIdOrKey}/stripe/portal: + post: + operationId: createCustomerStripePortalSession + summary: Create Stripe customer portal session + description: |- + Create Stripe customer portal session. + Only returns URL if the customer billing profile is linked to a stripe app and customer. + + Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + change their billing address and access their invoice history. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/StripeCustomerPortalSession' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + - Apps + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateStripeCustomerPortalSessionParams' + /api/v1/customers/{customerIdOrKey}/subscriptions: + get: + operationId: listCustomerSubscriptions + summary: List customer subscriptions + description: Lists all subscriptions for a customer. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: status + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/SubscriptionStatus' + style: form + - $ref: '#/components/parameters/CustomerSubscriptionOrderByOrdering.order' + - $ref: '#/components/parameters/CustomerSubscriptionOrderByOrdering.orderBy' + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Customers + /api/v1/debug/metrics: + get: + operationId: getDebugMetrics + summary: Get event metrics + description: |- + Returns debug metrics (in OpenMetrics format) like the number of ingested events since mindnight UTC. + + The OpenMetrics Counter(s) reset every day at midnight UTC. + responses: + '200': + description: The request has succeeded. + content: + text/plain: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Debug + /api/v1/entitlements: + get: + operationId: listEntitlements + summary: List all entitlements + description: |- + List all entitlements for all the subjects and features. This endpoint is intended for administrative purposes only. + To fetch the entitlements of a specific subject please use the /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements`](#tag/entitlements/get/api/v2/entitlements) instead. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: subject + in: query + required: false + description: |- + Filtering by multiple subjects. + + Usage: `?subject=customer-1&subject=customer-2` + schema: + type: array + items: + type: string + style: form + - name: entitlementType + in: query + required: false + description: |- + Filtering by multiple entitlement types. + + Usage: `?entitlementType=metered&entitlementType=boolean` + schema: + type: array + items: + $ref: '#/components/schemas/EntitlementType' + style: form + - name: excludeInactive + in: query + required: false + description: Exclude inactive entitlements in the response (those scheduled for later or earlier) + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.order' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/ListEntitlementsResult' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + x-internal: true + /api/v1/entitlements/{entitlementId}: + get: + operationId: getEntitlementById + summary: Get entitlement by ID + description: |- + Get entitlement by ID. + + ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements/{entitlementId}`](#tag/entitlements/get/api/v2/entitlements/{entitlementId}) instead. + parameters: + - name: entitlementId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/events: + get: + operationId: listEvents + summary: List ingested events + description: |- + List ingested events within a time range. + + If the from query param is not provided it defaults to last 72 hours. + parameters: + - name: clientId + in: query + required: false + description: |- + Client ID + Useful to track progress of a query. + schema: + type: string + minLength: 1 + maxLength: 36 + explode: false + style: form + - name: ingestedAtFrom + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: ingestedAtTo + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: id + in: query + required: false + description: |- + The event ID. + + Accepts partial ID. + schema: + type: string + explode: false + style: form + - name: subject + in: query + required: false + description: |- + The event subject. + + Accepts partial subject. + schema: + type: string + explode: false + style: form + - name: customerId + in: query + required: false + description: The event customer ID. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + schema: + type: string + format: date-time + style: form + - name: limit + in: query + required: false + description: Number of events to return. + schema: + type: integer + minimum: 1 + maximum: 100 + default: 100 + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/IngestedEvent' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Events + post: + operationId: ingestEvents + description: Ingests an event or batch of events following the CloudEvents specification. + summary: Ingest events + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Events + requestBody: + required: true + content: + application/cloudevents+json: + schema: + $ref: '#/components/schemas/Event' + application/cloudevents-batch+json: + schema: + type: array + items: + $ref: '#/components/schemas/Event' + application/json: + schema: + $ref: '#/components/schemas/IngestEventsBody' + /api/v1/features: + get: + operationId: listFeatures + summary: List features + description: List features. + parameters: + - name: meterSlug + in: query + required: false + description: Filter by meterSlug + schema: + type: array + items: + type: string + style: form + - name: includeArchived + in: query + required: false + description: Include archived features in response. + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/FeatureOrderByOrdering.order' + - $ref: '#/components/parameters/FeatureOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/ListFeaturesResult' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createFeature + summary: Create feature + description: |- + Features are either metered or static. A feature is metered if meterSlug is provided at creation. + For metered features you can pass additional filters that will be applied when calculating feature usage, based on the meter's groupBy fields. + Meters with SUM, COUNT, UNIQUE_COUNT and LATEST aggregations are supported for features. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Feature' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/FeatureCreateInputs' + /api/v1/features/{featureId}: + get: + operationId: getFeature + summary: Get feature + description: Get a feature by ID. + parameters: + - name: featureId + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Feature' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deleteFeature + summary: Delete feature + description: |- + Archive a feature by ID. + + Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements cannot be created for it, but archiving the feature does not affect existing entitlements. + This means, if you want to create a new feature with the same key, and then create entitlements for it, the previous entitlements have to be deleted first on a per subject basis. + parameters: + - name: featureId + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/grants: + get: + operationId: listGrants + summary: List grants + description: |- + List all grants for all the subjects and entitlements. This endpoint is intended for administrative purposes only. + To fetch the grants of a specific entitlement please use the /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + + ⚠️ __Deprecated__: Use [`GET /api/v2/grants`](#tag/entitlements/get/api/v2/grants) instead. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: subject + in: query + required: false + description: |- + Filtering by multiple subjects. + + Usage: `?subject=customer-1&subject=customer-2` + schema: + type: array + items: + type: string + style: form + - name: includeDeleted + in: query + required: false + description: Include deleted + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/GrantOrderByOrdering.order' + - $ref: '#/components/parameters/GrantOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + anyOf: + - type: array + items: + $ref: '#/components/schemas/EntitlementGrant' + - $ref: '#/components/schemas/GrantPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/grants/{grantId}: + delete: + operationId: voidGrant + summary: Void grant + description: |- + Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed to the grant will remain, but future usage cannot be burnt down from the grant. + For example, if you have a single grant for your metered entitlement with an initial amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous usage will not be affected. + parameters: + - name: grantId + in: path + required: true + schema: + type: string + - name: at + in: query + required: false + description: |- + The time at which the grant should be voided. + Must not be in the future and must be within the current usage period of the entitlement. + Defaults to the current time if not specified. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v1/info/currencies: + get: + operationId: listCurrencies + summary: List supported currencies + description: List all supported currencies. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Currency' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Lookup Information + /api/v1/info/progress/{id}: + get: + operationId: getProgress + summary: Get progress + description: Get progress + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Progress' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Lookup Information + /api/v1/marketplace/listings: + get: + operationId: listMarketplaceListings + summary: List available apps + description: List available apps of the app marketplace. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceListingPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/marketplace/listings/{type}: + get: + operationId: getMarketplaceListing + summary: Get app details by type + description: Get a marketplace listing by type. + parameters: + - name: type + in: path + required: true + schema: + $ref: '#/components/schemas/AppType' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceListing' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/marketplace/listings/{type}/install: + post: + operationId: marketplaceAppInstall + summary: Install app + description: Install an app from the marketplace. + parameters: + - $ref: '#/components/parameters/MarketplaceInstallRequest.type' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceInstallResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceInstallRequestPayload' + /api/v1/marketplace/listings/{type}/install/apikey: + post: + operationId: marketplaceAppAPIKeyInstall + summary: Install app via API key + description: Install an marketplace app via API Key. + parameters: + - $ref: '#/components/parameters/MarketplaceApiKeyInstallRequest.type' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MarketplaceInstallResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: |- + Name of the application to install. + + If name is not provided defaults to the marketplace listing's name. + createBillingProfile: + type: boolean + description: |- + If true, a billing profile will be created for the app. + The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + default: true + apiKey: + type: string + description: |- + The API key for the provider. + For example, the Stripe API key. + required: + - apiKey + /api/v1/marketplace/listings/{type}/install/oauth2: + get: + operationId: marketplaceOAuth2InstallGetURL + summary: Get OAuth2 install URL + description: |- + Install an app via OAuth. + Returns a URL to start the OAuth 2.0 flow. + parameters: + - name: type + in: path + required: true + schema: + $ref: '#/components/schemas/AppType' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/ClientAppStartResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/marketplace/listings/{type}/install/oauth2/authorize: + get: + operationId: marketplaceOAuth2InstallAuthorize + summary: Install app via OAuth2 + description: |- + Authorize OAuth2 code. + Verifies the OAuth code and exchanges it for a token and refresh token + parameters: + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantSuccessParams.state' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantSuccessParams.code' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantErrorParams.error' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantErrorParams.error_description' + - $ref: '#/components/parameters/OAuth2AuthorizationCodeGrantErrorParams.error_uri' + - $ref: '#/components/parameters/MarketplaceOAuth2InstallAuthorizeRequest.type' + responses: + '303': + description: Redirection + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Apps + /api/v1/meters: + get: + operationId: listMeters + summary: List meters + description: List meters. + parameters: + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/MeterOrderByOrdering.order' + - $ref: '#/components/parameters/MeterOrderByOrdering.orderBy' + - $ref: '#/components/parameters/queryMeterList.includeDeleted' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + post: + operationId: createMeter + summary: Create meter + description: Create a meter. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MeterCreate' + /api/v1/meters/{meterIdOrSlug}: + get: + operationId: getMeter + summary: Get meter + description: Get a meter by ID or slug. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + put: + operationId: updateMeter + summary: Update meter + description: Update a meter. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Meter' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MeterUpdate' + delete: + operationId: deleteMeter + summary: Delete meter + description: Delete a meter. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + /api/v1/meters/{meterIdOrSlug}/group-by/{groupByKey}/values: + get: + operationId: listMeterGroupByValues + summary: List meter group by values + description: List meter group by values. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: groupByKey + in: path + required: true + schema: + type: string + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. Defaults to 24 hours ago. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + /api/v1/meters/{meterIdOrSlug}/query: + get: + operationId: queryMeter + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - $ref: '#/components/parameters/MeterQuery.clientId' + - $ref: '#/components/parameters/MeterQuery.from' + - $ref: '#/components/parameters/MeterQuery.to' + - $ref: '#/components/parameters/MeterQuery.windowSize' + - $ref: '#/components/parameters/MeterQuery.windowTimeZone' + - $ref: '#/components/parameters/MeterQuery.subject' + - $ref: '#/components/parameters/MeterQuery.filterCustomerId' + - $ref: '#/components/parameters/MeterQuery.filterGroupBy' + - $ref: '#/components/parameters/MeterQuery.advancedMeterGroupByFilters' + - $ref: '#/components/parameters/MeterQuery.groupBy' + description: Query meter for usage. + summary: Query meter + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryResult' + text/csv: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + post: + operationId: queryMeterPost + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + summary: Query meter + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryResult' + text/csv: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryRequest' + /api/v1/meters/{meterIdOrSlug}/subjects: + get: + operationId: listMeterSubjects + summary: List meter subjects + description: List subjects for a meter. + parameters: + - name: meterIdOrSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. Defaults to the beginning of time. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Meters + /api/v1/notification/channels: + get: + operationId: listNotificationChannels + summary: List notification channels + description: List all notification channels. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted notification channels in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: includeDisabled + in: query + required: false + description: |- + Include disabled notification channels in response. + + Usage: `?includeDisabled=false` + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/NotificationChannelOrderByOrdering.order' + - $ref: '#/components/parameters/NotificationChannelOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + post: + operationId: createNotificationChannel + summary: Create a notification channel + description: Create a new notification channel. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannel' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelCreateRequest' + /api/v1/notification/channels/{channelId}: + put: + operationId: updateNotificationChannel + summary: Update a notification channel + description: Update notification channel. + parameters: + - name: channelId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannel' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannelCreateRequest' + get: + operationId: getNotificationChannel + summary: Get notification channel + description: Get a notification channel by id. + parameters: + - name: channelId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationChannel' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + delete: + operationId: deleteNotificationChannel + summary: Delete a notification channel + description: |- + Soft delete notification channel by id. + + Once a notification channel is deleted it cannot be undeleted. + parameters: + - name: channelId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/events: + get: + operationId: listNotificationEvents + summary: List notification events + description: List all notification events. + parameters: + - name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: feature + in: query + required: false + description: |- + Filtering by multiple feature ids or keys. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: subject + in: query + required: false + description: |- + Filtering by multiple subject ids or keys. + + Usage: `?subject=subject-1&subject=subject-2` + schema: + type: array + items: + type: string + style: form + - name: rule + in: query + required: false + description: |- + Filtering by multiple rule ids. + + Usage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5` + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: channel + in: query + required: false + description: |- + Filtering by multiple channel ids. + + Usage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J` + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/NotificationEventOrderByOrdering.order' + - $ref: '#/components/parameters/NotificationEventOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEventPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/events/{eventId}: + get: + operationId: getNotificationEvent + summary: Get notification event + description: Get a notification event by id. + parameters: + - name: eventId + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEvent' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/events/{eventId}/resend: + post: + operationId: resendNotificationEvent + summary: Re-send notification event + parameters: + - name: eventId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '202': + description: The request has been accepted for processing, but processing has not yet completed. + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEventResendRequest' + /api/v1/notification/rules: + get: + operationId: listNotificationRules + summary: List notification rules + description: List all notification rules. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted notification rules in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: includeDisabled + in: query + required: false + description: |- + Include disabled notification rules in response. + + Usage: `?includeDisabled=false` + schema: + type: boolean + default: false + explode: false + style: form + - name: feature + in: query + required: false + description: |- + Filtering by multiple feature ids/keys. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ULID (Universally Unique Lexicographically Sortable Identifier). + A key is a unique string that is used to identify a resource. + + TODO: this is a temporary solution to support both ULID and Key in the same spec for codegen. + style: form + - name: channel + in: query + required: false + description: |- + Filtering by multiple notifiaction channel ids. + + Usage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3` + schema: + type: array + items: + type: string + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/NotificationRuleOrderByOrdering.order' + - $ref: '#/components/parameters/NotificationRuleOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRulePaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + post: + operationId: createNotificationRule + summary: Create a notification rule + description: Create a new notification rule. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRule' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRuleCreateRequest' + /api/v1/notification/rules/{ruleId}: + put: + operationId: updateNotificationRule + summary: Update a notification rule + description: Update notification rule. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRule' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRuleCreateRequest' + get: + operationId: getNotificationRule + summary: Get notification rule + description: Get a notification rule by id. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationRule' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + delete: + operationId: deleteNotificationRule + summary: Delete a notification rule + description: |- + Soft delete notification rule by id. + + Once a notification rule is deleted it cannot be undeleted. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/notification/rules/{ruleId}/test: + post: + operationId: testNotificationRule + summary: Test notification rule + description: Test a notification rule by sending a test event with random data. + parameters: + - name: ruleId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationEvent' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Notifications + /api/v1/plans: + get: + operationId: listPlans + summary: List plans + description: List all plans. + parameters: + - name: includeDeleted + in: query + required: false + description: |- + Include deleted plans in response. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: id + in: query + required: false + description: Filter by plan.id attribute + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: key + in: query + required: false + description: Filter by plan.key attribute + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + style: form + - name: keyVersion + in: query + required: false + description: Filter by plan.key and plan.version attributes + schema: + type: object + additionalProperties: + type: array + items: + type: integer + style: deepObject + - name: status + in: query + required: false + description: |- + Only return plans with the given status. + + Usage: + - `?status=active`: return only the currently active plan + - `?status=draft`: return only the draft plan + - `?status=archived`: return only the archived plans + schema: + type: array + items: + $ref: '#/components/schemas/PlanStatus' + style: form + - name: currency + in: query + required: false + description: Filter by plan.currency attribute + schema: + type: array + items: + $ref: '#/components/schemas/CurrencyCode' + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/PlanOrderByOrdering.order' + - $ref: '#/components/parameters/PlanOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createPlan + summary: Create a plan + description: Create a new plan. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanCreate' + /api/v1/plans/{planIdOrKey}/next: + post: + operationId: nextPlan + summary: New draft plan + description: |- + Create a new draft version from plan. + It returns error if there is already a plan in draft or planId does not reference the latest published version. + parameters: + - name: planIdOrKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + x-go-type: string + x-go-type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + deprecated: true + /api/v1/plans/{planId}: + put: + operationId: updatePlan + summary: Update a plan + description: Update plan by id. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanReplaceUpdate' + get: + operationId: getPlan + summary: Get plan + description: Get a plan by id or key. The latest published version is returned if latter is used. + parameters: + - name: planId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + x-go-type: string + x-go-type: string + - name: includeLatest + in: query + required: false + description: |- + Include latest version of the Plan instead of the version in active state. + + Usage: `?includeLatest=true` + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deletePlan + summary: Delete plan + description: |- + Soft delete plan by plan.id. + + Once a plan is deleted it cannot be undeleted. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/plans/{planId}/addons: + get: + operationId: listPlanAddons + summary: List all available add-ons for plan + description: List all available add-ons for plan. + parameters: + - name: planId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: includeDeleted + in: query + required: false + description: |- + Include deleted plan add-on assignments. + + Usage: `?includeDeleted=true` + schema: + type: boolean + default: false + explode: false + style: form + - name: id + in: query + required: false + description: Filter by addon.id attribute. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + - name: key + in: query + required: false + description: Filter by addon.key attribute. + schema: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + style: form + - name: keyVersion + in: query + required: false + description: Filter by addon.key and addon.version attributes. + schema: + type: object + additionalProperties: + type: array + items: + type: integer + style: deepObject + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/PlanAddonOrderByOrdering.order' + - $ref: '#/components/parameters/PlanAddonOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddonPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + post: + operationId: createPlanAddon + summary: Create new add-on assignment for plan + description: Create new add-on assignment for plan. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddonCreate' + /api/v1/plans/{planId}/addons/{planAddonId}: + put: + operationId: updatePlanAddon + summary: Update add-on assignment for plan + description: Update add-on assignment for plan. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: planAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddonReplaceUpdate' + get: + operationId: getPlanAddon + summary: Get add-on assignment for plan + description: Get add-on assignment for plan by id. + parameters: + - name: planId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: planAddonId + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PlanAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + delete: + operationId: deletePlanAddon + summary: Delete add-on assignment for plan + description: |- + Delete add-on assignment for plan. + + Once a plan is deleted it cannot be undeleted. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: planAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/plans/{planId}/archive: + post: + operationId: archivePlan + summary: Archive plan version + description: Archive a plan version. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/plans/{planId}/publish: + post: + operationId: publishPlan + summary: Publish plan + description: Publish a plan version. + parameters: + - name: planId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Plan' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Product Catalog + /api/v1/portal/meters/{meterSlug}/query: + get: + operationId: queryPortalMeter + parameters: + - name: meterSlug + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + - $ref: '#/components/parameters/MeterQuery.clientId' + - $ref: '#/components/parameters/MeterQuery.from' + - $ref: '#/components/parameters/MeterQuery.to' + - $ref: '#/components/parameters/MeterQuery.windowSize' + - $ref: '#/components/parameters/MeterQuery.windowTimeZone' + - $ref: '#/components/parameters/MeterQuery.filterCustomerId' + - $ref: '#/components/parameters/MeterQuery.filterGroupBy' + - $ref: '#/components/parameters/MeterQuery.advancedMeterGroupByFilters' + - $ref: '#/components/parameters/MeterQuery.groupBy' + description: Query meter for consumer portal. This endpoint is publicly exposable to consumers. Query meter for consumer portal. This endpoint is publicly exposable to consumers. + summary: Query meter Query meter + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/MeterQueryResult' + text/csv: + schema: + type: string + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + security: + - PortalTokenAuth: [] + /api/v1/portal/tokens: + post: + operationId: createPortalToken + summary: Create consumer portal token + description: Create a consumer portal token. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/PortalToken' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PortalToken' + get: + operationId: listPortalTokens + summary: List consumer portal tokens + description: List tokens. + parameters: + - name: limit + in: query + required: false + schema: + type: integer + minimum: 1 + maximum: 100 + default: 25 + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/PortalToken' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + /api/v1/portal/tokens/invalidate: + post: + operationId: invalidatePortalTokens + summary: Invalidate portal tokens + description: Invalidates consumer portal tokens by ID or subject. + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Portal + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + id: + type: string + description: Invalidate a portal token by ID. + subject: + type: string + description: Invalidate all portal tokens for a subject. + /api/v1/stripe/checkout/sessions: + post: + operationId: createStripeCheckoutSession + summary: Create checkout session + description: Create checkout session. + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/CreateStripeCheckoutSessionResult' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - 'App: Stripe' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateStripeCheckoutSessionRequest' + /api/v1/subjects: + get: + operationId: listSubjects + summary: List subjects + description: |- + List subjects. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Subject' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + deprecated: true + post: + operationId: upsertSubject + summary: Upsert subject + description: |- + Upserts a subject. Creates or updates subject. + + If the subject doesn't exist, it will be created. + If the subject exists, it will be partially updated with the provided fields. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Subject' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + requestBody: + required: true + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SubjectUpsert' + deprecated: true + /api/v1/subjects/{subjectIdOrKey}: + get: + operationId: getSubject + summary: Get subject + description: |- + Get subject by ID or key. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subject' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + deprecated: true + delete: + operationId: deleteSubject + summary: Delete subject + description: |- + Delete subject by ID or key. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subjects + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements: + post: + operationId: createEntitlement + summary: Create a subject entitlement + description: |- + OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + + - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + + A given subject can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + + ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementCreateInputs' + deprecated: true + get: + operationId: listSubjectEntitlements + summary: List subject entitlements + description: |- + List all entitlements for a subject. For checking entitlement access, use the /value endpoint instead. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants: + get: + operationId: listEntitlementGrants + summary: List subject entitlement grants + description: |- + List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - name: orderBy + in: query + required: false + schema: + allOf: + - $ref: '#/components/schemas/GrantOrderBy' + default: updatedAt + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/EntitlementGrant' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + post: + operationId: createGrant + summary: Create subject entitlement grant + description: |- + Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + + ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrant' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrantCreateInput' + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override: + put: + operationId: overrideEntitlement + summary: Override subject entitlement + description: |- + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided subject-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + + ⚠️ __Deprecated__: Use [`PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override`](#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementCreateInputs' + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value: + get: + operationId: getEntitlementValue + summary: Get subject entitlement value + description: |- + This endpoint should be used for access checks and enforcement. All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + + For convenience reasons, /value works with both entitlementId and featureKey. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + - name: time + in: query + required: false + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementValue' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}: + get: + operationId: getEntitlement + summary: Get subject entitlement + description: |- + Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Entitlement' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + delete: + operationId: deleteEntitlement + summary: Delete subject entitlement + description: |- + Deleting an entitlement revokes access to the associated feature. As a single subject can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + + ⚠️ __Deprecated__: Use [`DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history: + get: + operationId: getEntitlementHistory + summary: Get subject entitlement history + description: |- + Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + + ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + - name: from + in: query + required: false + description: 'Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter.' + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + If not now then gets truncated to the granularity of the underlying meter. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: windowSize + in: query + required: true + description: Windowsize + schema: + $ref: '#/components/schemas/WindowSize' + explode: false + style: form + - name: windowTimeZone + in: query + required: false + description: The timezone used when calculating the windows. + schema: + type: string + default: UTC + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/WindowedBalanceHistory' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + deprecated: true + /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset: + post: + operationId: resetEntitlementUsage + summary: Reset subject entitlement + description: |- + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the subjects billing period to enforce usage based on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + + ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) instead. + parameters: + - name: subjectIdOrKey + in: path + required: true + schema: + type: string + - name: entitlementId + in: path + required: true + schema: + type: string + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ResetEntitlementUsageInput' + deprecated: true + /api/v1/subscriptions: + post: + operationId: createSubscription + summary: Create subscription + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionCreate' + /api/v1/subscriptions/{subscriptionId}: + get: + operationId: getSubscription + summary: Get subscription + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: at + in: query + required: false + description: The time at which the subscription should be queried. If not provided the current time is used. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionExpanded' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + patch: + operationId: editSubscription + summary: Edit subscription + description: |- + Batch processing commands for manipulating running subscriptions. + The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionEdit' + delete: + operationId: deleteSubscription + summary: Delete subscription + description: Deletes a subscription. Only scheduled subscriptions can be deleted. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + /api/v1/subscriptions/{subscriptionId}/addons: + post: + operationId: createSubscriptionAddon + summary: Create subscription addon + description: Create a new subscription addon, either providing the key or the id of the addon. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddonCreate' + get: + operationId: listSubscriptionAddons + summary: List subscription addons + description: List all addons of a subscription. In the returned list will match to a set unique by addonId. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + /api/v1/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}: + get: + operationId: getSubscriptionAddon + summary: Get subscription addon + description: Get a subscription addon by id. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: subscriptionAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + patch: + operationId: updateSubscriptionAddon + summary: Update subscription addon + description: 'Updates a subscription addon (allows changing the quantity: purchasing more instances or cancelling the current instances)' + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + - name: subscriptionAddonId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddon' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionAddonUpdate' + /api/v1/subscriptions/{subscriptionId}/cancel: + post: + operationId: cancelSubscription + summary: Cancel subscription + description: |- + Cancels the subscription. + Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancellation time. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: If not provided the subscription is canceled immediately. + /api/v1/subscriptions/{subscriptionId}/change: + post: + operationId: changeSubscription + summary: Change subscription + description: |- + Closes a running subscription and starts a new one according to the specification. + Can be used for upgrades, downgrades, and plan changes. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionChangeResponseBody' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionChange' + /api/v1/subscriptions/{subscriptionId}/migrate: + post: + operationId: migrateSubscription + summary: Migrate subscription + description: |- + Migrates the subscripiton to the provided version of the current plan. + If possible, the migration will be done immediately. + If not, the migration will be scheduled to the end of the current billing period. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/SubscriptionChangeResponseBody' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the migration, when the migration should take effect. + If not supported by the subscription, 400 will be returned. + default: immediate + targetVersion: + type: integer + minimum: 1 + description: |- + The version of the plan to migrate to. + If not provided, the subscription will migrate to the latest version of the current plan. + startingPhase: + type: string + minLength: 1 + description: |- + The key of the phase to start the subscription in. + If not provided, the subscription will start in the first phase of the plan. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + example: '2023-01-01T01:01:01.001Z' + /api/v1/subscriptions/{subscriptionId}/restore: + post: + operationId: restoreSubscription + summary: Restore subscription + description: |- + Restores a canceled subscription. + Any subscription scheduled to start later will be deleted and this subscription will be continued indefinitely. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + deprecated: true + /api/v1/subscriptions/{subscriptionId}/unschedule-cancelation: + post: + operationId: unscheduleCancelation + summary: Unschedule cancelation + description: Cancels the scheduled cancelation. + parameters: + - name: subscriptionId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/Subscription' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionBadRequestErrorResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/SubscriptionConflictErrorResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Subscriptions + /api/v2/customers/{customerIdOrKey}/entitlements: + post: + operationId: createCustomerEntitlementV2 + summary: Create a customer entitlement + description: |- + OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + + - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + + A given customer can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + + Once an entitlement is created you cannot modify it, only delete it. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2CreateInputs' + get: + operationId: listCustomerEntitlementsV2 + summary: List customer entitlements + description: List all entitlements for a customer. For checking entitlement access, use the /value endpoint instead. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.order' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}: + get: + operationId: getCustomerEntitlementV2 + summary: Get customer entitlement + description: |- + Get entitlement by feature key. For checking entitlement access, use the /value endpoint instead. + If featureKey is used, the entitlement is resolved for the current timestamp. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + delete: + operationId: deleteCustomerEntitlementV2 + summary: Delete customer entitlement + description: |- + Deleting an entitlement revokes access to the associated feature. As a single customer can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants: + get: + operationId: listCustomerEntitlementGrantsV2 + summary: List customer entitlement grants + description: List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: includeDeleted + in: query + required: false + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/GrantOrderByOrdering.order' + - $ref: '#/components/parameters/GrantOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/GrantV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + post: + operationId: createCustomerEntitlementGrantV2 + summary: Create customer entitlement grant + description: |- + Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + + A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + + Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + + Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + + Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + + Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrantV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementGrantCreateInputV2' + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history: + get: + operationId: getCustomerEntitlementHistoryV2 + summary: Get customer entitlement history + description: |- + Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + + BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + + WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: from + in: query + required: false + description: 'Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter.' + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: to + in: query + required: false + description: |- + End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + If not now then gets truncated to the granularity of the underlying meter. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + - name: windowSize + in: query + required: true + description: Windowsize + schema: + $ref: '#/components/schemas/WindowSize' + explode: false + style: form + - name: windowTimeZone + in: query + required: false + description: The timezone used when calculating the windows. + schema: + type: string + default: UTC + explode: false + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/WindowedBalanceHistory' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override: + put: + operationId: overrideCustomerEntitlementV2 + summary: Override customer entitlement + description: |- + Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided customer-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + + This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + responses: + '201': + description: The request has succeeded and a new resource has been created as a result. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '409': + description: The request could not be completed due to a conflict with the current state of the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2CreateInputs' + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset: + post: + operationId: resetCustomerEntitlementUsageV2 + summary: Reset customer entitlement + description: |- + Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the customers billing period to enforce usage based on their subscription. + + Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + responses: + '204': + description: 'There is no content to send for this request, but the headers may be useful. ' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ResetEntitlementUsageInput' + /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value: + get: + operationId: getCustomerEntitlementValueV2 + summary: Get customer entitlement value + description: Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + parameters: + - name: customerIdOrKey + in: path + required: true + schema: + $ref: '#/components/schemas/ULIDOrExternalKey' + - name: entitlementIdOrFeatureKey + in: path + required: true + schema: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + - name: time + in: query + required: false + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementValueV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + - Customers + /api/v2/entitlements: + get: + operationId: listEntitlementsV2 + summary: List all entitlements + description: |- + List all entitlements for all the customers and features. This endpoint is intended for administrative purposes only. + To fetch the entitlements of a specific subject please use the /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: customerKeys + in: query + required: false + description: |- + Filtering by multiple customers. + + Usage: `?customerKeys=customer-1&customerKeys=customer-3` + schema: + type: array + items: + type: string + style: form + - name: customerIds + in: query + required: false + description: |- + Filtering by multiple customers. + + Usage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9` + schema: + type: array + items: + type: string + style: form + - name: entitlementType + in: query + required: false + description: |- + Filtering by multiple entitlement types. + + Usage: `?entitlementType=metered&entitlementType=boolean` + schema: + type: array + items: + $ref: '#/components/schemas/EntitlementType' + style: form + - name: excludeInactive + in: query + required: false + description: Exclude inactive entitlements in the response (those scheduled for later or earlier) + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.order' + - $ref: '#/components/parameters/EntitlementOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v2/entitlements/{entitlementId}: + get: + operationId: getEntitlementByIdV2 + summary: Get entitlement by ID + description: Get entitlement by ID. + parameters: + - name: entitlementId + in: path + required: true + schema: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + example: 01G65Z755AFWAKHE12NY0CQ9FH + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/EntitlementV2' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '404': + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements + /api/v2/events: + get: + operationId: listEventsV2 + summary: List ingested events + description: List ingested events with advanced filtering and cursor pagination. + parameters: + - $ref: '#/components/parameters/CursorPagination.cursor' + - $ref: '#/components/parameters/CursorPagination.limit' + - name: clientId + in: query + required: false + description: |- + Client ID + Useful to track progress of a query. + schema: + type: string + minLength: 1 + maxLength: 36 + explode: false + style: form + - name: filter + in: query + required: false + description: The filter for the events encoded as JSON string. + content: + application/json: + schema: + properties: + id: + $ref: '#/components/schemas/FilterString' + source: + $ref: '#/components/schemas/FilterString' + subject: + $ref: '#/components/schemas/FilterString' + customerId: + $ref: '#/components/schemas/FilterIDExact' + type: + $ref: '#/components/schemas/FilterString' + time: + $ref: '#/components/schemas/FilterTime' + ingestedAt: + $ref: '#/components/schemas/FilterTime' + format: application/json + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/IngestedEventCursorPaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Events + /api/v2/grants: + get: + operationId: listGrantsV2 + summary: List grants + description: |- + List all grants for all the customers and entitlements. This endpoint is intended for administrative purposes only. + To fetch the grants of a specific entitlement please use the /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + If page is provided that takes precedence and the paginated response is returned. + parameters: + - name: feature + in: query + required: false + description: |- + Filtering by multiple features. + + Usage: `?feature=feature-1&feature=feature-2` + schema: + type: array + items: + type: string + style: form + - name: customer + in: query + required: false + description: |- + Filtering by multiple customers (either by ID or key). + + Usage: `?customer=customer-1&customer=customer-2` + schema: + type: array + items: + $ref: '#/components/schemas/ULIDOrExternalKey' + style: form + - name: includeDeleted + in: query + required: false + description: Include deleted + schema: + type: boolean + default: false + explode: false + style: form + - $ref: '#/components/parameters/Pagination.page' + - $ref: '#/components/parameters/Pagination.pageSize' + - $ref: '#/components/parameters/LimitOffset.offset' + - $ref: '#/components/parameters/LimitOffset.limit' + - $ref: '#/components/parameters/GrantOrderByOrdering.order' + - $ref: '#/components/parameters/GrantOrderByOrdering.orderBy' + responses: + '200': + description: The request has succeeded. + content: + application/json: + schema: + $ref: '#/components/schemas/GrantV2PaginatedResponse' + '400': + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestProblemResponse' + '401': + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedProblemResponse' + '403': + description: The server understood the request but refuses to authorize it. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenProblemResponse' + '412': + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PreconditionFailedProblemResponse' + '500': + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalServerErrorProblemResponse' + '503': + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ServiceUnavailableProblemResponse' + default: + description: An unexpected error response. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnexpectedProblemResponse' + tags: + - Entitlements +components: + parameters: + AddonOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + AddonOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/AddonOrderBy' + explode: false + style: form + BillingProfileCustomerOverrideOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + BillingProfileCustomerOverrideOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/BillingProfileCustomerOverrideOrderBy' + explode: false + style: form + BillingProfileListCustomerOverridesParams.billingProfile: + name: billingProfile + in: query + required: false + description: Filter by billing profile. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + BillingProfileListCustomerOverridesParams.customerId: + name: customerId + in: query + required: false + description: Filter by customer id. + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + BillingProfileListCustomerOverridesParams.customerKey: + name: customerKey + in: query + required: false + description: Filter by customer key + schema: + type: string + explode: false + style: form + BillingProfileListCustomerOverridesParams.customerName: + name: customerName + in: query + required: false + description: Filter by customer name. + schema: + type: string + explode: false + style: form + BillingProfileListCustomerOverridesParams.customerPrimaryEmail: + name: customerPrimaryEmail + in: query + required: false + description: Filter by customer primary email + schema: + type: string + explode: false + style: form + BillingProfileListCustomerOverridesParams.customersWithoutPinnedProfile: + name: customersWithoutPinnedProfile + in: query + required: false + description: Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. + schema: + type: boolean + style: form + BillingProfileListCustomerOverridesParams.expand: + name: expand + in: query + required: false + description: Expand the response with additional details. + schema: + type: array + items: + $ref: '#/components/schemas/BillingProfileCustomerOverrideExpand' + style: form + BillingProfileListCustomerOverridesParams.includeAllCustomers: + name: includeAllCustomers + in: query + required: false + description: |- + Include customers without customer overrides. + + If set to false only the customers specifically associated with a billing profile will be returned. + + If set to true, in case of the default billing profile, all customers will be returned. + schema: + type: boolean + default: true + style: form + BillingProfileOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + BillingProfileOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/BillingProfileOrderBy' + explode: false + style: form + CursorPagination.cursor: + name: cursor + in: query + required: false + description: The cursor after which to start the pagination. + schema: + type: string + explode: false + style: form + CursorPagination.limit: + name: limit + in: query + required: false + description: The limit of the pagination. + schema: + type: integer + minimum: 1 + maximum: 100 + default: 100 + explode: false + style: form + CustomerOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + CustomerOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/CustomerOrderBy' + explode: false + style: form + CustomerSubscriptionOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + CustomerSubscriptionOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/CustomerSubscriptionOrderBy' + explode: false + style: form + EntitlementOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + EntitlementOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/EntitlementOrderBy' + explode: false + style: form + FeatureOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + FeatureOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/FeatureOrderBy' + explode: false + style: form + GrantOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + GrantOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/GrantOrderBy' + explode: false + style: form + InvoiceListParams.createdAfter: + name: createdAfter + in: query + required: false + description: |- + Filter by invoice created time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.createdBefore: + name: createdBefore + in: query + required: false + description: |- + Filter by invoice created time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.customers: + name: customers + in: query + required: false + description: Filter by customer ID + schema: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + style: form + InvoiceListParams.expand: + name: expand + in: query + required: false + description: What parts of the list output to expand in listings + schema: + type: array + items: + $ref: '#/components/schemas/InvoiceExpand' + style: form + InvoiceListParams.extendedStatuses: + name: extendedStatuses + in: query + required: false + description: Filter by invoice extended statuses + schema: + type: array + items: + type: string + style: form + InvoiceListParams.includeDeleted: + name: includeDeleted + in: query + required: false + description: Include deleted invoices + schema: + type: boolean + explode: false + style: form + InvoiceListParams.issuedAfter: + name: issuedAfter + in: query + required: false + description: |- + Filter by invoice issued time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.issuedBefore: + name: issuedBefore + in: query + required: false + description: |- + Filter by invoice issued time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.periodStartAfter: + name: periodStartAfter + in: query + required: false + description: |- + Filter by period start time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.periodStartBefore: + name: periodStartBefore + in: query + required: false + description: |- + Filter by period start time. + Inclusive. + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + InvoiceListParams.statuses: + name: statuses + in: query + required: false + description: Filter by the invoice status. + schema: + type: array + items: + $ref: '#/components/schemas/InvoiceStatus' + style: form + InvoiceOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + InvoiceOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/InvoiceOrderBy' + explode: false + style: form + LimitOffset.limit: + name: limit + in: query + required: false + description: |- + Number of items to return. + + Default is 100. + schema: + type: integer + minimum: 1 + maximum: 1000 + default: 100 + explode: false + style: form + LimitOffset.offset: + name: offset + in: query + required: false + description: |- + Number of items to skip. + + Default is 0. + schema: + type: integer + minimum: 0 + default: 0 + explode: false + style: form + MarketplaceApiKeyInstallRequest.type: + name: type + in: path + required: true + description: The type of the app to install. + schema: + $ref: '#/components/schemas/AppType' + MarketplaceInstallRequest.type: + name: type + in: path + required: true + description: The type of the app to install. + schema: + $ref: '#/components/schemas/AppType' + MarketplaceOAuth2InstallAuthorizeRequest.type: + name: type + in: path + required: true + description: The type of the app to install. + schema: + $ref: '#/components/schemas/AppType' + MeterOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + MeterOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/MeterOrderBy' + explode: false + style: form + MeterQuery.advancedMeterGroupByFilters: + name: advancedMeterGroupByFilters + in: query + required: false + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + content: + application/json: + schema: + additionalProperties: + $ref: '#/components/schemas/FilterString' + title: Advanced meter group by filters + format: application/json + MeterQuery.clientId: + name: clientId + in: query + required: false + description: |- + Client ID + Useful to track progress of a query. + schema: + type: string + minLength: 1 + maxLength: 36 + explode: false + style: form + MeterQuery.filterCustomerId: + name: filterCustomerId + in: query + required: false + description: |- + Filtering by multiple customers. + + For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + schema: + type: array + items: + type: string + maxItems: 100 + style: form + MeterQuery.filterGroupBy: + name: filterGroupBy + in: query + required: false + description: |- + Simple filter for group bys with exact match. + + For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + + ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + schema: + type: object + additionalProperties: + type: string + style: deepObject + deprecated: true + MeterQuery.from: + name: from + in: query + required: false + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + + For example: ?from=2025-01-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + MeterQuery.groupBy: + name: groupBy + in: query + required: false + description: |- + If not specified a single aggregate will be returned for each subject and time window. + `subject` is a reserved group by value. + + For example: ?groupBy=subject&groupBy=model + schema: + type: array + items: + type: string + style: form + MeterQuery.subject: + name: subject + in: query + required: false + description: |- + Filtering by multiple subjects. + + For example: ?subject=subject-1&subject=subject-2 + schema: + type: array + items: + type: string + style: form + MeterQuery.to: + name: to + in: query + required: false + description: |- + End date-time in RFC 3339 format. + + Inclusive. + + For example: ?to=2025-02-01T00%3A00%3A00.000Z + schema: + type: string + format: date-time + example: '2023-01-01T01:01:01.001Z' + style: form + MeterQuery.windowSize: + name: windowSize + in: query + required: false + description: |- + If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + + For example: ?windowSize=DAY + schema: + $ref: '#/components/schemas/WindowSize' + explode: false + style: form + MeterQuery.windowTimeZone: + name: windowTimeZone + in: query + required: false + description: |- + The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + If not specified, the UTC timezone will be used. + + For example: ?windowTimeZone=UTC + schema: + type: string + default: UTC + explode: false + style: form + NotificationChannelOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + NotificationChannelOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/NotificationChannelOrderBy' + explode: false + style: form + NotificationEventOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + NotificationEventOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/NotificationEventOrderBy' + explode: false + style: form + NotificationRuleOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + NotificationRuleOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/NotificationRuleOrderBy' + explode: false + style: form + OAuth2AuthorizationCodeGrantErrorParams.error: + name: error + in: query + required: false + description: |- + Error code. + Required with the error response. + schema: + $ref: '#/components/schemas/OAuth2AuthorizationCodeGrantErrorType' + explode: false + style: form + OAuth2AuthorizationCodeGrantErrorParams.error_description: + name: error_description + in: query + required: false + description: |- + Optional human-readable text providing additional information, + used to assist the client developer in understanding the error that occurred. + schema: + type: string + explode: false + style: form + OAuth2AuthorizationCodeGrantErrorParams.error_uri: + name: error_uri + in: query + required: false + description: |- + Optional uri identifying a human-readable web page with + information about the error, used to provide the client + developer with additional information about the error + schema: + type: string + explode: false + style: form + OAuth2AuthorizationCodeGrantSuccessParams.code: + name: code + in: query + required: false + description: |- + Authorization code which the client will later exchange for an access token. + Required with the success response. + schema: + type: string + explode: false + style: form + OAuth2AuthorizationCodeGrantSuccessParams.state: + name: state + in: query + required: false + description: |- + Required if the "state" parameter was present in the client authorization request. + The exact value received from the client: + + Unique, randomly generated, opaque, and non-guessable string that is sent + when starting an authentication request and validated when processing the response. + schema: + type: string + explode: false + style: form + Pagination.page: + name: page + in: query + required: false + description: |- + Page index. + + Default is 1. + schema: + type: integer + minimum: 1 + default: 1 + explode: false + style: form + Pagination.pageSize: + name: pageSize + in: query + required: false + description: |- + The maximum number of items per page. + + Default is 100. + schema: + type: integer + minimum: 1 + maximum: 1000 + default: 100 + explode: false + style: form + PlanAddonOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + PlanAddonOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/PlanAddonOrderBy' + explode: false + style: form + PlanOrderByOrdering.order: + name: order + in: query + required: false + description: The order direction. + schema: + allOf: + - $ref: '#/components/schemas/SortOrder' + default: ASC + explode: false + style: form + PlanOrderByOrdering.orderBy: + name: orderBy + in: query + required: false + description: The order by field. + schema: + $ref: '#/components/schemas/PlanOrderBy' + explode: false + style: form + listCustomerAppDataParams.type: + name: type + in: query + required: false + description: Filter customer data by app type. + schema: + $ref: '#/components/schemas/AppType' + explode: false + style: form + queryCustomerGet: + name: expand + in: query + required: false + description: What parts of the customer output to expand + schema: + type: array + items: + $ref: '#/components/schemas/CustomerExpand' + style: form + queryCustomerList.expand: + name: expand + in: query + required: false + description: What parts of the list output to expand in listings + schema: + type: array + items: + $ref: '#/components/schemas/CustomerExpand' + style: form + queryCustomerList.includeDeleted: + name: includeDeleted + in: query + required: false + description: Include deleted customers. + schema: + type: boolean + default: false + explode: false + style: form + queryCustomerList.key: + name: key + in: query + required: false + description: |- + Filter customers by key. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryCustomerList.name: + name: name + in: query + required: false + description: |- + Filter customers by name. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryCustomerList.planKey: + name: planKey + in: query + required: false + description: Filter customers by the plan key of their susbcription. + schema: + type: string + explode: false + style: form + queryCustomerList.primaryEmail: + name: primaryEmail + in: query + required: false + description: |- + Filter customers by primary email. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryCustomerList.subject: + name: subject + in: query + required: false + description: |- + Filter customers by usage attribution subject. + Case-insensitive partial match. + schema: + type: string + explode: false + style: form + queryMeterList.includeDeleted: + name: includeDeleted + in: query + required: false + description: Include deleted meters. + schema: + type: boolean + default: false + explode: false + style: form + schemas: + Addon: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - version + - instanceType + - currency + - status + - rateCards + - validationErrors + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + version: + type: integer + minimum: 1 + description: Version of the add-on. Incremented when the add-on is updated. + title: Version + default: 1 + readOnly: true + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instanceType of the add-ons. Can be "single" or "multiple". + title: InstanceType + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the add-on. + title: Currency + default: USD + effectiveFrom: + type: string + format: date-time + description: The date and time when the add-on becomes effective. When not specified, the add-on is a draft. + example: '2023-01-01T01:01:01.001Z' + title: Effective start date + readOnly: true + effectiveTo: + type: string + format: date-time + description: The date and time when the add-on is no longer effective. When not specified, the add-on is effective indefinitely. + example: '2023-01-01T01:01:01.001Z' + title: Effective end date + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AddonStatus' + description: |- + The status of the add-on. + Computed based on the effective start and end dates: + - draft = no effectiveFrom + - active = effectiveFrom <= now < effectiveTo + - archived = effectiveTo <= now + title: Status + readOnly: true + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the add-on. + title: Rate cards + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + nullable: true + description: List of validation errors. + title: Validation errors + readOnly: true + description: Add-on allows extending subscriptions with compatible plans with additional ratecards. + AddonCreate: + type: object + required: + - name + - key + - instanceType + - currency + - rateCards + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instanceType of the add-ons. Can be "single" or "multiple". + title: InstanceType + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the add-on. + title: Currency + default: USD + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the add-on. + title: Rate cards + description: Resource create operation model. + AddonInstanceType: + type: string + enum: + - single + - multiple + description: |- + The instanceType of the add-on. + Single instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once. + AddonOrderBy: + type: string + enum: + - id + - key + - version + - created_at + - updated_at + description: Order by options for add-ons. + AddonPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Addon' + description: The items in the current page. + description: Paginated response + AddonReplaceUpdate: + type: object + required: + - name + - instanceType + - rateCards + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instanceType of the add-ons. Can be "single" or "multiple". + title: InstanceType + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the add-on. + title: Rate cards + description: Resource update operation model. + AddonStatus: + type: string + enum: + - draft + - active + - archived + description: The status of the add-on defined by the effectiveFrom and effectiveTo properties. + Address: + type: object + properties: + country: + allOf: + - $ref: '#/components/schemas/CountryCode' + description: Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 format. + postalCode: + type: string + description: Postal code. + state: + type: string + description: State or province. + city: + type: string + description: City. + line1: + type: string + description: First line of the address. + line2: + type: string + description: Second line of the address. + phoneNumber: + type: string + description: Phone number. + description: Address + Alignment: + type: object + properties: + billablesMustAlign: + type: boolean + description: |- + Whether all Billable items and RateCards must align. + Alignment means the Price's BillingCadence must align for both duration and anchor time. + deprecated: true + description: Alignment configuration for a plan or subscription. + deprecated: true + Annotations: + type: object + additionalProperties: {} + description: Set of key-value pairs managed by the system. Cannot be modified by user. + example: + externalId: 019142cc-a016-796a-8113-1a942fecd26d + App: + type: object + oneOf: + - $ref: '#/components/schemas/StripeApp' + - $ref: '#/components/schemas/SandboxApp' + - $ref: '#/components/schemas/CustomInvoicingApp' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeApp' + sandbox: '#/components/schemas/SandboxApp' + custom_invoicing: '#/components/schemas/CustomInvoicingApp' + description: |- + App. + One of: stripe + AppBase: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + description: |- + Abstract base model for installed apps. + + Represent an app installed to the organization. + This is an actual instance, with its own configuration and credentials. + AppCapability: + type: object + required: + - type + - key + - name + - description + properties: + type: + allOf: + - $ref: '#/components/schemas/AppCapabilityType' + description: The capability type. + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: Key + name: + type: string + description: The capability name. + description: + type: string + description: The capability description. + description: |- + App capability. + + Capabilities only exist in config so they don't extend the Resource model. + example: + type: collectPayments + key: stripe_collect_payment + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + AppCapabilityType: + type: string + enum: + - reportUsage + - reportEvents + - calculateTax + - invoiceCustomers + - collectPayments + description: App capability type. + AppPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/App' + description: The items in the current page. + description: Paginated response + AppReadOrCreateOrUpdateOrDeleteOrQuery: + type: object + oneOf: + - $ref: '#/components/schemas/StripeAppReadOrCreateOrUpdateOrDeleteOrQuery' + - $ref: '#/components/schemas/SandboxApp' + - $ref: '#/components/schemas/CustomInvoicingApp' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeAppReadOrCreateOrUpdateOrDeleteOrQuery' + sandbox: '#/components/schemas/SandboxApp' + custom_invoicing: '#/components/schemas/CustomInvoicingApp' + description: |- + App. + One of: stripe + AppReference: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the app. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: |- + App reference + + Can be used as a short reference to an app if the full app object is not needed. + AppReplaceUpdate: + type: object + oneOf: + - $ref: '#/components/schemas/StripeAppReplaceUpdate' + - $ref: '#/components/schemas/SandboxAppReplaceUpdate' + - $ref: '#/components/schemas/CustomInvoicingAppReplaceUpdate' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeAppReplaceUpdate' + sandbox: '#/components/schemas/SandboxAppReplaceUpdate' + custom_invoicing: '#/components/schemas/CustomInvoicingAppReplaceUpdate' + description: App ReplaceUpdate Model + AppStatus: + type: string + enum: + - ready + - unauthorized + description: App installed status. + AppType: + type: string + enum: + - stripe + - sandbox + - custom_invoicing + description: Type of the app. + BadRequestProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + BalanceHistoryWindow: + type: object + required: + - period + - usage + - balanceAtStart + properties: + period: + $ref: '#/components/schemas/Period' + usage: + type: number + format: double + description: The total usage of the feature in the period. + example: 100 + readOnly: true + balanceAtStart: + type: number + format: double + description: The entitlement balance at the start of the period. + example: 100 + readOnly: true + description: The balance history window. + BillingCollectionAlignment: + type: string + enum: + - subscription + - anchored + description: |- + BillingCollectionAlignment specifies when the pending line items should be collected into + an invoice. + title: Collection alignment + BillingCustomerProfile: + type: object + required: + - supplier + - workflow + - apps + properties: + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + readOnly: true + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The billing workflow settings for this profile + readOnly: true + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsOrReference' + description: |- + The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + readOnly: true + description: |- + Customer specific merged profile. + + This profile is calculated from the customer override and the billing profile it references or the default. + + Thus this does not have any kind of resource fields, only the calculated values. + BillingDiscountMetadata: + type: object + properties: + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Billing specific fields for product catalog discounts. + BillingDiscountPercentage: + type: object + required: + - percentage + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + minimum: 0 + maximum: 100 + description: The percentage of the discount. + title: Percentage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: A percentage discount. + BillingDiscountReason: + type: object + oneOf: + - $ref: '#/components/schemas/DiscountReasonMaximumSpend' + - $ref: '#/components/schemas/DiscountReasonRatecardPercentage' + - $ref: '#/components/schemas/DiscountReasonRatecardUsage' + discriminator: + propertyName: type + mapping: + maximum_spend: '#/components/schemas/DiscountReasonMaximumSpend' + ratecard_percentage: '#/components/schemas/DiscountReasonRatecardPercentage' + ratecard_usage: '#/components/schemas/DiscountReasonRatecardUsage' + description: The reason for the discount. + BillingDiscountUsage: + type: object + required: + - quantity + properties: + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the usage discount. + + Must be positive. + title: Usage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: A usage discount. + BillingDiscounts: + type: object + properties: + percentage: + allOf: + - $ref: '#/components/schemas/BillingDiscountPercentage' + description: The percentage discount. + usage: + allOf: + - $ref: '#/components/schemas/BillingDiscountUsage' + description: The usage discount. + description: A discount by type. + BillingInvoiceCustomerExtendedDetails: + type: object + required: + - usageAttribution + properties: + id: + type: string + description: Unique identifier for the party (if available) + readOnly: true + key: + type: string + minLength: 1 + maxLength: 256 + description: An optional unique key of the party (if available) + title: Key + name: + type: string + description: Legal name or representation of the organization. + taxId: + allOf: + - $ref: '#/components/schemas/BillingPartyTaxIdentity' + description: |- + The entity's legal ID code used for tax purposes. They may have + other numbers, but we're only interested in those valid for tax purposes. + addresses: + type: array + items: + $ref: '#/components/schemas/Address' + maxItems: 1 + description: Regular post addresses for where information should be sent if needed. + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: Mapping to attribute metered usage to the customer + title: Usage Attribution + description: |- + BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the billing party details for invoices. + + These fields contain the OpenMeter specific details for the customer, that are not strictly required for the invoice itself. + BillingParty: + type: object + properties: + id: + type: string + description: Unique identifier for the party (if available) + readOnly: true + key: + type: string + minLength: 1 + maxLength: 256 + description: An optional unique key of the party (if available) + title: Key + name: + type: string + description: Legal name or representation of the organization. + taxId: + allOf: + - $ref: '#/components/schemas/BillingPartyTaxIdentity' + description: |- + The entity's legal ID code used for tax purposes. They may have + other numbers, but we're only interested in those valid for tax purposes. + addresses: + type: array + items: + $ref: '#/components/schemas/Address' + maxItems: 1 + description: Regular post addresses for where information should be sent if needed. + description: Party represents a person or business entity. + BillingPartyReplaceUpdate: + type: object + properties: + key: + type: string + minLength: 1 + maxLength: 256 + description: An optional unique key of the party (if available) + title: Key + name: + type: string + description: Legal name or representation of the organization. + taxId: + allOf: + - $ref: '#/components/schemas/BillingPartyTaxIdentity' + description: |- + The entity's legal ID code used for tax purposes. They may have + other numbers, but we're only interested in those valid for tax purposes. + addresses: + type: array + items: + $ref: '#/components/schemas/Address' + maxItems: 1 + description: Regular post addresses for where information should be sent if needed. + description: Resource update operation model. + BillingPartyTaxIdentity: + type: object + properties: + code: + allOf: + - $ref: '#/components/schemas/BillingTaxIdentificationCode' + description: Normalized tax code shown on the original identity document. + description: Identity stores the details required to identify an entity for tax purposes in a specific country. + BillingProfile: + type: object + required: + - id + - name + - createdAt + - updatedAt + - supplier + - workflow + - apps + - default + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The billing workflow settings for this profile + readOnly: true + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsOrReference' + description: |- + The applications used by this billing profile. + + Expand settings govern if this includes the whole app object or just the ID references. + readOnly: true + default: + type: boolean + description: Is this the default profile? + description: BillingProfile represents a billing profile + BillingProfileAppReferences: + type: object + required: + - tax + - invoicing + - payment + properties: + tax: + allOf: + - $ref: '#/components/schemas/AppReference' + description: The tax app used for this workflow + readOnly: true + invoicing: + allOf: + - $ref: '#/components/schemas/AppReference' + description: The invoicing app used for this workflow + readOnly: true + payment: + allOf: + - $ref: '#/components/schemas/AppReference' + description: The payment app used for this workflow + readOnly: true + description: BillingProfileAppReferences represents the references (id, type) to the apps used by a billing profile + BillingProfileApps: + type: object + required: + - tax + - invoicing + - payment + properties: + tax: + allOf: + - $ref: '#/components/schemas/App' + description: The tax app used for this workflow + readOnly: true + invoicing: + allOf: + - $ref: '#/components/schemas/App' + description: The invoicing app used for this workflow + readOnly: true + payment: + allOf: + - $ref: '#/components/schemas/App' + description: The payment app used for this workflow + readOnly: true + description: BillingProfileApps represents the applications used by a billing profile + BillingProfileAppsCreate: + type: object + required: + - tax + - invoicing + - payment + properties: + tax: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The tax app used for this workflow + example: 01G65Z755AFWAKHE12NY0CQ9FH + x-go-type: string + invoicing: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The invoicing app used for this workflow + example: 01G65Z755AFWAKHE12NY0CQ9FH + x-go-type: string + payment: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The payment app used for this workflow + example: 01G65Z755AFWAKHE12NY0CQ9FH + x-go-type: string + description: BillingProfileAppsCreate represents the input for creating a billing profile's apps + BillingProfileAppsOrReference: + anyOf: + - $ref: '#/components/schemas/BillingProfileApps' + - $ref: '#/components/schemas/BillingProfileAppReferences' + description: |- + ProfileAppsOrReference represents the union of ProfileApps and ProfileAppReferences + for a billing profile. + BillingProfileCreate: + type: object + required: + - name + - supplier + - default + - workflow + - apps + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + default: + type: boolean + description: Is this the default profile? + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCreate' + description: The billing workflow settings for this profile. + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsCreate' + description: The apps used by this billing profile. + description: BillingProfileCreate represents the input for creating a billing profile + BillingProfileCustomerOverride: + type: object + required: + - createdAt + - updatedAt + - customerId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + billingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The billing profile this override is associated with. + + If empty the default profile is looked up dynamically. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer id this override is associated with. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Customer override values. + BillingProfileCustomerOverrideCreate: + type: object + properties: + billingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The billing profile this override is associated with. + + If not provided, the default billing profile is chosen if available. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Payload for creating a new or updating an existing customer override. + BillingProfileCustomerOverrideExpand: + type: string + enum: + - apps + - customer + description: CustomerOverrideExpand specifies the parts of the profile to expand. + BillingProfileCustomerOverrideOrderBy: + type: string + enum: + - customerId + - customerName + - customerKey + - customerPrimaryEmail + - customerCreatedAt + description: Order by options for customers. + BillingProfileCustomerOverrideWithDetails: + type: object + required: + - baseBillingProfileId + properties: + customerOverride: + allOf: + - $ref: '#/components/schemas/BillingProfileCustomerOverride' + description: |- + The customer override values. + + If empty the merged values are calculated based on the default profile. + baseBillingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The billing profile the customerProfile is associated with at the time of query. + + customerOverride contains the explicit mapping set in the customer override object. If that is + empty, then the baseBillingProfileId is the default profile. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerProfile: + allOf: + - $ref: '#/components/schemas/BillingCustomerProfile' + description: Merged billing profile with the customer specific overrides. + customer: + allOf: + - $ref: '#/components/schemas/Customer' + description: The customer this override belongs to. + description: Customer specific workflow overrides. + BillingProfileCustomerOverrideWithDetailsPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/BillingProfileCustomerOverrideWithDetails' + description: The items in the current page. + description: Paginated response + BillingProfileCustomerWorkflowOverride: + type: object + required: + - taxApp + - invoicingApp + - paymentApp + properties: + collection: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionSettings' + description: The collection settings for this workflow + invoicing: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSettings' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + tax: + allOf: + - $ref: '#/components/schemas/BillingWorkflowTaxSettings' + description: The tax settings for this workflow + taxApp: + allOf: + - $ref: '#/components/schemas/AppReadOrCreateOrUpdateOrDeleteOrQuery' + description: The tax app used for this workflow + readOnly: true + invoicingApp: + allOf: + - $ref: '#/components/schemas/AppReadOrCreateOrUpdateOrDeleteOrQuery' + description: The invoicing app used for this workflow + readOnly: true + paymentApp: + allOf: + - $ref: '#/components/schemas/AppReadOrCreateOrUpdateOrDeleteOrQuery' + description: The payment app used for this workflow + readOnly: true + description: Customer specific workflow overrides. + BillingProfileExpand: + type: string + enum: + - apps + description: BillingProfileExpand details what profile fields to expand + BillingProfileOrderBy: + type: string + enum: + - createdAt + - updatedAt + - default + - name + description: BillingProfileOrderBy specifies the ordering options for profiles + BillingProfilePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/BillingProfile' + description: The items in the current page. + description: Paginated response + BillingProfileReplaceUpdateWithWorkflow: + type: object + required: + - name + - supplier + - default + - workflow + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The name and contact information for the supplier this billing profile represents + default: + type: boolean + description: Is this the default profile? + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The billing workflow settings for this profile. + description: |- + BillingProfileReplaceUpdate represents the input for updating a billing profile + + The apps field cannot be updated directly, if an app change is desired a new + profile should be created. + BillingSettlementMode: + type: string + enum: + - credit_then_invoice + - credit_only + description: |- + The settlement mode of a plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + BillingTaxIdentificationCode: + type: string + minLength: 1 + maxLength: 32 + description: TaxIdentificationCode is a normalized tax code shown on the original identity document. + BillingWorkflow: + type: object + properties: + collection: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionSettings' + description: The collection settings for this workflow + invoicing: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSettings' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + tax: + allOf: + - $ref: '#/components/schemas/BillingWorkflowTaxSettings' + description: The tax settings for this workflow + description: BillingWorkflow represents the settings for a billing workflow. + BillingWorkflowAppReferenceType: + type: string + enum: + - app_id + - app_type + description: App reference type specifies the type of reference inside an app reference + BillingWorkflowCollectionAlignment: + type: object + oneOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionAlignmentSubscription' + - $ref: '#/components/schemas/BillingWorkflowCollectionAlignmentAnchored' + discriminator: + propertyName: type + mapping: + subscription: '#/components/schemas/BillingWorkflowCollectionAlignmentSubscription' + anchored: '#/components/schemas/BillingWorkflowCollectionAlignmentAnchored' + description: |- + The alignment for collecting the pending line items into an invoice. + + Defaults to subscription, which means that we are to create a new invoice every time the + a subscription period starts (for in advance items) or ends (for in arrears items). + BillingWorkflowCollectionAlignmentAnchored: + type: object + required: + - type + - recurringPeriod + properties: + type: + type: string + enum: + - anchored + description: The type of alignment. + recurringPeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodV2' + description: The recurring period for the alignment. + description: |- + BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items + into an invoice. + BillingWorkflowCollectionAlignmentSubscription: + type: object + required: + - type + properties: + type: + type: string + enum: + - subscription + description: The type of alignment. + description: |- + BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items + into an invoice. + BillingWorkflowCollectionSettings: + type: object + properties: + alignment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionAlignment' + description: The alignment for collecting the pending line items into an invoice. + default: + type: subscription + interval: + type: string + format: ISO8601 + description: |- + This grace period can be used to delay the collection of the pending line items specified in + alignment. + + This is useful, in case of multiple subscriptions having slightly different billing periods. + example: P1D + default: PT1H + description: Workflow collection specifies how to collect the pending line items for an invoice + BillingWorkflowCreate: + type: object + properties: + collection: + allOf: + - $ref: '#/components/schemas/BillingWorkflowCollectionSettings' + description: The collection settings for this workflow + invoicing: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSettings' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + tax: + allOf: + - $ref: '#/components/schemas/BillingWorkflowTaxSettings' + description: The tax settings for this workflow + description: Resource create operation model. + BillingWorkflowInvoicingSettings: + type: object + properties: + autoAdvance: + type: boolean + description: Whether to automatically issue the invoice after the draftPeriod has passed. + default: true + draftPeriod: + type: string + format: ISO8601 + description: The period for the invoice to be kept in draft status for manual reviews. + example: P1D + default: P0D + dueAfter: + type: string + format: ISO8601 + description: |- + The period after which the invoice is due. + With some payment solutions it's only applicable for manual collection method. + example: P30D + default: P30D + progressiveBilling: + type: boolean + description: Should progressive billing be allowed for this workflow? + default: true + subscriptionEndProrationMode: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSubscriptionEndProrationMode' + description: Controls how subscription-ending shortened service periods are billed. + default: bill_actual_period + defaultTaxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + Default tax configuration to apply to the invoices. + + Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and `behavior` remains + fully supported. + description: BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow + title: Workflow invoice settings + BillingWorkflowInvoicingSubscriptionEndProrationMode: + type: string + enum: + - bill_full_period + - bill_actual_period + description: Billing workflow subscription end proration mode. + BillingWorkflowLineResolution: + type: string + enum: + - day + - period + description: BillingWorkflowLineResolution specifies how the line items should be resolved in the invoice + title: Item resolution + BillingWorkflowPaymentSettings: + type: object + properties: + collectionMethod: + allOf: + - $ref: '#/components/schemas/CollectionMethod' + description: The payment method for the invoice. + default: charge_automatically + description: BillingWorkflowPaymentSettings represents the payment settings for a billing workflow + title: Workflow payment settings + BillingWorkflowTaxSettings: + type: object + properties: + enabled: + type: boolean + description: |- + Enable automatic tax calculation when tax is supported by the app. + For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + default: true + enforced: + type: boolean + description: |- + Enforce tax calculation when tax is supported by the app. + When enabled, OpenMeter will not allow to create an invoice without tax calculation. + Enforcement is different per apps, for example, Stripe app requires customer + to have a tax location when starting a paid subscription. + default: false + description: BillingWorkflowTaxSettings represents the tax settings for a billing workflow + title: Workflow tax settings + CheckoutSessionCustomTextAfterSubmitParams: + type: object + properties: + afterSubmit: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed after the payment confirmation button. + shippingAddress: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed alongside shipping address collection. + submit: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed alongside the payment confirmation button. + termsOfServiceAcceptance: + type: object + properties: + message: + type: string + maxLength: 1200 + description: Custom text that should be displayed in place of the default terms of service agreement text. + description: Stripe CheckoutSession.custom_text + CheckoutSessionUIMode: + type: string + enum: + - embedded + - hosted + description: Stripe CheckoutSession.ui_mode + ClientAppStartResponse: + type: object + required: + - url + properties: + url: + type: string + description: The URL to start the OAuth2 authorization code grant flow. + description: Response from the client app (OpenMeter backend) to start the OAuth2 flow. + CollectionMethod: + type: string + enum: + - charge_automatically + - send_invoice + description: CollectionMethod specifies how the invoice should be collected (automatic vs manual) + title: Collection method + ConflictProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The request could not be completed due to a conflict with the current state of the target resource. + CountryCode: + type: string + minLength: 2 + maxLength: 2 + pattern: ^[A-Z]{2}$ + description: |- + [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. + Custom two-letter country codes are also supported for convenience. + example: US + CreateCheckoutSessionTaxIdCollection: + type: object + required: + - enabled + properties: + enabled: + type: boolean + description: Enable tax ID collection during checkout. Defaults to false. + required: + allOf: + - $ref: '#/components/schemas/CreateCheckoutSessionTaxIdCollectionRequired' + description: Describes whether a tax ID is required during checkout. Defaults to never. + description: Create Stripe checkout session tax ID collection. + CreateCheckoutSessionTaxIdCollectionRequired: + type: string + enum: + - if_supported + - never + description: Create Stripe checkout session tax ID collection required. + CreateStripeCheckoutSessionBillingAddressCollection: + type: string + enum: + - auto + - required + description: Specify whether Checkout should collect the customer’s billing address. + CreateStripeCheckoutSessionConsentCollection: + type: object + properties: + paymentMethodReuseAgreement: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement' + description: |- + Determines the position and visibility of the payment method reuse agreement in the UI. + When set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI. + promotions: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionPromotions' + description: |- + If set to auto, enables the collection of customer consent for promotional communications. + The Checkout Session will determine whether to display an option to opt into promotional + communication from the merchant depending on the customer’s locale. Only available to US merchants. + termsOfService: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionTermsOfService' + description: |- + If set to required, it requires customers to check a terms of service checkbox before being able to pay. + There must be a valid terms of service URL set in your Stripe Dashboard settings. + https://dashboard.stripe.com/settings/public + description: Configure fields for the Checkout Session to gather active consent from customers. + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement: + type: object + properties: + position: + $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition' + description: Create Stripe checkout session payment method reuse agreement. + CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition: + type: string + enum: + - auto + - hidden + description: Create Stripe checkout session consent collection agreement position. + CreateStripeCheckoutSessionConsentCollectionPromotions: + type: string + enum: + - auto + - none + description: Create Stripe checkout session consent collection promotions. + CreateStripeCheckoutSessionConsentCollectionTermsOfService: + type: string + enum: + - none + - required + description: Create Stripe checkout session consent collection terms of service. + CreateStripeCheckoutSessionCustomerUpdate: + type: object + properties: + address: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdateBehavior' + description: |- + Describes whether Checkout saves the billing address onto customer.address. + To always collect a full billing address, use billing_address_collection. + Defaults to never. + name: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdateBehavior' + description: |- + Describes whether Checkout saves the name onto customer.name. + Defaults to never. + shipping: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdateBehavior' + description: |- + Describes whether Checkout saves shipping information onto customer.shipping. + To collect shipping information, use shipping_address_collection. + Defaults to never. + description: Controls what fields on Customer can be updated by the Checkout Session. + CreateStripeCheckoutSessionCustomerUpdateBehavior: + type: string + enum: + - auto + - never + description: Create Stripe checkout session customer update behavior. + CreateStripeCheckoutSessionRedirectOnCompletion: + type: string + enum: + - always + - if_required + - never + description: Create Stripe checkout session redirect on completion. + CreateStripeCheckoutSessionRequest: + type: object + required: + - customer + - options + properties: + appId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: If not provided, the default Stripe app is used if any. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customer: + anyOf: + - $ref: '#/components/schemas/CustomerId' + - $ref: '#/components/schemas/CustomerKey' + - $ref: '#/components/schemas/CustomerCreate' + description: |- + Provide a customer ID or key to use an existing OpenMeter customer. + or provide a customer object to create a new customer. + stripeCustomerId: + type: string + description: |- + Stripe customer ID. + If not provided OpenMeter creates a new Stripe customer or + uses the OpenMeter customer's default Stripe customer ID. + options: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionRequestOptions' + description: Options passed to Stripe when creating the checkout session. + description: Create Stripe checkout session request. + example: + customer: + name: ACME, Inc. + currency: USD + usageAttribution: + subjectKeys: + - my-identifier + options: + currency: USD + successURL: http://example.com + billingAddressCollection: required + taxIdCollection: + enabled: true + required: if_supported + customerUpdate: + name: auto + address: auto + CreateStripeCheckoutSessionRequestOptions: + type: object + properties: + billingAddressCollection: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionBillingAddressCollection' + description: Specify whether Checkout should collect the customer’s billing address. Defaults to auto. + cancelURL: + type: string + description: |- + If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + This parameter is not allowed if ui_mode is embedded. + clientReferenceID: + type: string + description: A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + customerUpdate: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionCustomerUpdate' + description: Controls what fields on Customer can be updated by the Checkout Session. + consentCollection: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionConsentCollection' + description: Configure fields for the Checkout Session to gather active consent from customers. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: Three-letter ISO currency code, in lowercase. + customText: + allOf: + - $ref: '#/components/schemas/CheckoutSessionCustomTextAfterSubmitParams' + description: Display additional text for your customers using custom text. + expiresAt: + type: integer + format: int64 + description: |- + The Epoch time in seconds at which the Checkout Session will expire. + It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + locale: + type: string + metadata: + type: object + additionalProperties: + type: string + description: |- + Set of key-value pairs that you can attach to an object. + This can be useful for storing additional information about the object in a structured format. + Individual keys can be unset by posting an empty value to them. + All keys can be unset by posting an empty value to metadata. + returnURL: + type: string + description: |- + The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site. + This parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session. + successURL: + type: string + description: |- + The URL to which Stripe should send customers when payment or setup is complete. + This parameter is not allowed if ui_mode is embedded. + If you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page: + https://docs.stripe.com/payments/checkout/custom-success-page + uiMode: + allOf: + - $ref: '#/components/schemas/CheckoutSessionUIMode' + description: The UI mode of the Session. Defaults to hosted. + paymentMethodTypes: + type: array + items: + type: string + description: A list of the types of payment methods (e.g., card) this Checkout Session can accept. + redirectOnCompletion: + allOf: + - $ref: '#/components/schemas/CreateStripeCheckoutSessionRedirectOnCompletion' + description: |- + This parameter applies to ui_mode: embedded. Defaults to always. + Learn more about the redirect behavior of embedded sessions at + https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + taxIdCollection: + allOf: + - $ref: '#/components/schemas/CreateCheckoutSessionTaxIdCollection' + description: Controls tax ID collection during checkout. + description: |- + Create Stripe checkout session options + See https://docs.stripe.com/api/checkout/sessions/create + CreateStripeCheckoutSessionResult: + type: object + required: + - customerId + - stripeCustomerId + - sessionId + - setupIntentId + - createdAt + - mode + properties: + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The OpenMeter customer ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + stripeCustomerId: + type: string + description: The Stripe customer ID. + sessionId: + type: string + description: The checkout session ID. + setupIntentId: + type: string + description: The checkout session setup intent ID. + clientSecret: + type: string + description: |- + The client secret of the checkout session. + This can be used to initialize Stripe.js for your client-side implementation. + clientReferenceId: + type: string + description: |- + A unique string to reference the Checkout Session. + This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + customerEmail: + type: string + description: Customer's email address provided to Stripe. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: Three-letter ISO currency code, in lowercase. + createdAt: + type: string + format: date-time + description: Timestamp at which the checkout session was created. + example: '2023-01-01T01:01:01.001Z' + expiresAt: + type: string + format: date-time + description: Timestamp at which the checkout session will expire. + example: '2023-01-01T01:01:01.001Z' + metadata: + type: object + additionalProperties: + type: string + description: Set of key-value pairs attached to the checkout session. + status: + type: string + description: The status of the checkout session. + url: + type: string + description: URL to show the checkout session. + mode: + allOf: + - $ref: '#/components/schemas/StripeCheckoutSessionMode' + description: |- + Mode + Always `setup` for now. + cancelURL: + type: string + description: Cancel URL. + successURL: + type: string + description: Success URL. + returnURL: + type: string + description: Return URL. + description: Create Stripe Checkout Session response. + CreateStripeCustomerPortalSessionParams: + type: object + properties: + configurationId: + type: string + description: |- + The ID of an existing configuration to use for this session, + describing its functionality and features. + If not specified, the session uses the default configuration. + + See https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration + title: Configuration + locale: + type: string + description: |- + The IETF language tag of the locale customer portal is displayed in. + If blank or auto, the customer’s preferred_locales or browser’s locale is used. + + See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale + title: Locale + returnUrl: + type: string + description: |- + The URL to redirect the customer to after they have completed + their requested actions. + + See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url + title: ReturnUrl + description: Stripe customer portal request params. + CreditNoteOriginalInvoiceRef: + type: object + required: + - type + - url + properties: + type: + type: string + enum: + - credit_note_original_invoice + description: Type of the invoice. + issuedAt: + type: string + format: date-time + description: IssueAt reflects the time the document was issued. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: (Serial) Number of the referenced document. + readOnly: true + url: + type: string + format: uri + description: Link to the source document. + readOnly: true + allOf: + - $ref: '#/components/schemas/InvoiceGenericDocumentRef' + description: CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is based on. + Currency: + type: object + required: + - code + - name + - symbol + - subunits + properties: + code: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency ISO code. + name: + type: string + description: The currency name. + symbol: + type: string + description: The currency symbol. + subunits: + type: integer + format: uint32 + description: Subunit of the currency. + description: Currency describes a currency supported by OpenMeter. + CurrencyCode: + type: string + minLength: 3 + maxLength: 3 + pattern: ^[A-Z]{3}$ + description: |- + Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. + Custom three-letter currency codes are also supported for convenience. + example: USD + CustomInvoicingApp: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + - enableDraftSyncHook + - enableIssuingSyncHook + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - custom_invoicing + description: The app's type is CustomInvoicing. + enableDraftSyncHook: + type: boolean + description: |- + Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + enableIssuingSyncHook: + type: boolean + description: |- + Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + description: |- + Custom Invoicing app can be used for interface with any invoicing or payment system. + + This app provides ways to manipulate invoices and payments, however the integration + must rely on Notifications API to get notified about invoice changes. + CustomInvoicingAppReplaceUpdate: + type: object + required: + - name + - type + - enableDraftSyncHook + - enableIssuingSyncHook + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + type: + type: string + enum: + - custom_invoicing + description: The app's type is CustomInvoicing. + enableDraftSyncHook: + type: boolean + description: |- + Enable draft.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + enableIssuingSyncHook: + type: boolean + description: |- + Enable issuing.sync hook. + + If the hook is not enabled, the invoice will be progressed to the next state automatically. + description: Resource update operation model. + CustomInvoicingCustomerAppData: + type: object + required: + - type + properties: + app: + allOf: + - $ref: '#/components/schemas/CustomInvoicingApp' + description: The installed custom invoicing app this data belongs to. + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - custom_invoicing + description: The app name. + title: App Type + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Metadata to be used by the custom invoicing provider. + description: Custom Invoicing Customer App Data. + CustomInvoicingDraftSynchronizedRequest: + type: object + properties: + invoicing: + allOf: + - $ref: '#/components/schemas/CustomInvoicingSyncResult' + description: The result of the synchronization. + description: Information to finalize the draft details of an invoice. + CustomInvoicingFinalizedInvoicingRequest: + type: object + properties: + invoiceNumber: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: If set the invoice's number will be set to this value. + sentToCustomerAt: + type: string + format: date-time + description: If set the invoice's sent to customer at will be set to this value. + example: '2023-01-01T01:01:01.001Z' + description: Information to finalize the invoicing details of an invoice. + CustomInvoicingFinalizedPaymentRequest: + type: object + properties: + externalId: + type: string + description: If set the invoice's payment external ID will be set to this value. + description: Information to finalize the payment details of an invoice. + CustomInvoicingFinalizedRequest: + type: object + properties: + invoicing: + allOf: + - $ref: '#/components/schemas/CustomInvoicingFinalizedInvoicingRequest' + description: The result of the synchronization. + payment: + allOf: + - $ref: '#/components/schemas/CustomInvoicingFinalizedPaymentRequest' + description: The result of the payment synchronization. + description: |- + Information to finalize the invoice. + + If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix). + CustomInvoicingLineDiscountExternalIdMapping: + type: object + required: + - lineDiscountId + - externalId + properties: + lineDiscountId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The line discount ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + externalId: + type: string + description: The external ID (e.g. custom invoicing system's ID). + description: Mapping between line discounts and external IDs. + CustomInvoicingLineExternalIdMapping: + type: object + required: + - lineId + - externalId + properties: + lineId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The line ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + externalId: + type: string + description: The external ID (e.g. custom invoicing system's ID). + description: Mapping between lines and external IDs. + CustomInvoicingPaymentTrigger: + type: string + enum: + - paid + - payment_failed + - payment_uncollectible + - payment_overdue + - action_required + - void + description: Payment trigger to execute on a finalized invoice. + CustomInvoicingSyncResult: + type: object + properties: + invoiceNumber: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: If set the invoice's number will be set to this value. + externalId: + type: string + description: If set the invoice's invoicing external ID will be set to this value. + lineExternalIds: + type: array + items: + $ref: '#/components/schemas/CustomInvoicingLineExternalIdMapping' + description: |- + If set the invoice's line external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice. + lineDiscountExternalIds: + type: array + items: + $ref: '#/components/schemas/CustomInvoicingLineDiscountExternalIdMapping' + description: |- + If set the invoice's line discount external IDs will be set to this value. + + This can be used to reference the external system's entities in the + invoice. + description: |- + Information to synchronize the invoice. + + Can be used to store external app's IDs on the invoice or lines. + CustomInvoicingTaxConfig: + type: object + required: + - code + properties: + code: + type: string + description: |- + Tax code. + + The tax code should be interpreted by the custom invoicing provider. + title: Tax code + description: Custom invoicing tax config. + CustomInvoicingUpdatePaymentStatusRequest: + type: object + required: + - trigger + properties: + trigger: + allOf: + - $ref: '#/components/schemas/CustomInvoicingPaymentTrigger' + description: The trigger to be executed on the invoice. + description: |- + Update payment status request. + + Can be used to manipulate invoice's payment status (when custominvoicing app is being used). + CustomPlanInput: + type: object + allOf: + - type: object + required: + - name + - currency + - billingCadence + - phases + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the plan. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + description: The template for omitting properties. + description: Plan input for custom subscription creation (without key and version). + CustomSubscriptionChange: + type: object + required: + - timing + - customPlan + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + For changing a subscription, the accepted values depend on the subscription configuration. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + example: '2023-01-01T01:01:01.001Z' + customPlan: + allOf: + - $ref: '#/components/schemas/CustomPlanInput' + description: The custom plan description which defines the Subscription. + description: Change a custom subscription. + CustomSubscriptionCreate: + type: object + required: + - customPlan + properties: + customPlan: + allOf: + - $ref: '#/components/schemas/CustomPlanInput' + description: The custom plan description which defines the Subscription. + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + The default is immediate. + default: immediate + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the customer. Provide either the key or ID. Has presedence over the key. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerKey: + type: string + minLength: 1 + maxLength: 256 + description: The key of the customer. Provide either the key or ID. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + example: '2023-01-01T01:01:01.001Z' + description: Create a custom subscription. + title: Create custom + Customer: + type: object + required: + - id + - name + - createdAt + - updatedAt + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 256 + description: |- + An optional unique key of the customer. + Either key or usageAttribution.subjectKeys must be provided. + Useful to reference the customer in external systems. + For example, your database ID. + title: Key + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: |- + Mapping to attribute metered usage to the customer + Either key or usageAttribution.subjectKeys must be provided. + title: Usage Attribution + primaryEmail: + type: string + description: The primary email address of the customer. + title: Primary Email + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency of the customer. + Used for billing, tax and invoicing. + title: Currency + billingAddress: + allOf: + - $ref: '#/components/schemas/Address' + description: |- + The billing address of the customer. + Used for tax and invoicing. + title: Billing Address + currentSubscriptionId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the Subscription if the customer has one. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: Current Subscription ID + readOnly: true + subscriptions: + type: array + items: + $ref: '#/components/schemas/Subscription' + description: |- + The subscriptions of the customer. + Only with the `subscriptions` expand option. + title: Subscriptions + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + description: A customer object. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + name: ACME Inc. + usageAttribution: + subjectKeys: + - my_subject_key + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + CustomerAccess: + type: object + required: + - entitlements + properties: + entitlements: + type: object + additionalProperties: + $ref: '#/components/schemas/EntitlementValue' + description: |- + Map of entitlements the customer has access to. + The key is the feature key, the value is the entitlement value + the entitlement ID. + readOnly: true + description: CustomerAccess describes what features the customer has access to. + CustomerAppData: + type: object + oneOf: + - $ref: '#/components/schemas/StripeCustomerAppData' + - $ref: '#/components/schemas/SandboxCustomerAppData' + - $ref: '#/components/schemas/CustomInvoicingCustomerAppData' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeCustomerAppData' + sandbox: '#/components/schemas/SandboxCustomerAppData' + custom_invoicing: '#/components/schemas/CustomInvoicingCustomerAppData' + description: |- + CustomerAppData + Stores the app specific data for the customer. + One of: stripe, sandbox, custom_invoicing + CustomerAppDataCreateOrUpdateItem: + type: object + oneOf: + - $ref: '#/components/schemas/StripeCustomerAppDataCreateOrUpdateItem' + - $ref: '#/components/schemas/SandboxCustomerAppData' + - $ref: '#/components/schemas/CustomInvoicingCustomerAppData' + discriminator: + propertyName: type + mapping: + stripe: '#/components/schemas/StripeCustomerAppDataCreateOrUpdateItem' + sandbox: '#/components/schemas/SandboxCustomerAppData' + custom_invoicing: '#/components/schemas/CustomInvoicingCustomerAppData' + description: |- + CustomerAppData + Stores the app specific data for the customer. + One of: stripe, sandbox, custom_invoicing + CustomerAppDataPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/CustomerAppData' + description: The items in the current page. + description: Paginated response + CustomerCreate: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 256 + description: |- + An optional unique key of the customer. + Either key or usageAttribution.subjectKeys must be provided. + Useful to reference the customer in external systems. + For example, your database ID. + title: Key + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: |- + Mapping to attribute metered usage to the customer + Either key or usageAttribution.subjectKeys must be provided. + title: Usage Attribution + primaryEmail: + type: string + description: The primary email address of the customer. + title: Primary Email + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency of the customer. + Used for billing, tax and invoicing. + title: Currency + billingAddress: + allOf: + - $ref: '#/components/schemas/Address' + description: |- + The billing address of the customer. + Used for tax and invoicing. + title: Billing Address + description: Resource create operation model. + CustomerExpand: + type: string + enum: + - subscriptions + description: CustomerExpand specifies the parts of the customer to expand in the list output. + CustomerId: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Create Stripe checkout session with customer ID. + CustomerKey: + type: object + required: + - key + properties: + key: + type: string + description: Create Stripe checkout session with customer key. + CustomerOrderBy: + type: string + enum: + - id + - name + - createdAt + description: Order by options for customers. + CustomerPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Customer' + description: The items in the current page. + description: Paginated response + CustomerReplaceUpdate: + type: object + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 256 + description: |- + An optional unique key of the customer. + Either key or usageAttribution.subjectKeys must be provided. + Useful to reference the customer in external systems. + For example, your database ID. + title: Key + usageAttribution: + allOf: + - $ref: '#/components/schemas/CustomerUsageAttribution' + description: |- + Mapping to attribute metered usage to the customer + Either key or usageAttribution.subjectKeys must be provided. + title: Usage Attribution + primaryEmail: + type: string + description: The primary email address of the customer. + title: Primary Email + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency of the customer. + Used for billing, tax and invoicing. + title: Currency + billingAddress: + allOf: + - $ref: '#/components/schemas/Address' + description: |- + The billing address of the customer. + Used for tax and invoicing. + title: Billing Address + description: Resource update operation model. + CustomerSubscriptionOrderBy: + type: string + enum: + - activeFrom + - activeTo + description: Order by options for customer subscriptions. + CustomerUsageAttribution: + type: object + required: + - subjectKeys + properties: + subjectKeys: + type: array + items: + type: string + minLength: 1 + description: SubjectKey is a key that is used to identify a subject. + minItems: 0 + description: |- + The subjects that are attributed to the customer. + Can be empty when no subjects are associated with the customer. + title: SubjectKeys + description: |- + Mapping to attribute metered usage to the customer. + One customer can have zero or more subjects, + but one subject can only belong to one customer. + DiscountPercentage: + type: object + required: + - percentage + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + minimum: 0 + maximum: 100 + description: The percentage of the discount. + title: Percentage + description: Percentage discount. + DiscountReasonMaximumSpend: + type: object + required: + - type + properties: + type: + type: string + enum: + - maximum_spend + description: The reason for the discount is a maximum spend. + DiscountReasonRatecardPercentage: + type: object + required: + - type + - percentage + properties: + type: + type: string + enum: + - ratecard_percentage + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + minimum: 0 + maximum: 100 + description: The percentage of the discount. + title: Percentage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: The reason for the discount is a ratecard percentage. + DiscountReasonRatecardUsage: + type: object + required: + - type + - quantity + properties: + type: + type: string + enum: + - ratecard_usage + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the usage discount. + + Must be positive. + title: Usage + correlationId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Correlation ID for the discount. + + This is used to link discounts across different invoices (progressive billing use case). + + If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + please make sure to keep the same correlation ID of the discount or in progressive billing + setups the discount amounts might be incorrect. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: The reason for the discount is a ratecard usage. + DiscountReasonType: + type: string + enum: + - maximum_spend + - ratecard_percentage + - ratecard_usage + description: The type of the discount reason. + DiscountUsage: + type: object + required: + - quantity + properties: + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the usage discount. + + Must be positive. + title: Usage + description: |- + Usage discount. + + Usage discount means that the first N items are free. From billing perspective + this means that any usage on a specific feature is considered 0 until this discount + is exhausted. + Discounts: + type: object + properties: + percentage: + allOf: + - $ref: '#/components/schemas/DiscountPercentage' + description: The percentage discount. + usage: + allOf: + - $ref: '#/components/schemas/DiscountUsage' + description: The usage discount. + description: Discount by type on a price + DynamicPrice: + type: object + required: + - type + properties: + type: + type: string + enum: + - dynamic + description: The type of the price. + multiplier: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The multiplier to apply to the base price to get the dynamic price. + + Examples: + - 0.0: the price is zero + - 0.5: the price is 50% of the base price + - 1.0: the price is the same as the base price + - 1.5: the price is 150% of the base price + title: The multiplier to apply to the base price to get the dynamic price + default: '1' + description: |- + Dynamic price. + + The underlying meter's value is considered the base price in the + customer's currency. + + The rate specifies the markup over the price. + DynamicPriceWithCommitments: + type: object + required: + - type + properties: + type: + type: string + enum: + - dynamic + description: The type of the price. + multiplier: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The multiplier to apply to the base price to get the dynamic price. + + Examples: + - 0.0: the price is zero + - 0.5: the price is 50% of the base price + - 1.0: the price is the same as the base price + - 1.5: the price is 150% of the base price + title: The multiplier to apply to the base price to get the dynamic price + default: '1' + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Dynamic price with spend commitments. + EditOp: + type: string + enum: + - add_item + - remove_item + - unschedule_edit + - add_phase + - remove_phase + - stretch_phase + description: Enum listing the different operation types. + EditSubscriptionAddItem: + type: object + required: + - op + - phaseKey + - rateCard + properties: + op: + type: string + enum: + - add_item + phaseKey: + type: string + rateCard: + $ref: '#/components/schemas/RateCard' + description: Add a new item to a phase. + EditSubscriptionAddPhase: + type: object + required: + - op + - phase + properties: + op: + type: string + enum: + - add_phase + phase: + $ref: '#/components/schemas/SubscriptionPhaseCreate' + description: Add a new phase + EditSubscriptionRemoveItem: + type: object + required: + - op + - phaseKey + - itemKey + properties: + op: + type: string + enum: + - remove_item + phaseKey: + type: string + itemKey: + type: string + description: Remove an item from a phase. + EditSubscriptionRemovePhase: + type: object + required: + - op + - phaseKey + - shift + properties: + op: + type: string + enum: + - remove_phase + phaseKey: + type: string + shift: + $ref: '#/components/schemas/RemovePhaseShifting' + description: Remove a phase + EditSubscriptionStretchPhase: + type: object + required: + - op + - phaseKey + - extendBy + properties: + op: + type: string + enum: + - stretch_phase + phaseKey: + type: string + extendBy: + type: string + format: duration + description: Stretch a phase + EditSubscriptionUnscheduleEdit: + type: object + required: + - op + properties: + op: + type: string + enum: + - unschedule_edit + description: Unschedules any edits from the current phase. + Entitlement: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMetered' + - $ref: '#/components/schemas/EntitlementStatic' + - $ref: '#/components/schemas/EntitlementBoolean' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMetered' + static: '#/components/schemas/EntitlementStatic' + boolean: '#/components/schemas/EntitlementBoolean' + description: |- + Entitlement templates are used to define the entitlements of a plan. + Features are omitted from the entitlement template, as they are defined in the rate card. + deprecated: true + EntitlementBaseTemplate: + type: object + required: + - createdAt + - updatedAt + - activeFrom + - id + - type + - subjectKey + - featureKey + - featureId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/EntitlementType' + description: The type of the entitlement. + title: Type + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + description: Shared fields of the entitlement templates. + EntitlementBoolean: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - subjectKey + - featureKey + - featureId + properties: + type: + type: string + enum: + - boolean + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + description: Entitlement template of a boolean entitlement. + deprecated: true + EntitlementBooleanCreateInputs: + type: object + required: + - type + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + type: + type: string + enum: + - boolean + description: Create inputs for boolean entitlement + deprecated: true + EntitlementBooleanV2: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - featureKey + - featureId + - customerId + properties: + type: + type: string + enum: + - boolean + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: Entitlement template of a boolean entitlement. + EntitlementCreateInputs: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMeteredCreateInputs' + - $ref: '#/components/schemas/EntitlementStaticCreateInputs' + - $ref: '#/components/schemas/EntitlementBooleanCreateInputs' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMeteredCreateInputs' + static: '#/components/schemas/EntitlementStaticCreateInputs' + boolean: '#/components/schemas/EntitlementBooleanCreateInputs' + description: Create inputs for entitlement + EntitlementCreateSharedFields: + type: object + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + description: Shared fields for entitlement creation + EntitlementCustomerFields: + type: object + required: + - customerId + properties: + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: Customer fields for entitlements + EntitlementGrant: + type: object + required: + - createdAt + - updatedAt + - amount + - effectiveAt + - expiration + - id + - entitlementId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + entitlementId: + type: string + description: The unique entitlement ULID that the grant is associated with. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + nextRecurrence: + type: string + format: date-time + description: The next time the grant will recurr. + example: '2023-01-01T01:01:01.001Z' + expiresAt: + type: string + format: date-time + description: The time the grant expires. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + voidedAt: + type: string + format: date-time + description: The time the grant was voided. + example: '2023-01-01T01:01:01.001Z' + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The recurrence period of the grant. + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Grant annotations + example: + issueAfterReset: true + description: The grant. + deprecated: true + EntitlementGrantCreateInput: + type: object + required: + - amount + - effectiveAt + - expiration + properties: + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The subject of the grant. + description: The grant creation input. + deprecated: true + EntitlementGrantCreateInputV2: + type: object + required: + - amount + - effectiveAt + properties: + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The subject of the grant. + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Grant annotations + example: + internal_reference: internal_reference + description: The grant creation input. + EntitlementGrantV2: + type: object + required: + - createdAt + - updatedAt + - amount + - effectiveAt + - id + - entitlementId + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + amount: + type: number + format: double + minimum: 0 + description: The amount to grant. Should be a positive number. + example: 100 + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: |- + The priority of the grant. Grants with higher priority are applied first. + Priority is a positive decimal numbers. With lower numbers indicating higher importance. + For example, a priority of 1 is more urgent than a priority of 2. + When there are several grants available for the same subject, the system selects the grant with the highest priority. + In cases where grants share the same priority level, the grant closest to its expiration will be used first. + In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + example: 1 + effectiveAt: + type: string + format: date-time + description: Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + example: '2023-01-01T01:01:01.001Z' + minRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + default: 0 + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: The grant metadata. + example: + stripePaymentId: pi_4OrAkhLvyihio9p51h9iiFnB + maxRolloverAmount: + type: number + format: double + description: |- + Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + example: 100 + expiration: + allOf: + - $ref: '#/components/schemas/ExpirationPeriod' + description: The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Grant annotations + example: + internal_reference: internal_reference + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + entitlementId: + type: string + description: The unique entitlement ULID that the grant is associated with. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + nextRecurrence: + type: string + format: date-time + description: The next time the grant will recurr. + example: '2023-01-01T01:01:01.001Z' + expiresAt: + type: string + format: date-time + description: The time the grant expires. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + voidedAt: + type: string + format: date-time + description: The time the grant was voided. + example: '2023-01-01T01:01:01.001Z' + recurrence: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The recurrence period of the grant. + description: The grant. + EntitlementMetered: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - subjectKey + - featureKey + - featureId + - lastReset + - currentUsagePeriod + - measureUsageFrom + - usagePeriod + properties: + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + isUnlimited: + type: boolean + description: Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + deprecated: true + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + default: 1 + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + lastReset: + type: string + format: date-time + description: The time the last reset happened. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + readOnly: true + measureUsageFrom: + type: string + format: date-time + description: The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: THe usage period of the entitlement. + readOnly: true + description: |- + Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + deprecated: true + EntitlementMeteredCalculatedFields: + type: object + required: + - lastReset + - currentUsagePeriod + - measureUsageFrom + - usagePeriod + properties: + lastReset: + type: string + format: date-time + description: The time the last reset happened. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + readOnly: true + measureUsageFrom: + type: string + format: date-time + description: The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: THe usage period of the entitlement. + readOnly: true + description: Calculated fields for metered entitlements. + EntitlementMeteredCreateInputs: + type: object + required: + - type + - usagePeriod + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + isUnlimited: + type: boolean + description: Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + deprecated: true + default: false + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + measureUsageFrom: + allOf: + - $ref: '#/components/schemas/MeasureUsageFrom' + description: Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + default: 1 + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + description: Create inpurs for metered entitlement + deprecated: true + EntitlementMeteredV2: + type: object + required: + - type + - createdAt + - updatedAt + - activeFrom + - id + - featureKey + - featureId + - lastReset + - currentUsagePeriod + - measureUsageFrom + - usagePeriod + - customerId + properties: + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + deprecated: true + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + deprecated: true + default: 1 + issue: + allOf: + - $ref: '#/components/schemas/IssueAfterReset' + description: Issue after reset + title: Issue after reset + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + lastReset: + type: string + format: date-time + description: The time the last reset happened. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + readOnly: true + measureUsageFrom: + type: string + format: date-time + description: The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: THe usage period of the entitlement. + readOnly: true + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: |- + Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + EntitlementMeteredV2CreateInputs: + type: object + required: + - type + - usagePeriod + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + measureUsageFrom: + allOf: + - $ref: '#/components/schemas/MeasureUsageFrom' + description: Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + deprecated: true + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + deprecated: true + default: 1 + issue: + allOf: + - $ref: '#/components/schemas/IssueAfterReset' + description: Issue after reset + title: Issue after reset + grants: + type: array + items: + $ref: '#/components/schemas/EntitlementGrantCreateInputV2' + description: Grants + title: Grants + description: Create inputs for metered entitlement + EntitlementOrderBy: + type: string + enum: + - createdAt + - updatedAt + description: Order by options for entitlements. + EntitlementPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Entitlement' + description: The items in the current page. + description: Paginated response + EntitlementStatic: + type: object + required: + - type + - config + - createdAt + - updatedAt + - activeFrom + - id + - subjectKey + - featureKey + - featureId + properties: + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + subjectKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier key unique to the subject. + NOTE: Subjects are being deprecated, please use the new customer APIs. + example: customer-1 + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + description: A static entitlement. + deprecated: true + EntitlementStaticCreateInputs: + type: object + required: + - type + - config + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The feature the subject is entitled to use. + Either featureKey or featureId is required. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriodCreateInput' + description: The usage period associated with the entitlement. + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + description: Create inputs for static entitlement + deprecated: true + EntitlementStaticV2: + type: object + required: + - type + - config + - createdAt + - updatedAt + - activeFrom + - id + - featureKey + - featureId + - customerId + properties: + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: The annotations of the entitlement. + example: + subscription.id: sub_123 + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the subject is entitled to use. + example: example-feature-key + featureId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The feature the subject is entitled to use. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + currentUsagePeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current usage period. + usagePeriod: + allOf: + - $ref: '#/components/schemas/RecurringPeriod' + description: The defined usage period of the entitlement + customerKey: + type: string + description: The identifier key unique to the customer + example: customer-1 + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The identifier unique to the customer + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + description: A static entitlement. + EntitlementType: + type: string + enum: + - metered + - boolean + - static + description: Type of the entitlement. + deprecated: true + x-go-type: string + EntitlementV2: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMeteredV2' + - $ref: '#/components/schemas/EntitlementStaticV2' + - $ref: '#/components/schemas/EntitlementBooleanV2' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMeteredV2' + static: '#/components/schemas/EntitlementStaticV2' + boolean: '#/components/schemas/EntitlementBooleanV2' + description: |- + Entitlement templates are used to define the entitlements of a plan. + Features are omitted from the entitlement template, as they are defined in the rate card. + EntitlementV2CreateInputs: + type: object + oneOf: + - $ref: '#/components/schemas/EntitlementMeteredV2CreateInputs' + - $ref: '#/components/schemas/EntitlementStaticCreateInputs' + - $ref: '#/components/schemas/EntitlementBooleanCreateInputs' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/EntitlementMeteredV2CreateInputs' + static: '#/components/schemas/EntitlementStaticCreateInputs' + boolean: '#/components/schemas/EntitlementBooleanCreateInputs' + description: Create inputs for entitlement + EntitlementV2PaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/EntitlementV2' + description: The items in the current page. + description: Paginated response + EntitlementValue: + type: object + required: + - hasAccess + properties: + hasAccess: + type: boolean + description: Whether the subject has access to the feature. Shared accross all entitlement types. + example: true + readOnly: true + balance: + type: number + format: double + description: Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + example: 100 + readOnly: true + usage: + type: number + format: double + description: Only available for metered entitlements. Returns the total feature usage in the current period. + example: 50 + readOnly: true + overage: + type: number + format: double + description: Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + example: 0 + readOnly: true + totalAvailableGrantAmount: + type: number + format: double + description: Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + example: 100 + readOnly: true + config: + type: string + description: Only available for static entitlements. The JSON parsable config of the entitlement. + example: '{ key: "value" }' + readOnly: true + description: Entitlements are the core of OpenMeter access management. They define access to features for subjects. Entitlements can be metered, boolean, or static. + EntitlementValueV2: + type: object + required: + - hasAccess + properties: + hasAccess: + type: boolean + description: Whether the subject has access to the feature. Shared accross all entitlement types. + example: true + readOnly: true + balance: + type: number + format: double + description: Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + example: 100 + readOnly: true + usage: + type: number + format: double + description: Only available for metered entitlements. Returns the total feature usage in the current period. + example: 50 + readOnly: true + overage: + type: number + format: double + description: Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + example: 0 + readOnly: true + totalAvailableGrantAmount: + type: number + format: double + description: Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + example: 100 + readOnly: true + config: + type: string + description: Only available for static entitlements. The JSON parsable config of the entitlement. + example: '{ key: "value" }' + readOnly: true + grantBalances: + type: object + additionalProperties: + type: number + format: double + description: |- + Only available for metered entitlements. The closing balance of each active grant at query time. + The key is the grant ID and the value is the remaining balance. + readOnly: true + description: EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 APIs. + ErrorExtension: + type: object + required: + - field + - code + - message + properties: + field: + type: string + description: The path to the field. + example: addons/pro/ratecards/token/featureKey + readOnly: true + code: + type: string + description: The machine readable description of the error. + example: invalid_feature_key + readOnly: true + message: + type: string + description: The human readable description of the error. + example: not found feature by key + readOnly: true + additionalProperties: {} + description: Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode] + Event: + type: object + required: + - id + - source + - specversion + - type + - subject + properties: + id: + type: string + minLength: 1 + description: Identifies the event. + example: 5c10fade-1c9e-4d6c-8275-c52c36731d3c + source: + type: string + minLength: 1 + format: uri-reference + description: Identifies the context in which an event happened. + example: service-name + specversion: + type: string + minLength: 1 + description: The version of the CloudEvents specification which the event uses. + example: '1.0' + default: '1.0' + type: + type: string + minLength: 1 + description: Contains a value describing the type of event related to the originating occurrence. + example: com.example.someevent + datacontenttype: + type: string + enum: + - application/json + nullable: true + description: Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP. + example: application/json + dataschema: + type: string + format: uri + nullable: true + minLength: 1 + description: Identifies the schema that data adheres to. + subject: + type: string + minLength: 1 + description: Describes the subject of the event in the context of the event producer (identified by source). + example: customer-id + time: + type: string + format: date-time + description: Timestamp of when the occurrence happened. Must adhere to RFC 3339. + example: '2023-01-01T01:01:01.001Z' + nullable: true + data: + type: object + additionalProperties: {} + nullable: true + description: |- + The event payload. + Optional, if present it must be a JSON object. + description: |- + CloudEvents Specification JSON Schema + + Optional properties are nullable according to the CloudEvents specification: + OPTIONAL not omitted attributes MAY be represented as a null JSON value. + example: + id: 5c10fade-1c9e-4d6c-8275-c52c36731d3c + source: service-name + specversion: '1.0' + type: prompt + subject: customer-id + time: '2023-01-01T01:01:01.001Z' + x-go-type-import: + path: github.com/cloudevents/sdk-go/v2/event + x-go-type: event.Event + EventDeliveryAttemptResponse: + type: object + required: + - body + - durationMs + properties: + statusCode: + type: integer + description: Status code of the response if available. + title: Status Code + readOnly: true + body: + type: string + description: The body of the response. + title: Response Body + readOnly: true + durationMs: + type: integer + description: The duration of the response in milliseconds. + title: Response Duration + readOnly: true + url: + type: string + description: URL where the event was sent in case of notification channel with webhook type. + title: URL + readOnly: true + description: The response of the event delivery attempt. + ExpirationDuration: + type: string + enum: + - HOUR + - DAY + - WEEK + - MONTH + - YEAR + description: The expiration duration enum + ExpirationPeriod: + type: object + required: + - duration + - count + properties: + duration: + allOf: + - $ref: '#/components/schemas/ExpirationDuration' + description: The unit of time for the expiration period. + count: + type: integer + format: uint32 + minimum: 1 + maximum: 1000 + description: The number of time units in the expiration period. + example: 12 + description: The grant expiration definition + Feature: + type: object + required: + - createdAt + - updatedAt + - key + - name + - id + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + archivedAt: + type: string + format: date-time + description: Timestamp of when the resource was archived. + example: '2023-01-01T01:01:01.001Z' + title: Archival Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: The unique key of the feature + name: + type: string + title: The human-readable name of the feature + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + title: Optional metadata + example: + key: value + meterSlug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: Meter slug + example: tokens_total + meterGroupByFilters: + type: object + additionalProperties: + type: string + description: |- + Optional meter group by filters. + Useful if the meter scope is broader than what feature tracks. + Example scenario would be a meter tracking all token use with groupBy fields for the model, + then the feature could filter for model=gpt-4. + + ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + title: Meter group by filters + deprecated: true + example: + model: gpt-4 + type: input + advancedMeterGroupByFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/FilterString' + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + title: Advanced meter group by filters + example: + model: + $in: + - gpt-4 + - gpt-4o + type: + $eq: input + unitCost: + allOf: + - $ref: '#/components/schemas/FeatureUnitCost' + description: |- + Optional per-unit cost configuration. + Use "manual" for a fixed per-unit cost, or "llm" to look up cost + from the LLM cost database based on meter group-by properties. + title: Unit cost + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Readonly unique ULID identifier. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + readOnly: true + description: |- + Represents a feature that can be enabled or disabled for a plan. + Used both for product catalog and entitlements. + FeatureCreateInputs: + type: object + required: + - key + - name + properties: + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: The unique key of the feature + name: + type: string + title: The human-readable name of the feature + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + title: Optional metadata + example: + key: value + meterSlug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A key is a unique string that is used to identify a resource. + title: Meter slug + example: tokens_total + meterGroupByFilters: + type: object + additionalProperties: + type: string + description: |- + Optional meter group by filters. + Useful if the meter scope is broader than what feature tracks. + Example scenario would be a meter tracking all token use with groupBy fields for the model, + then the feature could filter for model=gpt-4. + + ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + title: Meter group by filters + deprecated: true + example: + model: gpt-4 + type: input + advancedMeterGroupByFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/FilterString' + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + title: Advanced meter group by filters + example: + model: + $in: + - gpt-4 + - gpt-4o + type: + $eq: input + unitCost: + allOf: + - $ref: '#/components/schemas/FeatureUnitCost' + description: |- + Optional per-unit cost configuration. + Use "manual" for a fixed per-unit cost, or "llm" to look up cost + from the LLM cost database based on meter group-by properties. + title: Unit cost + description: |- + Represents a feature that can be enabled or disabled for a plan. + Used both for product catalog and entitlements. + FeatureLLMUnitCost: + type: object + required: + - type + properties: + type: + type: string + enum: + - llm + providerProperty: + type: string + description: |- + Meter group-by property that holds the LLM provider. + Use this when the meter has a group-by dimension for provider. + Mutually exclusive with `provider`. + title: Provider property + provider: + type: string + description: |- + Static LLM provider value (e.g., "openai", "anthropic"). + Use this when the feature tracks a single provider. + Mutually exclusive with `providerProperty`. + title: Provider + modelProperty: + type: string + description: |- + Meter group-by property that holds the model ID. + Use this when the meter has a group-by dimension for model. + Mutually exclusive with `model`. + title: Model property + model: + type: string + description: |- + Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). + Use this when the feature tracks a single model. + Mutually exclusive with `modelProperty`. + title: Model + tokenTypeProperty: + type: string + description: |- + Meter group-by property that holds the token type. + Use this when the meter has a group-by dimension for token type. + Mutually exclusive with `tokenType`. + title: Token type property + tokenType: + type: string + description: |- + Static token type value. + Use this when the feature tracks a single token type (e.g., only input tokens). + Expected values: input, output, cache_read, reasoning, cache_write, request, response. + `request` is an alias for `input`, `response` is an alias for `output`. + Mutually exclusive with `tokenTypeProperty`. + title: Token type + pricing: + allOf: + - $ref: '#/components/schemas/FeatureLLMUnitCostPricing' + description: |- + Resolved per-token pricing from the LLM cost database. + Only populated in responses when the feature's meter group-by filters + specify exact provider and model values. + title: Resolved pricing + readOnly: true + description: |- + LLM cost lookup configuration. + Maps meter group-by dimensions to LLM cost database fields. + FeatureLLMUnitCostPricing: + type: object + required: + - inputPerToken + - outputPerToken + properties: + inputPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per input token in USD. + title: Input per token + outputPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per output token in USD. + title: Output per token + cacheReadPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per cache read token in USD. + title: Cache read per token + reasoningPerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per reasoning token in USD. + title: Reasoning per token + cacheWritePerToken: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Cost per cache write token in USD. + title: Cache write per token + description: Resolved per-token pricing from the LLM cost database. + FeatureManualUnitCost: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - manual + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Fixed per-unit cost amount in USD. + description: A fixed per-unit cost amount. + FeatureMeta: + type: object + required: + - id + - key + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Unique identifier of a feature. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Feature Unique Identifier + key: + type: string + description: |- + The key is an immutable unique identifier of the feature used throughout the API, + for example when interacting with a subject's entitlements. + title: Feature Key + example: gpt4_tokens + description: Limited representation of a feature resource which includes only its unique identifiers (id, key). + FeatureOrderBy: + type: string + enum: + - id + - key + - name + - createdAt + - updatedAt + description: Order by options for features. + FeaturePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Feature' + description: The items in the current page. + description: Paginated response + FeatureUnitCost: + type: object + oneOf: + - $ref: '#/components/schemas/FeatureManualUnitCost' + - $ref: '#/components/schemas/FeatureLLMUnitCost' + discriminator: + propertyName: type + mapping: + manual: '#/components/schemas/FeatureManualUnitCost' + llm: '#/components/schemas/FeatureLLMUnitCost' + description: |- + Per-unit cost configuration for a feature. + Either a fixed manual amount or a dynamic LLM cost lookup. + FeatureUnitCostType: + type: string + enum: + - llm + - manual + description: The type of unit cost. + FilterBoolean: + type: object + properties: + $eq: + type: boolean + nullable: true + description: The field must be equal to the provided value. + x-omitempty: true + description: A filter for a boolean field. + FilterFloat: + type: object + properties: + $eq: + type: number + format: double + nullable: true + description: The field must be equal to the provided value. + x-omitempty: true + $ne: + type: number + format: double + nullable: true + description: The field must not be equal to the provided value. + x-omitempty: true + $gt: + type: number + format: double + nullable: true + description: The field must be greater than the provided value. + x-omitempty: true + $gte: + type: number + format: double + nullable: true + description: The field must be greater than or equal to the provided value. + x-omitempty: true + $lt: + type: number + format: double + nullable: true + description: The field must be less than the provided value. + x-omitempty: true + $lte: + type: number + format: double + nullable: true + description: The field must be less than or equal to the provided value. + x-omitempty: true + $and: + type: array + items: + $ref: '#/components/schemas/FilterFloat' + nullable: true + description: Provide a list of filters to be combined with a logical AND. + x-omitempty: true + $or: + type: array + items: + $ref: '#/components/schemas/FilterFloat' + nullable: true + description: Provide a list of filters to be combined with a logical OR. + x-omitempty: true + description: A filter for a float field. + FilterIDExact: + type: object + properties: + $in: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + nullable: true + description: The field must be in the provided list of values. + x-omitempty: true + description: A filter for a ID (ULID) field allowing only equality or inclusion. + FilterInteger: + type: object + properties: + $eq: + type: integer + nullable: true + description: The field must be equal to the provided value. + x-omitempty: true + $ne: + type: integer + nullable: true + description: The field must not be equal to the provided value. + x-omitempty: true + $gt: + type: integer + nullable: true + description: The field must be greater than the provided value. + x-omitempty: true + $gte: + type: integer + nullable: true + description: The field must be greater than or equal to the provided value. + x-omitempty: true + $lt: + type: integer + nullable: true + description: The field must be less than the provided value. + x-omitempty: true + $lte: + type: integer + nullable: true + description: The field must be less than or equal to the provided value. + x-omitempty: true + $and: + type: array + items: + $ref: '#/components/schemas/FilterInteger' + nullable: true + description: Provide a list of filters to be combined with a logical AND. + x-omitempty: true + $or: + type: array + items: + $ref: '#/components/schemas/FilterInteger' + nullable: true + description: Provide a list of filters to be combined with a logical OR. + x-omitempty: true + description: A filter for an integer field. + FilterString: + type: object + properties: + $eq: + type: string + nullable: true + description: The field must be equal to the provided value. + x-omitempty: true + $ne: + type: string + nullable: true + description: The field must not be equal to the provided value. + x-omitempty: true + $in: + type: array + items: + type: string + nullable: true + description: The field must be in the provided list of values. + x-omitempty: true + $nin: + type: array + items: + type: string + nullable: true + description: The field must not be in the provided list of values. + x-omitempty: true + $like: + type: string + nullable: true + description: The field must match the provided value. + x-omitempty: true + $nlike: + type: string + nullable: true + description: The field must not match the provided value. + x-omitempty: true + $ilike: + type: string + nullable: true + description: The field must match the provided value, ignoring case. + x-omitempty: true + $nilike: + type: string + nullable: true + description: The field must not match the provided value, ignoring case. + x-omitempty: true + $gt: + type: string + nullable: true + description: The field must be greater than the provided value. + x-omitempty: true + $gte: + type: string + nullable: true + description: The field must be greater than or equal to the provided value. + x-omitempty: true + $lt: + type: string + nullable: true + description: The field must be less than the provided value. + x-omitempty: true + $lte: + type: string + nullable: true + description: The field must be less than or equal to the provided value. + x-omitempty: true + $and: + type: array + items: + $ref: '#/components/schemas/FilterString' + nullable: true + description: Provide a list of filters to be combined with a logical AND. + x-omitempty: true + $or: + type: array + items: + $ref: '#/components/schemas/FilterString' + nullable: true + description: Provide a list of filters to be combined with a logical OR. + x-omitempty: true + description: A filter for a string field. + FilterTime: + type: object + properties: + $gt: + type: string + format: date-time + nullable: true + description: The field must be greater than the provided value. + x-omitempty: true + $gte: + type: string + format: date-time + nullable: true + description: The field must be greater than or equal to the provided value. + x-omitempty: true + $lt: + type: string + format: date-time + nullable: true + description: The field must be less than the provided value. + x-omitempty: true + $lte: + type: string + format: date-time + nullable: true + description: The field must be less than or equal to the provided value. + x-omitempty: true + $and: + type: array + items: + $ref: '#/components/schemas/FilterTime' + nullable: true + description: Provide a list of filters to be combined with a logical AND. + x-omitempty: true + $or: + type: array + items: + $ref: '#/components/schemas/FilterTime' + nullable: true + description: Provide a list of filters to be combined with a logical OR. + x-omitempty: true + description: A filter for a time field. + FlatPrice: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - flat + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the flat price. + description: Flat price. + FlatPriceWithPaymentTerm: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - flat + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the flat price. + paymentTerm: + allOf: + - $ref: '#/components/schemas/PricePaymentTerm' + description: |- + The payment term of the flat price. + Defaults to in advance. + default: in_advance + description: Flat price with payment term. + ForbiddenProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server understood the request but refuses to authorize it. + GatewayTimeoutProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. + GrantBurnDownHistorySegment: + type: object + required: + - period + - usage + - overage + - balanceAtStart + - grantBalancesAtStart + - balanceAtEnd + - grantBalancesAtEnd + - grantUsages + properties: + period: + allOf: + - $ref: '#/components/schemas/Period' + description: The period of the segment. + usage: + type: number + format: double + description: The total usage of the grant in the period. + example: 100 + readOnly: true + overage: + type: number + format: double + description: Overuse that wasn't covered by grants. + example: 100 + readOnly: true + balanceAtStart: + type: number + format: double + description: entitlement balance at the start of the period. + example: 100 + readOnly: true + grantBalancesAtStart: + type: object + additionalProperties: + type: number + format: double + description: 'The balance breakdown of each active grant at the start of the period: GrantID: Balance' + example: + 01G65Z755AFWAKHE12NY0CQ9FH: 100 + readOnly: true + balanceAtEnd: + type: number + format: double + description: The entitlement balance at the end of the period. + example: 100 + readOnly: true + grantBalancesAtEnd: + type: object + additionalProperties: + type: number + format: double + description: 'The balance breakdown of each active grant at the end of the period: GrantID: Balance' + example: + 01G65Z755AFWAKHE12NY0CQ9FH: 100 + readOnly: true + grantUsages: + type: array + items: + $ref: '#/components/schemas/GrantUsageRecord' + description: Which grants were actually burnt down in the period and by what amount. + readOnly: true + description: |- + A segment of the grant burn down history. + + A given segment represents the usage of a grant between events that changed either the grant burn down priority order or the usag period. + GrantOrderBy: + type: string + enum: + - id + - createdAt + - updatedAt + description: Order by options for grants. + GrantPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/EntitlementGrant' + description: The items in the current page. + description: Paginated response + GrantUsageRecord: + type: object + required: + - grantId + - usage + properties: + grantId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The id of the grant + example: 01G65Z755AFWAKHE12NY0CQ9FH + usage: + type: number + format: double + description: The usage in the period + example: 100 + description: Usage Record + GrantV2PaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/EntitlementGrantV2' + description: The items in the current page. + description: Paginated response + IDResource: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + description: IDResource is a resouce with an ID. + IngestEventsBody: + anyOf: + - $ref: '#/components/schemas/Event' + - type: array + items: + $ref: '#/components/schemas/Event' + description: |- + The body of the events request. + Either a single event or a batch of events. + IngestedEvent: + type: object + required: + - event + - ingestedAt + - storedAt + properties: + event: + allOf: + - $ref: '#/components/schemas/Event' + description: The original event ingested. + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID if the event is associated with a customer. + example: 01G65Z755AFWAKHE12NY0CQ9FH + validationError: + type: string + description: The validation error if the event failed validation. + ingestedAt: + type: string + format: date-time + description: The date and time the event was ingested. + example: '2023-01-01T01:01:01.001Z' + storedAt: + type: string + format: date-time + description: The date and time the event was stored. + example: '2023-01-01T01:01:01.001Z' + description: An ingested event with optional validation error. + example: + event: + id: 5c10fade-1c9e-4d6c-8275-c52c36731d3c + source: service-name + specversion: '1.0' + type: prompt + subject: customer-id + time: '2023-01-01T01:01:01.001Z' + ingestedAt: '2023-01-01T01:01:01.001Z' + storedAt: '2023-01-01T01:01:02.001Z' + IngestedEventCursorPaginatedResponse: + type: object + required: + - items + properties: + items: + type: array + items: + $ref: '#/components/schemas/IngestedEvent' + maxItems: 100 + description: The items in the response. + nextCursor: + type: string + description: The cursor of the last item in the list. + description: A response for cursor pagination. + InstallMethod: + type: string + enum: + - with_oauth2 + - with_api_key + - no_credentials_required + description: Install method of the application. + InternalServerErrorProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server encountered an unexpected condition that prevented it from fulfilling the request. + Invoice: + type: object + required: + - id + - createdAt + - updatedAt + - type + - supplier + - customer + - number + - currency + - totals + - status + - statusDetails + - workflow + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/InvoiceType' + description: |- + Type of the invoice. + + The type of invoice determines the purpose of the invoice and how it should be handled. + + Supported types: + - standard: A regular commercial invoice document between a supplier and customer. + - credit_note: Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + readOnly: true + supplier: + allOf: + - $ref: '#/components/schemas/BillingParty' + description: The taxable entity supplying the goods or services. + customer: + allOf: + - $ref: '#/components/schemas/BillingInvoiceCustomerExtendedDetails' + description: Legal entity receiving the goods or services. + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: |- + Number specifies the human readable key used to reference this Invoice. + + The invoice number can change in the draft phases, as we are allocating temporary draft + invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + + Please note that the number is (depending on the upstream settings) either unique for the + whole organization or unique for the customer, or in multi (stripe) account setups unique for the + account. + readOnly: true + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency for all invoice line items. + + Multi currency invoices are not supported yet. + preceding: + type: array + items: + $ref: '#/components/schemas/InvoiceDocumentRef' + description: Key information regarding previous invoices and potentially details as to why they were corrected. + readOnly: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Summary of all the invoice totals, including taxes (calculated). + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceStatus' + description: |- + The status of the invoice. + + This field only conatins a simplified status, for more detailed information use the statusDetails field. + readOnly: true + statusDetails: + allOf: + - $ref: '#/components/schemas/InvoiceStatusDetails' + description: The details of the current invoice status. + readOnly: true + issuedAt: + type: string + format: date-time + description: |- + The time the invoice was issued. + + Depending on the status of the invoice this can mean multiple things: + - draft, gathering: The time the invoice will be issued based on the workflow settings. + - issued: The time the invoice was issued. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + draftUntil: + type: string + format: date-time + description: |- + The time until the invoice is in draft status. + + On draft invoice creation it is calculated from the workflow settings. + + If manual approval is required, the draftUntil time is set. + example: '2023-01-01T01:01:01.001Z' + quantitySnapshotedAt: + type: string + format: date-time + description: The time when the quantity snapshots on the invoice lines were taken. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + collectionAt: + type: string + format: date-time + description: The time when the invoice will be/has been collected. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + dueAt: + type: string + format: date-time + description: Due time of the fulfillment of the invoice (if available). + example: '2023-01-01T01:01:01.001Z' + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: The period the invoice covers. If the invoice has no line items, it's not set. + voidedAt: + type: string + format: date-time + description: |- + The time the invoice was voided. + + If the invoice was voided, this field will be set to the time the invoice was voided. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + sentToCustomerAt: + type: string + format: date-time + description: The time the invoice was sent to customer. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + workflow: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowSettings' + description: |- + The workflow associated with the invoice. + + It is always a snapshot of the workflow settings at the time of invoice creation. The + field is optional as it should be explicitly requested with expand options. + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceLine' + description: List of invoice lines representing each of the items sold to the customer. + payment: + allOf: + - $ref: '#/components/schemas/InvoicePaymentTerms' + description: Information on when, how, and to whom the invoice should be paid. + readOnly: true + validationIssues: + type: array + items: + $ref: '#/components/schemas/ValidationIssue' + description: Validation issues reported by the invoice workflow. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + description: Invoice represents an invoice in the system. + InvoiceAppExternalIds: + type: object + properties: + invoicing: + type: string + description: The external ID of the invoice in the invoicing app if available. + readOnly: true + tax: + type: string + description: The external ID of the invoice in the tax app if available. + readOnly: true + payment: + type: string + description: The external ID of the invoice in the payment app if available. + readOnly: true + description: InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + InvoiceAvailableActionDetails: + type: object + required: + - resultingState + properties: + resultingState: + type: string + description: |- + The state the invoice will reach if the action is activated and + all intermediate steps are successful. + + For example advancing a draft_created invoice will result in a draft_manual_approval_needed invoice. + readOnly: true + description: |- + InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + non-gathering invoices. + InvoiceAvailableActionInvoiceDetails: + type: object + description: |- + InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + gathering invoices. + InvoiceAvailableActions: + type: object + properties: + advance: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Advance the invoice to the next status. + readOnly: true + approve: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Approve an invoice that requires manual approval. + readOnly: true + delete: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Delete the invoice (only non-issued invoices can be deleted). + readOnly: true + retry: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Retry an invoice issuing step that failed. + readOnly: true + snapshotQuantities: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Snapshot quantities for usage based line items. + readOnly: true + void: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionDetails' + description: Void an already issued invoice. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActionInvoiceDetails' + description: Invoice a gathering invoice + readOnly: true + description: InvoiceAvailableActions represents the actions that can be performed on the invoice. + InvoiceDetailedLine: + type: object + required: + - name + - createdAt + - updatedAt + - id + - managedBy + - status + - currency + - totals + - period + - invoiceAt + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + managedBy: + allOf: + - $ref: '#/components/schemas/InvoiceLineManagedBy' + description: managedBy specifies if the line is manually added via the api or managed by OpenMeter. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceLineStatus' + description: |- + Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. + readOnly: true + discounts: + allOf: + - $ref: '#/components/schemas/InvoiceLineDiscounts' + description: |- + Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + readOnly: true + creditAllocations: + type: array + items: + $ref: '#/components/schemas/InvoiceLineCreditAllocation' + description: |- + Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceReference' + description: The invoice this item belongs to. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of this line. + taxes: + type: array + items: + $ref: '#/components/schemas/InvoiceLineTaxItem' + description: Taxes applied to the invoice totals. + readOnly: true + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Totals for this line. + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + subscription: + allOf: + - $ref: '#/components/schemas/InvoiceLineSubscriptionReference' + description: Subscription are the references to the subscritpions that this line is related to. + readOnly: true + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + deprecated: true + type: + type: string + enum: + - flat_fee + description: Type of the line. + deprecated: true + readOnly: true + perUnitAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Price of the item being sold. + deprecated: true + paymentTerm: + allOf: + - $ref: '#/components/schemas/PricePaymentTerm' + description: Payment term of the line. + deprecated: true + default: in_advance + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Quantity of the item being sold. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceDetailedLineRateCard' + description: The rate card that is used for this line. + category: + allOf: + - $ref: '#/components/schemas/InvoiceDetailedLineCostCategory' + description: Category of the flat fee. + default: regular + readOnly: true + description: InvoiceDetailedLine represents a line item that is sold to the customer as a manually added fee. + InvoiceDetailedLineCostCategory: + type: string + enum: + - regular + - commitment + description: |- + InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a + commitment. + InvoiceDetailedLineRateCard: + type: object + required: + - price + properties: + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + price: + type: object + allOf: + - $ref: '#/components/schemas/FlatPriceWithPaymentTerm' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + title: Price + example: + type: flat + amount: '100' + paymentTerm: in_arrears + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + Quantity of the item being sold. + + Default: 1 + discounts: + allOf: + - $ref: '#/components/schemas/BillingDiscounts' + description: The discounts that are applied to the line. + description: InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. + InvoiceDiscountBase: + type: object + required: + - createdAt + - updatedAt + - id + - reason + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + reason: + allOf: + - $ref: '#/components/schemas/BillingDiscountReason' + description: Reason code. + readOnly: true + description: + type: string + description: Text description as to why the discount was applied. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + description: InvoiceDiscountBase represents a charge or discount that can be applied to a line or the entire invoice. + InvoiceDocumentRef: + type: object + allOf: + - $ref: '#/components/schemas/CreditNoteOriginalInvoiceRef' + description: InvoiceDocumentRef is used to describe a reference to an existing document (invoice). + InvoiceDocumentRefType: + type: string + enum: + - credit_note_original_invoice + description: InvoiceDocumentRefType defines the type of document that is being referenced. + InvoiceExpand: + type: string + enum: + - lines + - preceding + - workflow.apps + description: InvoiceExpand specifies the parts of the invoice to expand in the list output. + InvoiceGenericDocumentRef: + type: object + required: + - type + properties: + type: + allOf: + - $ref: '#/components/schemas/InvoiceDocumentRefType' + description: Type of the document referenced. + readOnly: true + reason: + type: string + description: Human readable description on why this reference is here or needs to be used. + readOnly: true + description: + type: string + description: Additional details about the document. + readOnly: true + description: |- + Omitted fields: + period: Tax period in which the referred document had an effect required by some tax regimes and formats. + stamps: Seals of approval from other organisations that may need to be listed. + ext: Extensions for additional codes that may be required. + title: InvoiceGenericDocumentRef is used to describe an existing document or a specific part of it's contents. + InvoiceLine: + type: object + required: + - name + - createdAt + - updatedAt + - id + - managedBy + - status + - currency + - totals + - period + - invoiceAt + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + managedBy: + allOf: + - $ref: '#/components/schemas/InvoiceLineManagedBy' + description: managedBy specifies if the line is manually added via the api or managed by OpenMeter. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceLineStatus' + description: |- + Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. + readOnly: true + discounts: + allOf: + - $ref: '#/components/schemas/InvoiceLineDiscounts' + description: |- + Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + readOnly: true + creditAllocations: + type: array + items: + $ref: '#/components/schemas/InvoiceLineCreditAllocation' + description: |- + Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceReference' + description: The invoice this item belongs to. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of this line. + taxes: + type: array + items: + $ref: '#/components/schemas/InvoiceLineTaxItem' + description: Taxes applied to the invoice totals. + readOnly: true + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Totals for this line. + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + subscription: + allOf: + - $ref: '#/components/schemas/InvoiceLineSubscriptionReference' + description: Subscription are the references to the subscritpions that this line is related to. + readOnly: true + type: + type: string + enum: + - usage_based + description: Type of the line. + deprecated: true + readOnly: true + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + children: + type: array + items: + $ref: '#/components/schemas/InvoiceDetailedLine' + description: The lines detailing the item or service sold. + readOnly: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the item being sold. + + Any usage discounts applied previously are deducted from this quantity. + readOnly: true + meteredQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity of the item that has been metered for the period before any discounts were applied. + readOnly: true + preLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The quantity of the item used before this line's period. + + It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + + Any usage discounts applied previously are deducted from this quantity. + readOnly: true + meteredPreLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The metered quantity of the item used in before this line's period without any discounts applied. + + It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + readOnly: true + description: InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. + InvoiceLineAmountDiscount: + type: object + required: + - createdAt + - updatedAt + - id + - reason + - amount + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + reason: + allOf: + - $ref: '#/components/schemas/BillingDiscountReason' + description: Reason code. + readOnly: true + description: + type: string + description: Text description as to why the discount was applied. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Fixed discount amount to apply (calculated if percent present). + title: Amount in the currency of the invoice + readOnly: true + description: InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied before taxes. + InvoiceLineAppExternalIds: + type: object + properties: + invoicing: + type: string + description: The external ID of the invoice in the invoicing app if available. + readOnly: true + tax: + type: string + description: The external ID of the invoice in the tax app if available. + readOnly: true + description: InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + InvoiceLineBase: + type: object + required: + - name + - createdAt + - updatedAt + - id + - type + - managedBy + - status + - currency + - totals + - period + - invoiceAt + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + type: + allOf: + - $ref: '#/components/schemas/InvoiceLineTypes' + description: |- + Type of the line. + + A line's type cannot be changed after creation. + deprecated: true + readOnly: true + managedBy: + allOf: + - $ref: '#/components/schemas/InvoiceLineManagedBy' + description: managedBy specifies if the line is manually added via the api or managed by OpenMeter. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/InvoiceLineStatus' + description: |- + Status of the line. + + External calls always create valid lines, other line types are managed by the + billing engine of OpenMeter. + readOnly: true + discounts: + allOf: + - $ref: '#/components/schemas/InvoiceLineDiscounts' + description: |- + Discounts detailes applied to this line. + + New discounts can be added via the invoice's discounts API, to facilitate + discounts that are affecting multiple lines. + readOnly: true + creditAllocations: + type: array + items: + $ref: '#/components/schemas/InvoiceLineCreditAllocation' + description: |- + Credit allocations applied to this line. + + Credits are deducted from the line total before taxes are applied. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/InvoiceReference' + description: The invoice this item belongs to. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of this line. + taxes: + type: array + items: + $ref: '#/components/schemas/InvoiceLineTaxItem' + description: Taxes applied to the invoice totals. + readOnly: true + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + totals: + allOf: + - $ref: '#/components/schemas/InvoiceTotals' + description: Totals for this line. + readOnly: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + subscription: + allOf: + - $ref: '#/components/schemas/InvoiceLineSubscriptionReference' + description: Subscription are the references to the subscritpions that this line is related to. + readOnly: true + description: |- + InvoiceLine represents a single item or service sold to the customer. + + This is a base class for all line types, and should not be used directly. + InvoiceLineCreditAllocation: + type: object + required: + - amount + properties: + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Amount allocated from credits. + title: Amount in the currency of the invoice + readOnly: true + description: + type: string + description: Text description as to why the credit was allocated. + readOnly: true + description: InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are applied. + InvoiceLineDiscounts: + type: object + properties: + amount: + type: array + items: + $ref: '#/components/schemas/InvoiceLineAmountDiscount' + description: |- + Amount based discounts applied to the line. + + Amount based discounts are deduced from the total price of the line. + usage: + type: array + items: + $ref: '#/components/schemas/InvoiceLineUsageDiscount' + description: |- + Usage based discounts applied to the line. + + Usage based discounts are deduced from the usage of the line before price calculations are applied. + description: InvoiceLineDiscounts represents the discounts applied to the invoice line by type. + InvoiceLineManagedBy: + type: string + enum: + - subscription + - system + - manual + description: InvoiceLineManagedBy specifies who manages the line. + InvoiceLineReplaceUpdate: + type: object + required: + - name + - period + - invoiceAt + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the line. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: |- + InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. + + This type makes ID optional to allow for creating new lines as part of the update. + InvoiceLineStatus: + type: string + enum: + - valid + - detailed + - split + description: Line status specifies the status of the line. + InvoiceLineSubscriptionReference: + type: object + required: + - subscription + - phase + - item + - billingPeriod + properties: + subscription: + allOf: + - $ref: '#/components/schemas/IDResource' + description: The subscription. + readOnly: true + phase: + allOf: + - $ref: '#/components/schemas/IDResource' + description: The phase of the subscription. + readOnly: true + item: + allOf: + - $ref: '#/components/schemas/IDResource' + description: The item this line is related to. + readOnly: true + billingPeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + The billing period of the subscription. In case the subscription item's billing period is different + from the subscription's billing period, this field will contain the billing period of the subscription itself. + + For example, in case of: + - A monthly billed subscription anchored to 2025-01-01 + - A subscription item billed daily + + An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed daily, but the subscription's billing period + will be 2025-01-01 to 2025-01-31. + readOnly: true + description: InvoiceLineSubscriptionReference contains the references to the subscription that this line is related to. + InvoiceLineTaxBehavior: + type: string + enum: + - inclusive + - exclusive + description: |- + InvoiceLineTaxBehavior details how the tax item is applied to the base amount. + + Inclusive means the tax is included in the base amount. + Exclusive means the tax is added to the base amount. + InvoiceLineTaxItem: + type: object + properties: + config: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax provider configuration. + readOnly: true + percent: + allOf: + - $ref: '#/components/schemas/Percentage' + description: |- + Percent defines the percentage set manually or determined from + the rate key (calculated if rate present). A nil percent implies that + this tax combo is **exempt** from tax.") + readOnly: true + surcharge: + allOf: + - $ref: '#/components/schemas/Numeric' + description: Some countries require an additional surcharge (calculated if rate present). + readOnly: true + behavior: + allOf: + - $ref: '#/components/schemas/InvoiceLineTaxBehavior' + description: Is the tax item inclusive or exclusive of the base amount. + readOnly: true + description: TaxConfig stores the configuration for a tax line relative to an invoice line. + InvoiceLineTypes: + type: string + enum: + - flat_fee + - usage_based + description: LineTypes represents the different types of lines that can be used in an invoice. + deprecated: true + InvoiceLineUsageDiscount: + type: object + required: + - createdAt + - updatedAt + - id + - reason + - quantity + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + reason: + allOf: + - $ref: '#/components/schemas/BillingDiscountReason' + description: Reason code. + readOnly: true + description: + type: string + description: Text description as to why the discount was applied. + readOnly: true + externalIds: + allOf: + - $ref: '#/components/schemas/InvoiceLineAppExternalIds' + description: External IDs of the invoice in other apps such as Stripe. + readOnly: true + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The usage to apply. + title: Usage quantity in the unit of the underlying meter + readOnly: true + preLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + The usage discount already applied to the previous split lines. + + Only set if progressive billing is enabled and the line is a split line. + title: Usage quantity in the unit of the underlying meter + readOnly: true + description: |- + InvoiceLineUsageDiscount represents an usage-based discount applied to the line. + + The deduction is done before the pricing algorithm is applied. + InvoiceNumber: + type: string + minLength: 1 + maxLength: 256 + description: |- + InvoiceNumber is a unique identifier for the invoice, generated by the + invoicing app. + + The uniqueness depends on a lot of factors: + - app setting (unique per app or unique per customer) + - multiple app scenarios (multiple apps generating invoices with the same prefix) + example: INV-2024-01-01-01 + InvoiceOrderBy: + type: string + enum: + - customer.name + - issuedAt + - status + - createdAt + - updatedAt + - periodStart + description: InvoiceOrderBy specifies the ordering options for invoice listing. + InvoicePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Invoice' + description: The items in the current page. + description: Paginated response + InvoicePaymentTerms: + type: object + properties: + terms: + allOf: + - $ref: '#/components/schemas/PaymentTerms' + description: The terms of payment for the invoice. + description: Payment contains details as to how the invoice should be paid. + InvoicePendingLineCreate: + type: object + required: + - name + - period + - invoiceAt + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + description: InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage. + InvoicePendingLineCreateInput: + type: object + required: + - currency + - lines + properties: + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency of the lines to be created. + lines: + type: array + items: + $ref: '#/components/schemas/InvoicePendingLineCreate' + minItems: 1 + description: The lines to be created. + description: InvoicePendingLineCreate represents the create model for a pending invoice line. + InvoicePendingLineCreateResponse: + type: object + required: + - lines + - invoice + - isInvoiceNew + properties: + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceLine' + description: The lines that were created. + readOnly: true + invoice: + allOf: + - $ref: '#/components/schemas/Invoice' + description: The invoice containing the created lines. + readOnly: true + isInvoiceNew: + type: boolean + description: Whether the invoice was newly created. + readOnly: true + description: InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. + InvoicePendingLinesActionFiltersInput: + type: object + properties: + lineIds: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: |- + The pending line items to include in the invoice, if not provided: + - all line items that have invoice_at < asOf will be included + - [progressive billing only] all usage based line items will be included up to asOf, new + usage-based line items will be staged for the rest of the billing cycle + + All lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail. + description: InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. + InvoicePendingLinesActionInput: + type: object + required: + - customerId + properties: + filters: + allOf: + - $ref: '#/components/schemas/InvoicePendingLinesActionFiltersInput' + description: Filters to apply when creating the invoice. + asOf: + type: string + format: date-time + description: |- + The time as of which the invoice is created. + + If not provided, the current time is used. + example: '2023-01-01T01:01:01.001Z' + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID for which to create the invoice. + example: 01G65Z755AFWAKHE12NY0CQ9FH + progressiveBillingOverride: + type: boolean + description: |- + Override the progressive billing setting of the customer. + + Can be used to disable/enable progressive billing in case the business logic + requires it, if not provided the billing profile's progressive billing setting will be used. + description: |- + BillingInvoiceActionInput is the input for creating an invoice. + + Invoice creation is always based on already pending line items created by the billingCreateLineByCustomer + operation. Empty invoices are not allowed. + InvoiceReference: + type: object + required: + - id + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the invoice. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: The number of the invoice. + readOnly: true + description: Reference to an invoice. + InvoiceReplaceUpdate: + type: object + required: + - supplier + - customer + - lines + - workflow + properties: + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + supplier: + allOf: + - $ref: '#/components/schemas/BillingPartyReplaceUpdate' + description: The supplier of the lines included in the invoice. + customer: + allOf: + - $ref: '#/components/schemas/BillingPartyReplaceUpdate' + description: The customer the invoice is sent to. + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceLineReplaceUpdate' + description: The lines included in the invoice. + workflow: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowReplaceUpdate' + description: The workflow settings for the invoice. + description: InvoiceReplaceUpdate represents the update model for an invoice. + InvoiceSimulationInput: + type: object + required: + - currency + - lines + properties: + number: + allOf: + - $ref: '#/components/schemas/InvoiceNumber' + description: The number of the invoice. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + Currency for all invoice line items. + + Multi currency invoices are not supported yet. + lines: + type: array + items: + $ref: '#/components/schemas/InvoiceSimulationLine' + description: Lines to be included in the generated invoice. + description: InvoiceSimulationInput is the input for simulating an invoice. + InvoiceSimulationLine: + type: object + required: + - name + - period + - invoiceAt + - quantity + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: Tax config specify the tax configuration for this line. + deprecated: true + period: + allOf: + - $ref: '#/components/schemas/Period' + description: |- + Period of the line item applies to for revenue recognition pruposes. + + Billing always treats periods as start being inclusive and end being exclusive. + invoiceAt: + type: string + format: date-time + description: The time this line item should be invoiced. + example: '2023-01-01T01:01:01.001Z' + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + description: Price of the usage-based item being sold. + deprecated: true + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature that the usage is based on. + deprecated: true + rateCard: + allOf: + - $ref: '#/components/schemas/InvoiceUsageBasedRateCard' + description: |- + The rate card that is used for this line. + + The rate card captures the intent of the price and discounts for the usage-based item. + quantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity of the item being sold. + preLinePeriodQuantity: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity of the item used before this line's period, if the line is billed progressively. + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ID of the line. If not specified it will be auto-generated. + + When discounts are specified, this must be provided, so that the discount can reference it. + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint. + InvoiceStatus: + type: string + enum: + - gathering + - draft + - issuing + - issued + - payment_processing + - overdue + - paid + - uncollectible + - voided + description: InvoiceStatus describes the status of an invoice. + InvoiceStatusDetails: + type: object + required: + - immutable + - failed + - extendedStatus + - availableActions + properties: + immutable: + type: boolean + description: Is the invoice editable? + readOnly: true + failed: + type: boolean + description: Is the invoice in a failed state? + readOnly: true + extendedStatus: + type: string + description: Extended status information for the invoice. + readOnly: true + availableActions: + allOf: + - $ref: '#/components/schemas/InvoiceAvailableActions' + description: The actions that can be performed on the invoice. + description: |- + InvoiceStatusDetails represents the details of the invoice status. + + API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine + the next steps of the invoice instead of the extendedStatus field. + InvoiceTotals: + type: object + required: + - amount + - chargesTotal + - discountsTotal + - creditsTotal + - taxesInclusiveTotal + - taxesExclusiveTotal + - taxesTotal + - total + properties: + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total value of the line before taxes, discounts and commitments. + readOnly: true + chargesTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of value of the line that are due to additional charges. + readOnly: true + discountsTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of value of the line that are due to discounts. + readOnly: true + creditsTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of value of the line that are due to credits. + readOnly: true + taxesInclusiveTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount of taxes that are included in the line. + readOnly: true + taxesExclusiveTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount of taxes that are added on top of amount from the line. + readOnly: true + taxesTotal: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount of taxes for this line. + readOnly: true + total: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The total amount value of the line after taxes, discounts and commitments. + readOnly: true + description: Totals contains the summaries of all calculations for the invoice. + InvoiceType: + type: string + enum: + - standard + - credit_note + description: |- + InvoiceType represents the type of invoice. + + The type of invoice determines the purpose of the invoice and how it should be handled. + InvoiceUsageBasedRateCard: + type: object + required: + - price + properties: + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the customer is entitled to use. + title: Feature key + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + discounts: + allOf: + - $ref: '#/components/schemas/BillingDiscounts' + description: The discounts that are applied to the line. + deprecated: true + description: InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. + InvoiceWorkflowInvoicingSettingsReplaceUpdate: + type: object + properties: + autoAdvance: + type: boolean + description: Whether to automatically issue the invoice after the draftPeriod has passed. + default: true + draftPeriod: + type: string + format: ISO8601 + description: The period for the invoice to be kept in draft status for manual reviews. + example: P1D + default: P0D + dueAfter: + type: string + format: ISO8601 + description: |- + The period after which the invoice is due. + With some payment solutions it's only applicable for manual collection method. + example: P30D + default: P30D + subscriptionEndProrationMode: + allOf: + - $ref: '#/components/schemas/BillingWorkflowInvoicingSubscriptionEndProrationMode' + description: Controls how subscription-ending shortened service periods are billed. + default: bill_actual_period + defaultTaxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + Default tax configuration to apply to the invoices. + + Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + deprecated and can no longer be added or changed: the organization default tax code is + used instead. Existing tax-code values may still be removed, and `behavior` remains + fully supported. + description: InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow. + InvoiceWorkflowReplaceUpdate: + type: object + required: + - workflow + properties: + workflow: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowSettingsReplaceUpdate' + description: The workflow used for this invoice. + description: |- + InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. + + Fields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings. + InvoiceWorkflowSettings: + type: object + required: + - sourceBillingProfileId + - workflow + properties: + apps: + allOf: + - $ref: '#/components/schemas/BillingProfileAppsOrReference' + description: The apps that will be used to orchestrate the invoice's workflow. + readOnly: true + sourceBillingProfileId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + sourceBillingProfileID is the billing profile on which the workflow was based on. + + The profile is snapshotted on invoice creation, after which it can be altered independently + of the profile itself. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + workflow: + allOf: + - $ref: '#/components/schemas/BillingWorkflow' + description: The workflow details used by this invoice. + description: |- + InvoiceWorkflowSettings represents the workflow settings used by the invoice. + + This is a clone of the billing profile's workflow settings at the time of invoice creation + with customer overrides considered. + InvoiceWorkflowSettingsReplaceUpdate: + type: object + required: + - invoicing + - payment + properties: + invoicing: + allOf: + - $ref: '#/components/schemas/InvoiceWorkflowInvoicingSettingsReplaceUpdate' + description: The invoicing settings for this workflow + payment: + allOf: + - $ref: '#/components/schemas/BillingWorkflowPaymentSettings' + description: The payment settings for this workflow + description: |- + Mutable workflow settings for an invoice. + + Other fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow + at creation time. + IssueAfterReset: + type: object + required: + - amount + properties: + amount: + type: number + format: double + minimum: 0 + description: The initial grant amount + title: Initial grant amount + priority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: The priority of the issue after reset + title: Issue grant after reset priority + default: 1 + description: Issue after reset + ListAppsRequest: + type: object + properties: + page: + type: integer + minimum: 1 + description: |- + Page index. + + Default is 1. + example: 1 + default: 1 + pageSize: + type: integer + minimum: 1 + maximum: 1000 + description: |- + The maximum number of items per page. + + Default is 100. + example: 100 + default: 100 + description: Query params for listing installed apps + ListEntitlementsResult: + oneOf: + - type: array + items: + $ref: '#/components/schemas/Entitlement' + - $ref: '#/components/schemas/EntitlementPaginatedResponse' + description: List entitlements result + ListFeaturesResult: + oneOf: + - type: array + items: + $ref: '#/components/schemas/Feature' + - $ref: '#/components/schemas/FeaturePaginatedResponse' + description: List features result + MarketplaceInstallRequestPayload: + type: object + properties: + name: + type: string + description: |- + Name of the application to install. + + If name is not provided defaults to the marketplace listing's name. + createBillingProfile: + type: boolean + description: |- + If true, a billing profile will be created for the app. + The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + default: true + description: Marketplace install request payload. + MarketplaceInstallResponse: + type: object + required: + - app + - defaultForCapabilityTypes + properties: + app: + $ref: '#/components/schemas/App' + defaultForCapabilityTypes: + type: array + items: + $ref: '#/components/schemas/AppCapabilityType' + description: Default for capabilities + description: Marketplace install response. + MarketplaceListing: + type: object + required: + - type + - name + - description + - capabilities + - installMethods + properties: + type: + allOf: + - $ref: '#/components/schemas/AppType' + description: The app's type + name: + type: string + description: The app's name. + description: + type: string + description: The app's description. + capabilities: + type: array + items: + $ref: '#/components/schemas/AppCapability' + description: The app's capabilities. + installMethods: + type: array + items: + $ref: '#/components/schemas/InstallMethod' + description: |- + Install methods. + + List of methods to install the app. + description: |- + A marketplace listing. + Represent an available app in the app marketplace that can be installed to the organization. + + Marketplace apps only exist in config so they don't extend the Resource model. + example: + type: stripe + name: Stripe + description: Stripe integration allows you to collect payments with Stripe. + capabilities: + - type: calculateTax + key: stripe_calculate_tax + name: Calculate Tax + description: Stripe Tax calculates tax portion of the invoices. + - type: invoiceCustomers + key: stripe_invoice_customers + name: Invoice Customers + description: Stripe invoices customers with due amount. + - type: collectPayments + key: stripe_collect_payments + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + installMethods: + - with_oauth2 + - with_api_key + MarketplaceListingPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/MarketplaceListing' + description: The items in the current page. + description: Paginated response + MeasureUsageFrom: + oneOf: + - $ref: '#/components/schemas/MeasureUsageFromPreset' + - $ref: '#/components/schemas/MeasureUsageFromTime' + description: Measure usage from + MeasureUsageFromPreset: + type: string + enum: + - CURRENT_PERIOD_START + - NOW + description: Start of measurement options + x-enum-varnames: + - CurrentPeriodStart + - Now + MeasureUsageFromTime: + type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + Metadata: + type: object + additionalProperties: + type: string + description: |- + Set of key-value pairs. + Metadata can be used to store additional information about a resource. + example: + externalId: 019142cc-a016-796a-8113-1a942fecd26d + x-go-type: map[string]string + Meter: + type: object + required: + - id + - createdAt + - updatedAt + - slug + - aggregation + - eventType + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: |- + Human-readable name for the resource. Between 1 and 256 characters. + Defaults to the slug if not specified. + title: Display name + slug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + A unique, human-readable identifier for the meter. + Must consist only alphanumeric and underscore characters. + example: tokens_total + aggregation: + allOf: + - $ref: '#/components/schemas/MeterAggregation' + description: The aggregation type to use for the meter. + example: SUM + eventType: + type: string + minLength: 1 + description: The event type to aggregate. + example: prompt + eventFrom: + type: string + format: date-time + description: |- + The date since the meter should include events. + Useful to skip old events. + If not specified, all historical events are included. + example: '2023-01-01T01:01:01.001Z' + valueProperty: + type: string + minLength: 1 + description: |- + JSONPath expression to extract the value from the ingested event's data property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + example: $.tokens + groupBy: + type: object + additionalProperties: + type: string + description: |- + Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + example: + type: $.type + annotations: + type: object + allOf: + - $ref: '#/components/schemas/Annotations' + nullable: true + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + description: A meter is a configuration that defines how to match and aggregate events. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + slug: tokens_total + name: Tokens Total + description: AI Token Usage + aggregation: SUM + eventType: prompt + valueProperty: $.tokens + groupBy: + model: $.model + type: $.type + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + MeterAggregation: + type: string + enum: + - SUM + - COUNT + - UNIQUE_COUNT + - AVG + - MIN + - MAX + - LATEST + description: The aggregation type to use for the meter. + x-enum-varnames: + - Sum + - Count + - UniqueCount + - Avg + - Min + - Max + - Latest + MeterCreate: + type: object + required: + - slug + - aggregation + - eventType + properties: + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + name: + type: string + minLength: 1 + maxLength: 256 + description: |- + Human-readable name for the resource. Between 1 and 256 characters. + Defaults to the slug if not specified. + title: Display name + slug: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + A unique, human-readable identifier for the meter. + Must consist only alphanumeric and underscore characters. + example: tokens_total + aggregation: + allOf: + - $ref: '#/components/schemas/MeterAggregation' + description: The aggregation type to use for the meter. + example: SUM + eventType: + type: string + minLength: 1 + description: The event type to aggregate. + example: prompt + eventFrom: + type: string + format: date-time + description: |- + The date since the meter should include events. + Useful to skip old events. + If not specified, all historical events are included. + example: '2023-01-01T01:01:01.001Z' + valueProperty: + type: string + minLength: 1 + description: |- + JSONPath expression to extract the value from the ingested event's data property. + + The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + + For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + example: $.tokens + groupBy: + type: object + additionalProperties: + type: string + description: |- + Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + example: + type: $.type + description: A meter create model. + example: + slug: tokens_total + name: Tokens Total + description: AI Token Usage + aggregation: SUM + eventType: prompt + valueProperty: $.tokens + groupBy: + model: $.model + type: $.type + MeterOrderBy: + type: string + enum: + - key + - name + - aggregation + - createdAt + - updatedAt + description: Order by options for meters. + MeterQueryRequest: + type: object + properties: + clientId: + type: string + minLength: 1 + maxLength: 36 + description: |- + Client ID + Useful to track progress of a query. + example: f74e58ed-94ce-4041-ae06-cf45420451a3 + from: + type: string + format: date-time + description: |- + Start date-time in RFC 3339 format. + + Inclusive. + example: '2023-01-01T01:01:01.001Z' + to: + type: string + format: date-time + description: |- + End date-time in RFC 3339 format. + + Inclusive. + example: '2023-01-01T01:01:01.001Z' + windowSize: + allOf: + - $ref: '#/components/schemas/WindowSize' + description: If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + example: DAY + windowTimeZone: + type: string + description: |- + The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + If not specified, the UTC timezone will be used. + example: UTC + default: UTC + subject: + type: array + items: + type: string + maxItems: 100 + description: Filtering by multiple subjects. + example: + - subject-1 + - subject-2 + filterCustomerId: + type: array + items: + type: string + maxItems: 100 + description: Filtering by multiple customers. + example: + - id-1 + - id-2 + filterGroupBy: + type: object + additionalProperties: + type: array + items: + type: string + description: Simple filter for group bys with exact match. + example: + model: + - gpt-4-turbo + - gpt-4o + type: + - prompt + advancedMeterGroupByFilters: + type: object + additionalProperties: + $ref: '#/components/schemas/FilterString' + description: |- + Optional advanced meter group by filters. + You can use this to filter for values of the meter groupBy fields. + example: + model: + $in: + - gpt-4 + - gpt-4o + type: + $eq: input + groupBy: + type: array + items: + type: string + maxItems: 100 + description: |- + If not specified a single aggregate will be returned for each subject and time window. + `subject` is a reserved group by value. + example: + - model + - type + description: A meter query request. + MeterQueryResult: + type: object + required: + - data + properties: + from: + type: string + format: date-time + description: |- + The start of the period the usage is queried from. + If not specified, the usage is queried from the beginning of time. + example: '2023-01-01T01:01:01.001Z' + to: + type: string + format: date-time + description: |- + The end of the period the usage is queried to. + If not specified, the usage is queried up to the current time. + example: '2023-01-01T01:01:01.001Z' + windowSize: + allOf: + - $ref: '#/components/schemas/WindowSize' + description: |- + The window size that the usage is aggregated. + If not specified, the usage is aggregated over the entire period. + data: + type: array + items: + $ref: '#/components/schemas/MeterQueryRow' + description: |- + The usage data. + If no data is available, an empty array is returned. + description: The result of a meter query. + example: + from: '2023-01-01T00:00:00Z' + to: '2023-01-02T00:00:00Z' + windowSize: DAY + data: + - value: 12 + windowStart: '2023-01-01T00:00:00Z' + windowEnd: '2023-01-02T00:00:00Z' + subject: customer-1 + groupBy: + model: gpt-4-turbo + type: prompt + MeterQueryRow: + type: object + required: + - value + - windowStart + - windowEnd + - subject + - groupBy + properties: + value: + type: number + format: double + description: The aggregated value. + windowStart: + type: string + format: date-time + description: The start of the window the value is aggregated over. + example: '2023-01-01T01:01:01.001Z' + windowEnd: + type: string + format: date-time + description: The end of the window the value is aggregated over. + example: '2023-01-01T01:01:01.001Z' + subject: + type: string + nullable: true + description: |- + The subject the value is aggregated over. + If not specified, the value is aggregated over all subjects. + customerId: + type: string + description: The customer ID the value is aggregated over. + groupBy: + type: object + additionalProperties: + type: string + nullable: true + description: The group by values the value is aggregated over. + description: A row in the result of a meter query. + example: + value: 12 + windowStart: '2023-01-01T00:00:00Z' + windowEnd: '2023-01-02T00:00:00Z' + subject: customer-1 + groupBy: + model: gpt-4-turbo + type: prompt + MeterUpdate: + type: object + properties: + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + name: + type: string + minLength: 1 + maxLength: 256 + description: |- + Human-readable name for the resource. Between 1 and 256 characters. + Defaults to the slug if not specified. + title: Display name + groupBy: + type: object + additionalProperties: + type: string + description: |- + Named JSONPath expressions to extract the group by values from the event data. + + Keys must be unique and consist only alphanumeric and underscore characters. + example: + type: $.type + description: |- + A meter update model. + + Only the properties that can be updated are included. + For example, the slug and aggregation cannot be updated. + example: + name: Tokens Total + description: AI Token Usage + groupBy: + model: $.model + type: $.type + NotFoundProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + NotImplementedProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server does not support the functionality required to fulfill the request. + NotificationChannel: + type: object + allOf: + - $ref: '#/components/schemas/NotificationChannelWebhook' + description: Notification channel. + NotificationChannelCreateRequest: + type: object + allOf: + - $ref: '#/components/schemas/NotificationChannelWebhookCreateRequest' + description: Union type for requests creating new notification channel with certain type. + NotificationChannelMeta: + type: object + required: + - id + - type + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification channel. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Channel Unique Identifier + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/NotificationChannelType' + description: Notification channel type. + title: Channel Type + description: Metadata only fields of a notification channel. + NotificationChannelOrderBy: + type: string + enum: + - id + - type + - createdAt + - updatedAt + description: Order by options for notification channels. + NotificationChannelPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/NotificationChannel' + description: The items in the current page. + description: Paginated response + NotificationChannelType: + type: string + enum: + - WEBHOOK + description: Type of the notification channel. + x-enum-varnames: + - Webhook + NotificationChannelWebhook: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - url + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification channel. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Channel Unique Identifier + readOnly: true + type: + type: string + enum: + - WEBHOOK + description: Notification channel type. + title: Channel Type + name: + type: string + minLength: 1 + maxLength: 256 + description: User friendly name of the channel. + title: Channel Name + example: customer-webhook + disabled: + type: boolean + description: Whether the channel is disabled or not. + title: Channel Disabled + example: true + default: false + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + url: + type: string + description: Webhook URL where the notification is sent. + title: Webhook URL + example: https://example.com/webhook + customHeaders: + type: object + additionalProperties: + type: string + description: Custom HTTP headers sent as part of the webhook request. + title: Custom HTTP Headers + signingSecret: + type: string + pattern: ^(whsec_)?[a-zA-Z0-9+/=]{32,100}$ + description: |- + Signing secret used for webhook request validation on the receiving end. + + Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + title: Signing Secret + example: whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8 + description: Notification channel with webhook type. + NotificationChannelWebhookCreateRequest: + type: object + required: + - type + - name + - url + properties: + type: + type: string + enum: + - WEBHOOK + description: Notification channel type. + title: Channel Type + name: + type: string + minLength: 1 + maxLength: 256 + description: User friendly name of the channel. + title: Channel Name + example: customer-webhook + disabled: + type: boolean + description: Whether the channel is disabled or not. + title: Channel Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + url: + type: string + description: Webhook URL where the notification is sent. + title: Webhook URL + example: https://example.com/webhook + customHeaders: + type: object + additionalProperties: + type: string + description: Custom HTTP headers sent as part of the webhook request. + title: Custom HTTP Headers + signingSecret: + type: string + pattern: ^(whsec_)?[a-zA-Z0-9+/=]{32,100}$ + description: |- + Signing secret used for webhook request validation on the receiving end. + + Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + title: Signing Secret + example: whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8 + description: Request with input parameters for creating new notification channel with webhook type. + NotificationEvent: + type: object + required: + - id + - type + - createdAt + - rule + - deliveryStatus + - payload + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier of the notification event. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Event Identifier + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/NotificationEventType' + description: Type of the notification event. + title: Event Type + readOnly: true + createdAt: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + rule: + allOf: + - $ref: '#/components/schemas/NotificationRule' + description: The nnotification rule which generated this event. + readOnly: true + deliveryStatus: + type: array + items: + $ref: '#/components/schemas/NotificationEventDeliveryStatus' + description: The delivery status of the notification event. + title: Delivery Status + readOnly: true + payload: + allOf: + - $ref: '#/components/schemas/NotificationEventPayload' + description: Timestamp when the notification event was created in RFC 3339 format. + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + description: Type of the notification event. + NotificationEventBalanceThresholdPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - entitlements.balance.threshold + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/NotificationEventBalanceThresholdPayloadData' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `entitlements.balance.threshold` type. + NotificationEventBalanceThresholdPayloadData: + type: object + required: + - entitlement + - feature + - subject + - value + - threshold + properties: + entitlement: + allOf: + - $ref: '#/components/schemas/EntitlementMetered' + title: Entitlement + readOnly: true + feature: + allOf: + - $ref: '#/components/schemas/Feature' + title: Feature + readOnly: true + subject: + allOf: + - $ref: '#/components/schemas/Subject' + title: Subject + readOnly: true + value: + allOf: + - $ref: '#/components/schemas/EntitlementValue' + title: Entitlement Value + readOnly: true + customer: + allOf: + - $ref: '#/components/schemas/Customer' + title: Customer + readOnly: true + threshold: + allOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThresholdValue' + title: Threshold + readOnly: true + description: Data of the payload for notification event with `entitlements.balance.threshold` type. + NotificationEventDeliveryAttempt: + type: object + required: + - state + - response + - timestamp + properties: + state: + allOf: + - $ref: '#/components/schemas/NotificationEventDeliveryStatusState' + description: State of teh delivery attempt. + title: State of teh delivery attempt + example: SUCCESS + readOnly: true + response: + allOf: + - $ref: '#/components/schemas/EventDeliveryAttemptResponse' + description: Response returned by the notification event recipient. + title: Response returned by the notification event recipient + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp of the delivery attempt. + example: '2023-01-01T01:01:01.001Z' + title: Timestamp of the delivery attempt + readOnly: true + description: The delivery attempt of the notification event. + NotificationEventDeliveryStatus: + type: object + required: + - state + - reason + - updatedAt + - channel + - attempts + properties: + state: + allOf: + - $ref: '#/components/schemas/NotificationEventDeliveryStatusState' + description: Delivery state of the notification event to the channel. + example: SUCCESS + readOnly: true + reason: + type: string + description: The reason of the last deliverry state update. + title: State Reason + example: Failed to dispatch event due to provider error. + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the status was last updated in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + channel: + allOf: + - $ref: '#/components/schemas/NotificationChannelMeta' + description: Notification channel the delivery status associated with. + title: Notification Channel + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + nextAttempt: + type: string + format: date-time + description: Timestamp of the next delivery attempt. If null it means there will be no more delivery attempts. + example: '2023-01-01T01:01:01.001Z' + title: Timestamp of the next delivery attempt + readOnly: true + attempts: + type: array + items: + $ref: '#/components/schemas/NotificationEventDeliveryAttempt' + description: List of delivery attempts. + title: Delivery Attempts + readOnly: true + description: The delivery status of the notification event. + NotificationEventDeliveryStatusState: + type: string + enum: + - SUCCESS + - FAILED + - SENDING + - PENDING + - RESENDING + description: The delivery state of the notification event to the channel. + title: Delivery State + x-enum-varnames: + - Success + - Failed + - Sending + - Pending + - Resending + NotificationEventEntitlementValuePayloadBase: + type: object + required: + - entitlement + - feature + - subject + - value + properties: + entitlement: + allOf: + - $ref: '#/components/schemas/EntitlementMetered' + title: Entitlement + readOnly: true + feature: + allOf: + - $ref: '#/components/schemas/Feature' + title: Feature + readOnly: true + subject: + allOf: + - $ref: '#/components/schemas/Subject' + title: Subject + readOnly: true + value: + allOf: + - $ref: '#/components/schemas/EntitlementValue' + title: Entitlement Value + readOnly: true + customer: + allOf: + - $ref: '#/components/schemas/Customer' + title: Customer + readOnly: true + description: Base data for any payload with entitlement entitlement value. + NotificationEventInvoiceCreatedPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - invoice.created + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/Invoice' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `invoice.created` type. + NotificationEventInvoiceUpdatedPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - invoice.updated + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/Invoice' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `invoice.updated` type. + NotificationEventOrderBy: + type: string + enum: + - id + - createdAt + description: Order by options for notification channels. + NotificationEventPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/NotificationEvent' + description: The items in the current page. + description: Paginated response + NotificationEventPayload: + type: object + oneOf: + - $ref: '#/components/schemas/NotificationEventResetPayload' + - $ref: '#/components/schemas/NotificationEventBalanceThresholdPayload' + - $ref: '#/components/schemas/NotificationEventInvoiceCreatedPayload' + - $ref: '#/components/schemas/NotificationEventInvoiceUpdatedPayload' + discriminator: + propertyName: type + mapping: + entitlements.reset: '#/components/schemas/NotificationEventResetPayload' + entitlements.balance.threshold: '#/components/schemas/NotificationEventBalanceThresholdPayload' + invoice.created: '#/components/schemas/NotificationEventInvoiceCreatedPayload' + invoice.updated: '#/components/schemas/NotificationEventInvoiceUpdatedPayload' + description: The delivery status of the notification event. + NotificationEventResendRequest: + type: object + properties: + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: Notification channels to which the event should be re-sent. + title: Channels + description: A notification event that will be re-sent. + NotificationEventResetPayload: + type: object + required: + - id + - type + - timestamp + - data + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the notification event the payload belongs to. + example: 01J2KNP1YTXQRXHTDJ4KPR7PZ0 + title: Notification Event Identifier + readOnly: true + type: + type: string + enum: + - entitlements.reset + description: Type of the notification event. + title: Notification Event Type + readOnly: true + timestamp: + type: string + format: date-time + description: Timestamp when the notification event was created in RFC 3339 format. + example: '2023-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + data: + allOf: + - $ref: '#/components/schemas/NotificationEventEntitlementValuePayloadBase' + description: The data of the payload. + title: Payload Data + readOnly: true + description: Payload for notification event with `entitlements.reset` type. + NotificationEventType: + type: string + enum: + - entitlements.balance.threshold + - entitlements.reset + - invoice.created + - invoice.updated + description: Type of the notification event. + NotificationRule: + type: object + oneOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThreshold' + - $ref: '#/components/schemas/NotificationRuleEntitlementReset' + - $ref: '#/components/schemas/NotificationRuleInvoiceCreated' + - $ref: '#/components/schemas/NotificationRuleInvoiceUpdated' + discriminator: + propertyName: type + mapping: + entitlements.balance.threshold: '#/components/schemas/NotificationRuleBalanceThreshold' + entitlements.reset: '#/components/schemas/NotificationRuleEntitlementReset' + invoice.created: '#/components/schemas/NotificationRuleInvoiceCreated' + invoice.updated: '#/components/schemas/NotificationRuleInvoiceUpdated' + description: Notification Rule. + NotificationRuleBalanceThreshold: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + - thresholds + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - entitlements.balance.threshold + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + thresholds: + type: array + items: + $ref: '#/components/schemas/NotificationRuleBalanceThresholdValue' + minItems: 1 + maxItems: 10 + description: List of thresholds the rule suppose to be triggered. + title: Entitlement Balance Thresholds + features: + type: array + items: + $ref: '#/components/schemas/FeatureMeta' + minItems: 1 + description: Optional field containing list of features the rule applies to. + title: Features + description: Notification rule with entitlements.balance.threshold type. + NotificationRuleBalanceThresholdCreateRequest: + type: object + required: + - type + - name + - thresholds + - channels + properties: + type: + type: string + enum: + - entitlements.balance.threshold + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + thresholds: + type: array + items: + $ref: '#/components/schemas/NotificationRuleBalanceThresholdValue' + minItems: 1 + maxItems: 10 + description: List of thresholds the rule suppose to be triggered. + title: Entitlement Balance Thresholds + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + features: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ULID (Universally Unique Lexicographically Sortable Identifier). + A key is a unique string that is used to identify a resource. + + TODO: this is a temporary solution to support both ULID and Key in the same spec for codegen. + minItems: 1 + description: Optional field for defining the scope of notification by feature. It may contain features by id or key. + title: Features + description: Request with input parameters for creating new notification rule with entitlements.balance.threshold type. + NotificationRuleBalanceThresholdValue: + type: object + required: + - value + - type + properties: + value: + type: number + format: double + description: Value of the threshold. + title: Threshold Value + example: 100 + type: + allOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThresholdValueType' + description: Type of the threshold. + example: usage_value + description: Threshold value with multiple supported types. + NotificationRuleBalanceThresholdValueType: + type: string + enum: + - PERCENT + - NUMBER + - balance_value + - usage_percentage + - usage_value + description: |- + Type of the rule in the balance threshold specification: + * `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period + * `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period + * `usage_value`: threshold defined by the usage value in the current usage period + * `NUMBER` (**deprecated**): see `usage_value` + * `PERCENT` (**deprecated**): see `usage_percentage` + title: Notification balance threshold type + x-enum-varnames: + - Percent + - Number + - BalanceValue + - UsagePercentage + - UsageValue + NotificationRuleCreateRequest: + type: object + oneOf: + - $ref: '#/components/schemas/NotificationRuleBalanceThresholdCreateRequest' + - $ref: '#/components/schemas/NotificationRuleEntitlementResetCreateRequest' + - $ref: '#/components/schemas/NotificationRuleInvoiceCreatedCreateRequest' + - $ref: '#/components/schemas/NotificationRuleInvoiceUpdatedCreateRequest' + discriminator: + propertyName: type + mapping: + entitlements.balance.threshold: '#/components/schemas/NotificationRuleBalanceThresholdCreateRequest' + entitlements.reset: '#/components/schemas/NotificationRuleEntitlementResetCreateRequest' + invoice.created: '#/components/schemas/NotificationRuleInvoiceCreatedCreateRequest' + invoice.updated: '#/components/schemas/NotificationRuleInvoiceUpdatedCreateRequest' + description: Union type for requests creating new notification rule with certain type. + NotificationRuleEntitlementReset: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - entitlements.reset + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + features: + type: array + items: + $ref: '#/components/schemas/FeatureMeta' + minItems: 1 + description: Optional field containing list of features the rule applies to. + title: Features + description: Notification rule with entitlements.reset type. + NotificationRuleEntitlementResetCreateRequest: + type: object + required: + - type + - name + - channels + properties: + type: + type: string + enum: + - entitlements.reset + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + features: + type: array + items: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$|^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + ULID (Universally Unique Lexicographically Sortable Identifier). + A key is a unique string that is used to identify a resource. + + TODO: this is a temporary solution to support both ULID and Key in the same spec for codegen. + minItems: 1 + description: Optional field for defining the scope of notification by feature. It may contain features by id or key. + title: Features + description: Request with input parameters for creating new notification rule with entitlements.reset type. + NotificationRuleInvoiceCreated: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - invoice.created + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + description: Notification rule with invoice.created type. + NotificationRuleInvoiceCreatedCreateRequest: + type: object + required: + - type + - name + - channels + properties: + type: + type: string + enum: + - invoice.created + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + description: Request with input parameters for creating new notification rule with invoice.created type. + NotificationRuleInvoiceUpdated: + type: object + required: + - createdAt + - updatedAt + - id + - type + - name + - channels + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + type: string + enum: + - invoice.updated + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + channels: + type: array + items: + $ref: '#/components/schemas/NotificationChannelMeta' + description: List of notification channels the rule applies to. + title: Channels assigned to Rule + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + description: Notification rule with invoice.updated type. + NotificationRuleInvoiceUpdatedCreateRequest: + type: object + required: + - type + - name + - channels + properties: + type: + type: string + enum: + - invoice.updated + description: Notification rule type. + title: Rule Type + name: + type: string + minLength: 1 + maxLength: 256 + description: The user friendly name of the notification rule. + title: Rule Name + example: Balance threshold reached + disabled: + type: boolean + description: Whether the rule is disabled or not. + title: Rule Disabled + example: true + default: false + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + channels: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + minItems: 1 + description: List of notification channels the rule is applied to. + title: Channels + description: Request with input parameters for creating new notification rule with invoice.updated type. + NotificationRuleMeta: + type: object + required: + - id + - type + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: Identifies the notification rule. + example: 01ARZ3NDEKTSV4RRFFQ69G5FAV + title: Rule Unique Identifier + readOnly: true + type: + allOf: + - $ref: '#/components/schemas/NotificationEventType' + description: Notification rule type. + title: Rule Type + readOnly: true + description: Metadata only fields of a notification channel. + NotificationRuleOrderBy: + type: string + enum: + - id + - type + - createdAt + - updatedAt + description: Order by options for notification channels. + NotificationRulePaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/NotificationRule' + description: The items in the current page. + description: Paginated response + Numeric: + type: string + pattern: ^\-?[0-9]+(\.[0-9]+)?$ + description: Numeric represents an arbitrary precision number. + OAuth2AuthorizationCodeGrantErrorType: + type: string + enum: + - invalid_request + - unauthorized_client + - access_denied + - unsupported_response_type + - invalid_scope + - server_error + - temporarily_unavailable + description: OAuth2 authorization code grant error types. + PackagePrice: + type: object + required: + - type + - amount + - quantityPerPackage + properties: + type: + type: string + enum: + - package + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The price of one package. + title: Amount + quantityPerPackage: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity per package. + title: Quantity per package + description: |- + Package price. + + The item is sold in packages. Each package contains quantityPerPackage items, the price of the + package is set in amount. + + The total price of the usage will be enough packages that can accomodate all the usage. + + Examples (given a package size of 20, and an amount of $10): + - if the quantity is 98, the price will be 5*$10=$50. + - if the quantity is zero, the price will be 0*$10=$0, as even the first package is not purchased. + - if the quantity is 20, the price will be 1*$10=$10, as the usage fits into the first package. + - if the quantity is 20.1, the price will be 2*$10=$20, as the additional 0.1 usage (compared to the + previous example) requires a new package. + PackagePriceWithCommitments: + type: object + required: + - type + - amount + - quantityPerPackage + properties: + type: + type: string + enum: + - package + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The price of one package. + title: Amount + quantityPerPackage: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The quantity per package. + title: Quantity per package + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Package price with spend commitments. + PaymentDueDate: + type: object + required: + - dueAt + - amount + properties: + dueAt: + type: string + format: date-time + description: When the payment is due. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + notes: + type: string + description: Other details to take into account for the due date. + readOnly: true + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: How much needs to be paid by the date. + readOnly: true + percent: + allOf: + - $ref: '#/components/schemas/Percentage' + description: Percentage of the total that should be paid by the date. + readOnly: true + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: If different from the parent document's base currency. + readOnly: true + description: PaymentDueDate contains an amount that should be paid by the given date. + PaymentTermDueDate: + type: object + required: + - type + - dueAt + properties: + type: + type: string + enum: + - due_date + description: Type of terms to be applied. + detail: + type: string + description: Text detail of the chosen payment terms. + readOnly: true + notes: + type: string + description: Description of the conditions for payment. + readOnly: true + dueAt: + type: array + items: + $ref: '#/components/schemas/PaymentDueDate' + minItems: 1 + description: When the payment is due. + readOnly: true + description: PaymentTermDueDate defines the terms for payment on a specific date. + PaymentTermInstant: + type: object + required: + - type + properties: + type: + type: string + enum: + - instant + description: Type of terms to be applied. + detail: + type: string + description: Text detail of the chosen payment terms. + readOnly: true + notes: + type: string + description: Description of the conditions for payment. + readOnly: true + description: PaymentTermInstant defines the terms for payment on receipt of invoice. + PaymentTermType: + type: string + enum: + - due_date + - instant + description: PaymentTermType defines the type of terms to be applied. + PaymentTerms: + anyOf: + - $ref: '#/components/schemas/PaymentTermInstant' + - $ref: '#/components/schemas/PaymentTermDueDate' + description: PaymentTerms defines the terms for payment. + Percentage: + type: number + format: double + description: |- + Numeric representation of a percentage + + 50% is represented as 50 + example: 50 + x-go-package: github.com/openmeterio/openmeter/pkg/models + x-go-type: models.Percentage + Period: + type: object + required: + - from + - to + properties: + from: + type: string + format: date-time + description: Period start time. + example: '2023-01-01T01:01:01.001Z' + to: + type: string + format: date-time + description: Period end time. + example: '2023-02-01T01:01:01.001Z' + description: A period with a start and end time. + Plan: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - version + - currency + - billingCadence + - status + - phases + - validationErrors + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + version: + type: integer + minimum: 1 + description: Version of the plan. Incremented when the plan is updated. + title: Version + default: 1 + readOnly: true + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the plan. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + effectiveFrom: + type: string + format: date-time + description: The date and time when the plan becomes effective. When not specified, the plan is a draft. + example: '2023-01-01T01:01:01.001Z' + title: Effective start date + readOnly: true + effectiveTo: + type: string + format: date-time + description: The date and time when the plan is no longer effective. When not specified, the plan is effective indefinitely. + example: '2023-01-01T01:01:01.001Z' + title: Effective end date + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/PlanStatus' + description: |- + The status of the plan. + Computed based on the effective start and end dates: + - draft = no effectiveFrom + - active = effectiveFrom <= now < effectiveTo + - archived / inactive = effectiveTo <= now + - scheduled = now < effectiveFrom < effectiveTo + title: Status + readOnly: true + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + nullable: true + description: List of validation errors. + title: Validation errors + readOnly: true + description: Plans provide a template for subscriptions. + PlanAddon: + type: object + required: + - createdAt + - updatedAt + - addon + - fromPlanPhase + - validationErrors + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the resource. + title: Metadata + addon: + allOf: + - $ref: '#/components/schemas/Addon' + description: Add-on object. + title: Addon + readOnly: true + fromPlanPhase: + type: string + description: The key of the plan phase from the add-on becomes available for purchase. + title: The plan phase from the add-on becomes purchasable + maxQuantity: + type: integer + description: |- + The maximum number of times the add-on can be purchased for the plan. + It is not applicable for add-ons with single instance type. + title: Max quantity of the add-on + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + nullable: true + description: List of validation errors. + title: Validation errors + readOnly: true + description: The PlanAddon describes the association between a plan and add-on. + PlanAddonCreate: + type: object + required: + - fromPlanPhase + - addonId + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the resource. + title: Metadata + fromPlanPhase: + type: string + description: The key of the plan phase from the add-on becomes available for purchase. + title: The plan phase from the add-on becomes purchasable + maxQuantity: + type: integer + description: |- + The maximum number of times the add-on can be purchased for the plan. + It is not applicable for add-ons with single instance type. + title: Max quantity of the add-on + addonId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The add-on unique identifier in ULID format. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: Add-on unique identifier + description: A plan add-on assignment create request. + PlanAddonOrderBy: + type: string + enum: + - id + - key + - version + - created_at + - updated_at + description: Order by options for plan add-on assignments. + PlanAddonPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/PlanAddon' + description: The items in the current page. + description: Paginated response + PlanAddonReplaceUpdate: + type: object + required: + - fromPlanPhase + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the resource. + title: Metadata + fromPlanPhase: + type: string + description: The key of the plan phase from the add-on becomes available for purchase. + title: The plan phase from the add-on becomes purchasable + maxQuantity: + type: integer + description: |- + The maximum number of times the add-on can be purchased for the plan. + It is not applicable for add-ons with single instance type. + title: Max quantity of the add-on + description: Resource update operation model. + PlanCreate: + type: object + required: + - name + - key + - currency + - billingCadence + - phases + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: The currency code of the plan. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + description: Resource create operation model. + PlanOrderBy: + type: string + enum: + - id + - key + - version + - created_at + - updated_at + description: Order by options for plans. + PlanPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Plan' + description: The items in the current page. + description: Paginated response + PlanPhase: + type: object + required: + - key + - name + - duration + - rateCards + properties: + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + duration: + type: string + format: duration + nullable: true + description: The duration of the phase. + title: Duration + example: P1Y + rateCards: + type: array + items: + $ref: '#/components/schemas/RateCard' + description: The rate cards of the plan. + title: Rate cards + description: The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + PlanReference: + type: object + required: + - id + - key + - version + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The plan ID. + example: 01G65Z755AFWAKHE12NY0CQ9FH + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The plan key. + version: + type: integer + description: The plan version. + description: References an exact plan. + PlanReferenceInput: + type: object + required: + - key + properties: + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The plan key. + version: + type: integer + description: The plan version. + description: References an exact plan defaulting to the current active version. + PlanReplaceUpdate: + type: object + required: + - name + - billingCadence + - phases + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + billingCadence: + type: string + format: duration + description: |- + The default billing cadence for subscriptions using this plan. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: Default pro-rating configuration for subscriptions using this plan. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the plan. + It determines how the billing system generates invoices and credits for the subscriptions using this plan. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + phases: + type: array + items: + $ref: '#/components/schemas/PlanPhase' + minItems: 1 + description: |- + The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + title: Plan phases + description: Resource update operation model. + PlanStatus: + type: string + enum: + - draft + - active + - archived + - scheduled + description: The status of a plan. + PlanSubscriptionChange: + type: object + required: + - timing + - plan + properties: + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + For changing a subscription, the accepted values depend on the subscription configuration. + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: What alignment settings the subscription should have. + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Arbitrary metadata associated with the subscription. + plan: + allOf: + - $ref: '#/components/schemas/PlanReferenceInput' + description: The plan reference to change to. + startingPhase: + type: string + minLength: 1 + description: |- + The key of the phase to start the subscription in. + If not provided, the subscription will start in the first phase of the plan. + name: + type: string + description: The name of the Subscription. If not provided the plan name is used. + description: + type: string + description: Description for the Subscription. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + example: '2023-01-01T01:01:01.001Z' + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: The settlement mode of the subscription. + description: Change subscription based on plan. + PlanSubscriptionCreate: + type: object + required: + - plan + properties: + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: What alignment settings the subscription should have. + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Arbitrary metadata associated with the subscription. + plan: + allOf: + - $ref: '#/components/schemas/PlanReferenceInput' + description: The plan reference to change to. + startingPhase: + type: string + minLength: 1 + description: |- + The key of the phase to start the subscription in. + If not provided, the subscription will start in the first phase of the plan. + name: + type: string + description: The name of the Subscription. If not provided the plan name is used. + description: + type: string + description: Description for the Subscription. + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: The settlement mode of the subscription. + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: |- + Timing configuration for the change, when the change should take effect. + The default is immediate. + default: immediate + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the customer. Provide either the key or ID. Has presedence over the key. + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerKey: + type: string + minLength: 1 + maxLength: 256 + description: The key of the customer. Provide either the key or ID. + billingAnchor: + type: string + format: date-time + description: The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + example: '2023-01-01T01:01:01.001Z' + description: Create subscription based on plan. + title: Create from plan + PortalToken: + type: object + required: + - subject + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + subject: + type: string + example: customer-1 + expiresAt: + type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + readOnly: true + expired: + type: boolean + readOnly: true + createdAt: + type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + readOnly: true + token: + type: string + description: The token is only returned at creation. + example: om_portal_IAnD3PpWW2A2Wr8m9jfzeHlGX8xmCXwG.y5q4S-AWqFu6qjfaFz0zQq4Ez28RsnyVwJffX5qxMvo + readOnly: true + allowedMeterSlugs: + type: array + items: + type: string + description: Optional, if defined only the specified meters will be allowed. + example: + - tokens_total + description: |- + A consumer portal token. + + Validator doesn't obey required for readOnly properties + See: https://github.com/stoplightio/spectral/issues/1274 + PreconditionFailedProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: One or more conditions given in the request header fields evaluated to false when tested on the server. + Price: + type: object + oneOf: + - $ref: '#/components/schemas/FlatPrice' + - $ref: '#/components/schemas/UnitPrice' + - $ref: '#/components/schemas/TieredPrice' + - $ref: '#/components/schemas/DynamicPrice' + - $ref: '#/components/schemas/PackagePrice' + discriminator: + propertyName: type + mapping: + flat: '#/components/schemas/FlatPrice' + unit: '#/components/schemas/UnitPrice' + tiered: '#/components/schemas/TieredPrice' + dynamic: '#/components/schemas/DynamicPrice' + package: '#/components/schemas/PackagePrice' + description: |- + Price. + One of: flat, unit, or tiered. + PricePaymentTerm: + type: string + enum: + - in_advance + - in_arrears + description: |- + The payment term of a flat price. + One of: in_advance or in_arrears. + PriceTier: + type: object + required: + - flatPrice + - unitPrice + properties: + upToAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: |- + Up to and including to this quantity will be contained in the tier. + If null, the tier is open-ended. + title: Up to quantity + flatPrice: + type: object + allOf: + - $ref: '#/components/schemas/FlatPrice' + nullable: true + description: The flat price component of the tier. + title: Flat price component + unitPrice: + type: object + allOf: + - $ref: '#/components/schemas/UnitPrice' + nullable: true + description: The unit price component of the tier. + title: Unit price component + description: |- + A price tier. + At least one price component is required in each tier. + PriceType: + type: string + enum: + - flat + - unit + - tiered + - dynamic + - package + description: The type of the price. + ProRatingConfig: + type: object + required: + - enabled + - mode + properties: + enabled: + type: boolean + description: Whether pro-rating is enabled for this plan. + title: Enable pro-rating + default: true + mode: + allOf: + - $ref: '#/components/schemas/ProRatingMode' + description: How to handle pro-rating for billing period changes. + title: Pro-rating mode + default: prorate_prices + description: Configuration for pro-rating behavior. + ProRatingMode: + type: string + enum: + - prorate_prices + description: Pro-rating mode options for handling billing period changes. + Progress: + type: object + required: + - success + - failed + - total + - updatedAt + properties: + success: + type: integer + format: uint64 + description: Success is the number of items that succeeded + failed: + type: integer + format: uint64 + description: Failed is the number of items that failed + total: + type: integer + format: uint64 + description: The total number of items to process + updatedAt: + type: string + format: date-time + description: The time the progress was last updated + example: '2023-01-01T01:01:01.001Z' + description: Progress describes a progress of a task. + RateCard: + type: object + oneOf: + - $ref: '#/components/schemas/RateCardFlatFee' + - $ref: '#/components/schemas/RateCardUsageBased' + discriminator: + propertyName: type + mapping: + flat_fee: '#/components/schemas/RateCardFlatFee' + usage_based: '#/components/schemas/RateCardUsageBased' + description: A rate card defines the pricing and entitlement of a feature or service. + RateCardBooleanEntitlement: + type: object + required: + - type + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - boolean + description: Entitlement template of a boolean entitlement. + RateCardEntitlement: + type: object + oneOf: + - $ref: '#/components/schemas/RateCardMeteredEntitlement' + - $ref: '#/components/schemas/RateCardStaticEntitlement' + - $ref: '#/components/schemas/RateCardBooleanEntitlement' + discriminator: + propertyName: type + mapping: + metered: '#/components/schemas/RateCardMeteredEntitlement' + static: '#/components/schemas/RateCardStaticEntitlement' + boolean: '#/components/schemas/RateCardBooleanEntitlement' + description: |- + Entitlement templates are used to define the entitlements of a plan. + Features are omitted from the entitlement template, as they are defined in the rate card. + RateCardFlatFee: + type: object + required: + - type + - key + - name + - billingCadence + - price + properties: + type: + type: string + enum: + - flat_fee + description: The type of the RateCard. + title: RateCard type + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the customer is entitled to use. + title: Feature key + entitlementTemplate: + allOf: + - $ref: '#/components/schemas/RateCardEntitlement' + description: |- + The entitlement of the rate card. + Only available when featureKey is set. + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + billingCadence: + type: string + format: duration + nullable: true + description: |- + The billing cadence of the rate card. + When null it means it is a one time fee. + title: Billing cadence + price: + type: object + allOf: + - $ref: '#/components/schemas/FlatPriceWithPaymentTerm' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + title: Price + example: + type: flat + amount: '100' + paymentTerm: in_arrears + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: |- + The discount of the rate card. For flat fee rate cards only percentage discounts are supported. + Only available when price is set. + title: Discounts + description: A flat fee rate card defines a one-time purchase or a recurring fee. + RateCardMeteredEntitlement: + type: object + required: + - type + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - metered + isSoftLimit: + type: boolean + description: If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + title: Soft limit + default: false + issueAfterReset: + type: number + format: double + minimum: 0 + description: |- + You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + title: Initial grant amount + issueAfterResetPriority: + type: integer + format: uint8 + minimum: 1 + maximum: 255 + description: Defines the grant priority for the default grant. + title: Issue grant after reset priority + default: 1 + preserveOverageAtReset: + type: boolean + description: If true, the overage is preserved at reset. If false, the usage is reset to 0. + title: Preserve overage at reset + default: false + usagePeriod: + type: string + format: duration + description: |- + The interval of the metered entitlement. + Defaults to the billing cadence of the rate card. + title: Usage Period + description: The entitlement template with a metered entitlement. + RateCardStaticEntitlement: + type: object + required: + - type + - config + properties: + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional metadata for the feature. + type: + type: string + enum: + - static + config: + type: string + format: json + description: The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + example: '{ "integrations": ["github"] }' + description: Entitlement template of a static entitlement. + RateCardType: + type: string + enum: + - flat_fee + - usage_based + description: The type of the rate card. + RateCardUsageBased: + type: object + required: + - type + - key + - name + - billingCadence + - price + properties: + type: + type: string + enum: + - usage_based + description: The type of the RateCard. + title: RateCard type + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature the customer is entitled to use. + title: Feature key + entitlementTemplate: + allOf: + - $ref: '#/components/schemas/RateCardEntitlement' + description: |- + The entitlement of the rate card. + Only available when featureKey is set. + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the rate card. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + billingCadence: + type: string + format: duration + description: The billing cadence of the rate card. + title: Billing cadence + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: |- + The discounts of the rate card. + + Flat fee rate cards only support percentage discounts. + title: Discounts + description: A usage-based rate card defines a price based on usage. + RateCardUsageBasedPrice: + type: object + oneOf: + - $ref: '#/components/schemas/FlatPriceWithPaymentTerm' + - $ref: '#/components/schemas/UnitPriceWithCommitments' + - $ref: '#/components/schemas/TieredPriceWithCommitments' + - $ref: '#/components/schemas/DynamicPriceWithCommitments' + - $ref: '#/components/schemas/PackagePriceWithCommitments' + discriminator: + propertyName: type + mapping: + flat: '#/components/schemas/FlatPriceWithPaymentTerm' + unit: '#/components/schemas/UnitPriceWithCommitments' + tiered: '#/components/schemas/TieredPriceWithCommitments' + dynamic: '#/components/schemas/DynamicPriceWithCommitments' + package: '#/components/schemas/PackagePriceWithCommitments' + description: The price of the usage based rate card. + RecurringPeriod: + type: object + required: + - interval + - anchor + - intervalISO + properties: + interval: + allOf: + - $ref: '#/components/schemas/RecurringPeriodInterval' + description: The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + title: Interval + anchor: + type: string + format: date-time + description: A date-time anchor to base the recurring period on. + example: '2023-01-01T01:01:01.001Z' + title: Anchor time + intervalISO: + type: string + format: duration + description: The unit of time for the interval in ISO8601 format. + description: Recurring period with an interval and an anchor. + deprecated: true + example: + interval: DAY + intervalISO: P1D + anchor: '2023-01-01T01:01:01.001Z' + RecurringPeriodCreateInput: + type: object + required: + - interval + properties: + interval: + allOf: + - $ref: '#/components/schemas/RecurringPeriodInterval' + description: The unit of time for the interval. + title: Interval + anchor: + type: string + format: date-time + description: A date-time anchor to base the recurring period on. + example: '2023-01-01T01:01:01.001Z' + title: Anchor time + description: Recurring period with an interval and an anchor. + example: + interval: DAY + anchor: '2023-01-01T01:01:01.001Z' + RecurringPeriodInterval: + anyOf: + - type: string + pattern: ^P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$ + - $ref: '#/components/schemas/RecurringPeriodIntervalEnum' + description: Period duration for the recurrence + RecurringPeriodIntervalEnum: + type: string + enum: + - DAY + - WEEK + - MONTH + - YEAR + description: |- + The unit of time for the interval. + One of: `day`, `week`, `month`, or `year`. + RecurringPeriodV2: + type: object + required: + - interval + - anchor + properties: + interval: + allOf: + - $ref: '#/components/schemas/RecurringPeriodInterval' + description: The unit of time for the interval. Heuristically maps ISO duraitons to enum values or returns the ISO duration. + title: Interval + anchor: + type: string + format: date-time + description: A date-time anchor to base the recurring period on. + example: '2023-01-01T01:01:01.001Z' + title: Anchor time + description: Recurring period with an interval and an anchor. + RemovePhaseShifting: + type: string + enum: + - next + - prev + description: The direction of the phase shift when a phase is removed. + ResetEntitlementUsageInput: + type: object + properties: + effectiveAt: + type: string + format: date-time + description: The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored. + example: '2023-01-01T01:01:01.001Z' + retainAnchor: + type: boolean + description: |- + Determines whether the usage period anchor is retained or reset to the effectiveAt time. + - If true, the usage period anchor is retained. + - If false, the usage period anchor is reset to the effectiveAt time. + preserveOverage: + type: boolean + description: |- + Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior. + - If true, the overage is preserved. + - If false, the overage is forgiven. + description: Reset parameters + SandboxApp: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - sandbox + description: The app's type is Sandbox. + description: |- + Sandbox app can be used for testing OpenMeter features. + + The app is not creating anything in external systems, thus it is safe to use for + verifying OpenMeter features. + SandboxAppReplaceUpdate: + type: object + required: + - name + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + type: + type: string + enum: + - sandbox + description: The app's type is Sandbox. + description: Resource update operation model. + SandboxCustomerAppData: + type: object + required: + - type + properties: + app: + allOf: + - $ref: '#/components/schemas/SandboxApp' + description: The installed sandbox app this data belongs to. + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - sandbox + description: The app name. + title: App Type + description: Sandbox Customer App Data. + ServiceUnavailableProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + SortOrder: + type: string + enum: + - ASC + - DESC + description: The order direction. + SpendCommitments: + type: object + properties: + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: |- + Spending commitments. + The customer is committed to spend at least the minimum amount and at most the maximum amount. + StripeAPIKeyInput: + type: object + required: + - secretAPIKey + properties: + secretAPIKey: + type: string + description: |- + The Stripe API key input. + Used to authenticate with the Stripe API. + StripeApp: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + - stripeAccountId + - livemode + - maskedAPIKey + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - stripe + description: The app's type is Stripe. + stripeAccountId: + type: string + description: The Stripe account ID. + readOnly: true + livemode: + type: boolean + description: Livemode, true if the app is in production mode. + readOnly: true + maskedAPIKey: + type: string + description: |- + The masked API key. + Only shows the first 8 and last 3 characters. + readOnly: true + description: A installed Stripe app object. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + type: stripe + name: Stripe + status: ready + listing: + type: stripe + name: Stripe + description: Stripe integration allows you to collect payments with Stripe. + capabilities: + - type: calculateTax + key: stripe_calculate_tax + name: Calculate Tax + description: Stripe Tax calculates tax portion of the invoices. + - type: invoiceCustomers + key: stripe_invoice_customers + name: Invoice Customers + description: Stripe invoices customers with due amount. + - type: collectPayments + key: stripe_collect_payments + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + installMethods: + - with_oauth2 + - with_api_key + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + stripeAccountId: acct_123456789 + livemode: true + maskedAPIKey: sk_live_************abc + StripeAppReadOrCreateOrUpdateOrDeleteOrQuery: + type: object + required: + - id + - name + - createdAt + - updatedAt + - listing + - status + - type + - stripeAccountId + - livemode + - maskedAPIKey + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + listing: + allOf: + - $ref: '#/components/schemas/MarketplaceListing' + description: The marketplace listing that this installed app is based on. + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/AppStatus' + description: Status of the app connection. + readOnly: true + type: + type: string + enum: + - stripe + description: The app's type is Stripe. + stripeAccountId: + type: string + description: The Stripe account ID. + readOnly: true + livemode: + type: boolean + description: Livemode, true if the app is in production mode. + readOnly: true + maskedAPIKey: + type: string + description: |- + The masked API key. + Only shows the first 8 and last 3 characters. + readOnly: true + secretAPIKey: + type: string + format: password + description: The Stripe API key. + description: A installed Stripe app object. + example: + id: 01G65Z755AFWAKHE12NY0CQ9FH + type: stripe + name: Stripe + status: ready + listing: + type: stripe + name: Stripe + description: Stripe integration allows you to collect payments with Stripe. + capabilities: + - type: calculateTax + key: stripe_calculate_tax + name: Calculate Tax + description: Stripe Tax calculates tax portion of the invoices. + - type: invoiceCustomers + key: stripe_invoice_customers + name: Invoice Customers + description: Stripe invoices customers with due amount. + - type: collectPayments + key: stripe_collect_payments + name: Collect Payments + description: Stripe payments collects outstanding revenue with Stripe customer's default payment method. + installMethods: + - with_oauth2 + - with_api_key + createdAt: '2024-01-01T01:01:01.001Z' + updatedAt: '2024-01-01T01:01:01.001Z' + stripeAccountId: acct_123456789 + livemode: true + maskedAPIKey: sk_live_************abc + StripeAppReplaceUpdate: + type: object + required: + - name + - type + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + type: + type: string + enum: + - stripe + description: The app's type is Stripe. + secretAPIKey: + type: string + format: password + description: The Stripe API key. + description: Resource update operation model. + StripeCheckoutSessionMode: + type: string + enum: + - setup + description: Stripe CheckoutSession.mode + StripeCustomerAppData: + type: object + required: + - type + - stripeCustomerId + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - stripe + description: The app name. + title: App Type + stripeCustomerId: + type: string + description: The Stripe customer ID. + stripeDefaultPaymentMethodId: + type: string + description: The Stripe default payment method ID. + app: + allOf: + - $ref: '#/components/schemas/StripeApp' + description: The installed stripe app this data belongs to. + readOnly: true + description: Stripe Customer App Data. + example: + type: stripe + stripeCustomerId: cus_xxxxxxxxxxxxxx + StripeCustomerAppDataBase: + type: object + required: + - stripeCustomerId + properties: + stripeCustomerId: + type: string + description: The Stripe customer ID. + stripeDefaultPaymentMethodId: + type: string + description: The Stripe default payment method ID. + description: Stripe Customer App Data Base. + StripeCustomerAppDataCreateOrUpdateItem: + type: object + required: + - type + - stripeCustomerId + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + The app ID. + If not provided, it will use the global default for the app type. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: App ID + type: + type: string + enum: + - stripe + description: The app name. + title: App Type + stripeCustomerId: + type: string + description: The Stripe customer ID. + stripeDefaultPaymentMethodId: + type: string + description: The Stripe default payment method ID. + description: Stripe Customer App Data. + example: + type: stripe + stripeCustomerId: cus_xxxxxxxxxxxxxx + StripeCustomerPortalSession: + type: object + required: + - id + - stripeCustomerId + - configurationId + - livemode + - createdAt + - returnUrl + - locale + - url + properties: + id: + type: string + description: |- + The ID of the customer portal session. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + stripeCustomerId: + type: string + description: The ID of the stripe customer. + configurationId: + type: string + description: |- + Configuration used to customize the customer portal. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + livemode: + type: boolean + description: |- + Livemode. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + createdAt: + type: string + format: date-time + description: |- + Created at. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + example: '2023-01-01T01:01:01.001Z' + returnUrl: + type: string + description: |- + Return URL. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + locale: + type: string + description: |- + Status. + /** + The IETF language tag of the locale customer portal is displayed in. + + See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + url: + type: string + description: |- + /** + The ID of the customer.The URL to redirect the customer to after they have completed + their requested actions. + description: |- + Stripe customer portal session. + + See: https://docs.stripe.com/api/customer_portal/sessions/object + StripeTaxConfig: + type: object + required: + - code + properties: + code: + type: string + pattern: ^txcd_\d{8}$ + description: |- + Product tax code. + + See: https://docs.stripe.com/tax/tax-codes + title: Tax code + example: txcd_10000000 + description: The tax config for Stripe. + StripeWebhookEvent: + type: object + required: + - id + - type + - livemode + - created + - data + properties: + id: + type: string + description: The event ID. + type: + type: string + description: The event type. + livemode: + type: boolean + description: Live mode. + created: + type: integer + format: int32 + description: The event created timestamp. + data: + type: object + properties: + object: {} + required: + - object + description: The event data. + description: Stripe webhook event. + StripeWebhookResponse: + type: object + required: + - namespaceId + - appId + properties: + namespaceId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + appId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + message: + type: string + description: Stripe webhook response. + Subject: + type: object + required: + - createdAt + - updatedAt + - id + - key + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the subject. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + key: + type: string + description: |- + A unique, human-readable identifier for the subject. + This is typically a database ID or a customer key. + example: customer-db-id-123 + displayName: + type: string + nullable: true + description: A human-readable display name for the subject. + example: Customer Name + metadata: + type: object + additionalProperties: {} + nullable: true + description: Metadata for the subject. + example: + hubspotId: '123456' + currentPeriodStart: + type: string + format: date-time + description: The start of the current period for the subject. + example: '2023-01-01T00:00:00Z' + deprecated: true + currentPeriodEnd: + type: string + format: date-time + description: The end of the current period for the subject. + example: '2023-02-01T00:00:00Z' + deprecated: true + stripeCustomerId: + type: string + nullable: true + description: The Stripe customer ID for the subject. + deprecated: true + example: cus_JMOlctsKV8 + description: |- + A subject is a unique identifier for a usage attribution by its key. + Subjects only exist in the concept of metering. + Subjects are optional to create and work as an enrichment for the subject key like displayName, metadata, etc. + Subjects are useful when you are reporting usage events with your own database ID but want to enrich the subject with a human-readable name or metadata. + For most use cases, a subject is equivalent to a customer. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + deprecated: true + example: + createdAt: '2025-01-01T01:01:01.001Z' + updatedAt: '2025-02-01T01:01:01.001Z' + deletedAt: '2025-03-01T01:01:01.001Z' + id: 01G65Z755AFWAKHE12NY0CQ9FH + key: customer-id + displayName: Customer Name + metadata: + hubspotId: '123456' + stripeCustomerId: cus_JMOlctsKV8 + SubjectUpsert: + type: object + required: + - key + properties: + key: + type: string + description: |- + A unique, human-readable identifier for the subject. + This is typically a database ID or a customer key. + example: customer-db-id-123 + displayName: + type: string + nullable: true + description: A human-readable display name for the subject. + example: Customer Name + metadata: + type: object + additionalProperties: {} + nullable: true + description: Metadata for the subject. + example: + hubspotId: '123456' + currentPeriodStart: + type: string + format: date-time + description: The start of the current period for the subject. + example: '2023-01-01T00:00:00Z' + deprecated: true + currentPeriodEnd: + type: string + format: date-time + description: The end of the current period for the subject. + example: '2023-02-01T00:00:00Z' + deprecated: true + stripeCustomerId: + type: string + nullable: true + description: The Stripe customer ID for the subject. + deprecated: true + example: cus_JMOlctsKV8 + description: |- + A subject is a unique identifier for a user or entity. + + ⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. + deprecated: true + example: + key: customer-id + displayName: Customer Name + metadata: + hubspotId: '123456' + stripeCustomerId: cus_JMOlctsKV8 + Subscription: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - status + - customerId + - currency + - billingCadence + - billingAnchor + - settlementMode + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + alignment: + allOf: + - $ref: '#/components/schemas/Alignment' + description: Alignment configuration for the plan. + status: + allOf: + - $ref: '#/components/schemas/SubscriptionStatus' + description: The status of the subscription. + readOnly: true + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID of the subscription. + example: 01G65Z755AFWAKHE12NY0CQ9FH + plan: + allOf: + - $ref: '#/components/schemas/PlanReference' + description: The plan of the subscription. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + The currency code of the subscription. + Will be revised once we add multi currency support. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The billing cadence for the subscriptions. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + readOnly: true + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: The pro-rating configuration for the subscriptions. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + readOnly: true + billingAnchor: + type: string + format: date-time + description: The normalizedbilling anchor of the subscription. + example: '2023-01-01T01:01:01.001Z' + title: Billing anchor + readOnly: true + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the subscription. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + readOnly: true + description: Subscription is an exact subscription instance. + SubscriptionAddon: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - addon + - quantityAt + - quantity + - timeline + - subscriptionId + - rateCards + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + readOnly: true + addon: + type: object + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the add-on. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A semi-unique identifier for the resource. + title: Key + readOnly: true + version: + type: integer + minimum: 1 + description: The version of the Add-on which templates this instance. + title: Version + default: 1 + readOnly: true + instanceType: + allOf: + - $ref: '#/components/schemas/AddonInstanceType' + description: The instance type of the add-on. + title: InstanceType + readOnly: true + required: + - id + - key + - version + - instanceType + description: Partially populated add-on properties. + title: Addon + quantityAt: + type: string + format: date-time + description: For which point in time the quantity was resolved to. + example: '2025-01-05T00:00:00Z' + title: QuantityAt + readOnly: true + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on. Always 1 for single instance add-ons. + title: Quantity + example: 1 + timeline: + type: array + items: + $ref: '#/components/schemas/SubscriptionAddonTimelineSegment' + description: The timeline of the add-on. The returned periods are sorted and continuous. + title: Timeline + example: + - quantity: 1 + activeFrom: '2025-01-01T00:00:00Z' + activeTo: '2025-01-02T00:00:00Z' + - quantity: 0 + activeFrom: '2025-01-02T00:00:00Z' + activeTo: '2025-01-03T00:00:00Z' + - quantity: 1 + activeFrom: '2025-01-03T00:00:00Z' + readOnly: true + subscriptionId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the subscription. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: SubscriptionID + readOnly: true + rateCards: + type: array + items: + $ref: '#/components/schemas/SubscriptionAddonRateCard' + description: The rate cards of the add-on. + title: Rate cards + readOnly: true + description: A subscription add-on, represents concrete instances of an add-on for a given subscription. + SubscriptionAddonCreate: + type: object + required: + - name + - quantity + - timing + - addon + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on. Always 1 for single instance add-ons. + title: Quantity + example: 1 + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: The timing of the operation. After the create or update, a new entry will be created in the timeline. + title: Timing + addon: + type: object + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The ID of the add-on. + example: 01G65Z755AFWAKHE12NY0CQ9FH + required: + - id + description: The add-on to create. + title: Addon + description: A subscription add-on create body. + SubscriptionAddonRateCard: + type: object + required: + - rateCard + - affectedSubscriptionItemIds + properties: + rateCard: + allOf: + - $ref: '#/components/schemas/RateCard' + description: The rate card. + title: Rate card + affectedSubscriptionItemIds: + type: array + items: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + description: The IDs of the subscription items that this rate card belongs to. + title: Affected subscription item IDs + readOnly: true + description: A rate card for a subscription add-on. + SubscriptionAddonTimelineSegment: + type: object + required: + - activeFrom + - quantity + properties: + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on for the given period. + title: Quantity + example: 1 + readOnly: true + description: A subscription add-on event. + SubscriptionAddonUpdate: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + quantity: + type: integer + minimum: 0 + description: The quantity of the add-on. Always 1 for single instance add-ons. + title: Quantity + example: 1 + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: The timing of the operation. After the create or update, a new entry will be created in the timeline. + title: Timing + description: Resource create or update operation model. + SubscriptionAlignment: + type: object + properties: + billablesMustAlign: + type: boolean + description: |- + Whether all Billable items and RateCards must align. + Alignment means the Price's BillingCadence must align for both duration and anchor time. + deprecated: true + currentAlignedBillingPeriod: + allOf: + - $ref: '#/components/schemas/Period' + description: The current billing period. Only has value if the subscription is aligned and active. + description: Alignment details enriched with the current billing period. + SubscriptionBadRequestErrorResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + allOf: + - $ref: '#/components/schemas/SubscriptionErrorExtensions' + description: Additional properties specific to the problem type may be present. + description: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + SubscriptionChange: + oneOf: + - $ref: '#/components/schemas/PlanSubscriptionChange' + - $ref: '#/components/schemas/CustomSubscriptionChange' + description: Change a subscription. + SubscriptionChangeResponseBody: + type: object + required: + - current + - next + properties: + current: + allOf: + - $ref: '#/components/schemas/Subscription' + description: The current subscription before the change. + title: Current subscription + next: + allOf: + - $ref: '#/components/schemas/SubscriptionExpanded' + description: The new state of the subscription after the change. + title: The subscription it will be changed to + description: Response body for subscription change. + SubscriptionConflictErrorResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + allOf: + - $ref: '#/components/schemas/SubscriptionErrorExtensions' + description: Additional properties specific to the problem type may be present. + description: |- + The request could not be completed due to a conflict with the current state of the target resource. + Variants with ErrorExtensions specific to subscriptions. + SubscriptionCreate: + oneOf: + - $ref: '#/components/schemas/PlanSubscriptionCreate' + - $ref: '#/components/schemas/CustomSubscriptionCreate' + description: Create a subscription. + SubscriptionEdit: + type: object + required: + - customizations + properties: + customizations: + type: array + items: + $ref: '#/components/schemas/SubscriptionEditOperation' + maxItems: 100 + description: |- + Batch processing commands for manipulating running subscriptions. + The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + timing: + allOf: + - $ref: '#/components/schemas/SubscriptionTiming' + description: Whether the billing period should be restarted.Timing configuration to allow for the changes to take effect at different times. + description: Subscription edit input. + SubscriptionEditOperation: + type: object + oneOf: + - $ref: '#/components/schemas/EditSubscriptionAddItem' + - $ref: '#/components/schemas/EditSubscriptionRemoveItem' + - $ref: '#/components/schemas/EditSubscriptionAddPhase' + - $ref: '#/components/schemas/EditSubscriptionRemovePhase' + - $ref: '#/components/schemas/EditSubscriptionStretchPhase' + - $ref: '#/components/schemas/EditSubscriptionUnscheduleEdit' + discriminator: + propertyName: op + mapping: + add_item: '#/components/schemas/EditSubscriptionAddItem' + remove_item: '#/components/schemas/EditSubscriptionRemoveItem' + add_phase: '#/components/schemas/EditSubscriptionAddPhase' + remove_phase: '#/components/schemas/EditSubscriptionRemovePhase' + stretch_phase: '#/components/schemas/EditSubscriptionStretchPhase' + unschedule_edit: '#/components/schemas/EditSubscriptionUnscheduleEdit' + description: The operation to be performed on the subscription. + SubscriptionErrorExtensions: + type: object + properties: + validationErrors: + type: array + items: + $ref: '#/components/schemas/ErrorExtension' + required: + - validationErrors + description: Error extensions for the Subscription Errors. + SubscriptionExpanded: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - status + - customerId + - currency + - billingCadence + - billingAnchor + - settlementMode + - phases + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + annotations: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Set of key-value pairs managed by the system. Cannot be modified by user. + title: Annotations + readOnly: true + status: + allOf: + - $ref: '#/components/schemas/SubscriptionStatus' + description: The status of the subscription. + readOnly: true + customerId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The customer ID of the subscription. + example: 01G65Z755AFWAKHE12NY0CQ9FH + plan: + allOf: + - $ref: '#/components/schemas/PlanReference' + description: The plan of the subscription. + currency: + allOf: + - $ref: '#/components/schemas/CurrencyCode' + description: |- + The currency code of the subscription. + Will be revised once we add multi currency support. + title: Currency + default: USD + billingCadence: + type: string + format: duration + description: |- + The billing cadence for the subscriptions. + Defines how often customers are billed using ISO8601 duration format. + Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + title: Billing cadence + example: P1M + readOnly: true + proRatingConfig: + allOf: + - $ref: '#/components/schemas/ProRatingConfig' + description: The pro-rating configuration for the subscriptions. + title: Pro-rating configuration + default: + enabled: true + mode: prorate_prices + readOnly: true + billingAnchor: + type: string + format: date-time + description: The normalizedbilling anchor of the subscription. + example: '2023-01-01T01:01:01.001Z' + title: Billing anchor + readOnly: true + settlementMode: + allOf: + - $ref: '#/components/schemas/BillingSettlementMode' + description: |- + The settlement mode of the subscription. + - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + This is the default and most common settlement mode. + title: Settlement mode + default: credit_then_invoice + readOnly: true + alignment: + allOf: + - $ref: '#/components/schemas/SubscriptionAlignment' + description: Alignment details enriched with the current billing period. + phases: + type: array + items: + $ref: '#/components/schemas/SubscriptionPhaseExpanded' + description: The phases of the subscription. + description: Expanded subscription + SubscriptionItem: + type: object + required: + - id + - name + - createdAt + - updatedAt + - activeFrom + - key + - billingCadence + - price + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + activeFrom: + type: string + format: date-time + description: The cadence start of the resource. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The cadence end of the resource. + example: '2023-01-01T01:01:01.001Z' + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: |- + The identifier of the RateCard. + SubscriptionItem/RateCard can be identified, it has a reference: + + 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across versions) + 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version of a Feature + + 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + + We say "referenced by the Price" regardless of how a price itself is referenced, it colloquially makes sense to say "paying the same price for the same thing". In practice this should be derived from what's printed on the invoice line-item. + featureKey: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: The feature's key (if present). + billingCadence: + type: string + format: duration + nullable: true + description: |- + The billing cadence of the rate card. + When null, the rate card is a one-time purchase. + title: Billing cadence + price: + allOf: + - $ref: '#/components/schemas/RateCardUsageBasedPrice' + nullable: true + description: |- + The price of the rate card. + When null, the feature or service is free. + title: Price + example: + type: flat + amount: '100' + paymentTerm: in_arrears + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts applied to the rate card. + title: Discounts + included: + allOf: + - $ref: '#/components/schemas/SubscriptionItemIncluded' + description: Describes what access is gained via the SubscriptionItem + taxConfig: + allOf: + - $ref: '#/components/schemas/TaxConfig' + description: |- + The tax config of the Subscription Item. + When undefined, the tax config of the feature or the default tax config of the plan is used. + title: Tax config + description: The actual contents of the Subscription, what the user gets, what they pay, etc... + SubscriptionItemIncluded: + type: object + required: + - feature + properties: + feature: + allOf: + - $ref: '#/components/schemas/Feature' + description: The feature the customer is entitled to use. + entitlement: + allOf: + - $ref: '#/components/schemas/Entitlement' + description: The entitlement of the Subscription Item. + description: Included contents like Entitlement, or the Feature. + SubscriptionPaginatedResponse: + type: object + required: + - totalCount + - page + - pageSize + - items + properties: + totalCount: + type: integer + description: The total number of items. + example: 500 + page: + type: integer + description: The page index. + example: 1 + pageSize: + type: integer + description: The maximum number of items per page. + example: 100 + items: + type: array + items: + $ref: '#/components/schemas/Subscription' + description: The items in the current page. + description: Paginated response + SubscriptionPhase: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - activeFrom + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A locally unique identifier for the resource. + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts on the plan. + title: Discounts + activeFrom: + type: string + format: date-time + description: The time from which the phase is active. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The until which the Phase is active. + example: '2023-01-01T01:01:01.001Z' + description: Subscription phase, analogous to plan phases. + SubscriptionPhaseCreate: + type: object + required: + - startAfter + - key + - name + properties: + startAfter: + type: string + format: duration + nullable: true + description: |- + Interval after the subscription starts to transition to the phase. + When null, the phase starts immediately after the subscription starts. + title: Start after + example: P1Y + duration: + type: string + format: duration + description: |- + The intended duration of the new phase. + Duration is required when the phase will not be the last phase. + title: Duration + example: P1M + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts on the plan. + title: Discounts + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A locally unique identifier for the phase. + name: + type: string + description: The name of the phase. + description: + type: string + description: The description of the phase. + description: Subscription phase create input. + SubscriptionPhaseExpanded: + type: object + required: + - id + - name + - createdAt + - updatedAt + - key + - activeFrom + - items + - itemTimelines + properties: + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: A unique identifier for the resource. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: ID + readOnly: true + name: + type: string + minLength: 1 + maxLength: 256 + description: Human-readable name for the resource. Between 1 and 256 characters. + title: Display name + description: + type: string + maxLength: 1024 + description: Optional description of the resource. Maximum 1024 characters. + title: Description + metadata: + type: object + allOf: + - $ref: '#/components/schemas/Metadata' + nullable: true + description: Additional metadata for the resource. + title: Metadata + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + key: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9]+(?:_[a-z0-9]+)*$ + description: A locally unique identifier for the resource. + discounts: + allOf: + - $ref: '#/components/schemas/Discounts' + description: The discounts on the plan. + title: Discounts + activeFrom: + type: string + format: date-time + description: The time from which the phase is active. + example: '2023-01-01T01:01:01.001Z' + activeTo: + type: string + format: date-time + description: The until which the Phase is active. + example: '2023-01-01T01:01:01.001Z' + items: + type: array + items: + $ref: '#/components/schemas/SubscriptionItem' + description: |- + The items of the phase. The structure is flattened to better conform to the Plan API. + The timelines are flattened according to the following rules: + - for the current phase, the `items` contains only the active item for each key + - for past phases, the `items` contains only the last item for each key + - for future phases, the `items` contains only the first version of the item for each key + itemTimelines: + type: object + additionalProperties: + type: array + items: + $ref: '#/components/schemas/SubscriptionItem' + description: Includes all versions of the items on each key, including all edits, scheduled changes, etc... + description: Expanded subscription phase + SubscriptionStatus: + type: string + enum: + - active + - inactive + - canceled + - scheduled + description: Subscription status. + SubscriptionTiming: + oneOf: + - $ref: '#/components/schemas/SubscriptionTimingEnum' + - type: string + format: date-time + description: '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.' + example: '2023-01-01T01:01:01.001Z' + description: |- + Subscription edit timing defined when the changes should take effect. + If the provided configuration is not supported by the subscription, an error will be returned. + SubscriptionTimingEnum: + type: string + enum: + - immediate + - next_billing_cycle + description: |- + Subscription edit timing. + When immediate, the requested changes take effect immediately. + When nextBillingCycle, the requested changes take effect at the next billing cycle. + TaxBehavior: + type: string + enum: + - inclusive + - exclusive + description: |- + Tax behavior. + + This enum is used to specify whether tax is included in the price or excluded from the price. + TaxConfig: + type: object + properties: + behavior: + allOf: + - $ref: '#/components/schemas/TaxBehavior' + description: |- + Tax behavior. + + If not specified the billing profile is used to determine the tax behavior. + If not specified in the billing profile, the provider's default behavior is used. + title: Tax behavior + stripe: + allOf: + - $ref: '#/components/schemas/StripeTaxConfig' + description: Stripe tax config. + title: Stripe tax config + deprecated: true + customInvoicing: + allOf: + - $ref: '#/components/schemas/CustomInvoicingTaxConfig' + description: Custom invoicing tax config. + title: Custom invoicing tax config + deprecated: true + taxCodeId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: |- + Tax code reference. + + When both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence: + the referenced tax code entity is used and `stripe.code` is ignored. + example: 01G65Z755AFWAKHE12NY0CQ9FH + title: Tax code ID + description: Set of provider specific tax configs. + TieredPrice: + type: object + required: + - type + - mode + - tiers + properties: + type: + type: string + enum: + - tiered + description: |- + The type of the price. + + One of: flat, unit, or tiered. + mode: + allOf: + - $ref: '#/components/schemas/TieredPriceMode' + description: |- + Defines if the tiering mode is volume-based or graduated: + - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + - In `graduated` tiering, pricing can change as the quantity grows. + title: Mode + tiers: + type: array + items: + $ref: '#/components/schemas/PriceTier' + minItems: 1 + description: |- + The tiers of the tiered price. + At least one price component is required in each tier. + title: Tiers + description: Tiered price. + TieredPriceMode: + type: string + enum: + - volume + - graduated + description: The mode of the tiered price. + TieredPriceWithCommitments: + type: object + required: + - type + - mode + - tiers + properties: + type: + type: string + enum: + - tiered + description: |- + The type of the price. + + One of: flat, unit, or tiered. + mode: + allOf: + - $ref: '#/components/schemas/TieredPriceMode' + description: |- + Defines if the tiering mode is volume-based or graduated: + - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + - In `graduated` tiering, pricing can change as the quantity grows. + title: Mode + tiers: + type: array + items: + $ref: '#/components/schemas/PriceTier' + minItems: 1 + description: |- + The tiers of the tiered price. + At least one price component is required in each tier. + title: Tiers + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Tiered price with spend commitments. + ULIDOrExternalKey: + anyOf: + - type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ULID (Universally Unique Lexicographically Sortable Identifier). + example: 01G65Z755AFWAKHE12NY0CQ9FH + - type: string + minLength: 1 + maxLength: 256 + description: ExternalKey is a looser version of key. + description: ULID (Universally Unique Lexicographically Sortable Identifier) or external unique key. + x-go-type: string + UnauthorizedProblemResponse: + type: object + allOf: + - $ref: '#/components/schemas/UnexpectedProblemResponse' + description: The request has not been applied because it lacks valid authentication credentials for the target resource. + UnexpectedProblemResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + type: object + additionalProperties: {} + description: Additional properties specific to the problem type may be present. + example: + validationErrors: + - code: validation_error + message: Validation error + otherAttribute: otherValue + additionalProperties: {} + description: |- + A Problem Details object (RFC 7807). + Additional properties specific to the problem type may be present. + x-go-type-import: + path: github.com/openmeterio/openmeter/pkg/models + x-go-type: models.StatusProblem + UnitPrice: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - unit + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the unit price. + description: Unit price. + UnitPriceWithCommitments: + type: object + required: + - type + - amount + properties: + type: + type: string + enum: + - unit + description: The type of the price. + amount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The amount of the unit price. + minimumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is committed to spend at least the amount. + title: Minimum amount + maximumAmount: + allOf: + - $ref: '#/components/schemas/Numeric' + description: The customer is limited to spend at most the amount. + title: Maximum amount + description: Unit price with spend commitments. + ValidationError: + type: object + required: + - field + - code + - message + properties: + field: + type: string + description: The path to the field. + example: addons/pro/ratecards/token/featureKey + readOnly: true + code: + type: string + description: The machine readable description of the error. + example: invalid_feature_key + readOnly: true + message: + type: string + description: The human readable description of the error. + example: not found feature by key + readOnly: true + attributes: + allOf: + - $ref: '#/components/schemas/Annotations' + description: Additional attributes. + readOnly: true + description: Validation errors providing detailed description of the issue. + ValidationErrorProblemResponse: + type: object + required: + - type + - title + - detail + - instance + properties: + type: + type: string + format: uri + description: Type contains a URI that identifies the problem type. + example: about:blank + default: about:blank + title: + type: string + description: A a short, human-readable summary of the problem type. + example: Bad Request + status: + type: integer + format: int16 + minimum: 400 + maximum: 599 + description: The HTTP status code generated by the origin server for this occurrence of the problem. + example: 400 + detail: + type: string + description: A human-readable explanation specific to this occurrence of the problem. + example: The request body must be a JSON object. + instance: + type: string + format: uri + description: A URI reference that identifies the specific occurrence of the problem. + example: urn:request:local/JMOlctsKV8-000001 + extensions: + type: object + properties: + validationErrors: + type: array + items: + $ref: '#/components/schemas/ValidationError' + description: Validation issues. + readOnly: true + description: A BadRequestError with a validationErrors extension. + ValidationIssue: + type: object + required: + - createdAt + - updatedAt + - id + - severity + - component + - message + properties: + createdAt: + type: string + format: date-time + description: Timestamp of when the resource was created. + example: '2024-01-01T01:01:01.001Z' + title: Creation Time + readOnly: true + updatedAt: + type: string + format: date-time + description: Timestamp of when the resource was last updated. + example: '2024-01-01T01:01:01.001Z' + title: Last Update Time + readOnly: true + deletedAt: + type: string + format: date-time + description: Timestamp of when the resource was permanently deleted. + example: '2024-01-01T01:01:01.001Z' + title: Deletion Time + readOnly: true + id: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: ID of the charge or discount. + example: 01G65Z755AFWAKHE12NY0CQ9FH + readOnly: true + severity: + allOf: + - $ref: '#/components/schemas/ValidationIssueSeverity' + description: The severity of the issue. + readOnly: true + field: + type: string + description: The field that the issue is related to, if available in JSON path format. + readOnly: true + code: + type: string + description: Machine indentifiable code for the issue, if available. + readOnly: true + component: + type: string + description: Component reporting the issue. + readOnly: true + message: + type: string + description: A human-readable description of the issue. + readOnly: true + metadata: + allOf: + - $ref: '#/components/schemas/Metadata' + description: Additional context for the issue. + readOnly: true + description: |- + ValidationIssue captures any validation issues related to the invoice. + + Issues with severity "critical" will prevent the invoice from being issued. + ValidationIssueSeverity: + type: string + enum: + - critical + - warning + description: |- + ValidationIssueSeverity describes the severity of a validation issue. + + Issues with severity "critical" will prevent the invoice from being issued. + VoidInvoiceActionCreate: + type: object + required: + - percentage + - action + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + description: How much of the total line items to be voided? (e.g. 100% means all charges are voided) + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceLineActionCreate' + description: The action to take on the line items. + description: InvoiceVoidAction describes how to handle the voided line items. + VoidInvoiceActionCreateItem: + type: object + required: + - percentage + - action + properties: + percentage: + allOf: + - $ref: '#/components/schemas/Percentage' + description: How much of the total line items to be voided? (e.g. 100% means all charges are voided) + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceLineActionCreateItem' + description: The action to take on the line items. + description: InvoiceVoidAction describes how to handle the voided line items. + VoidInvoiceActionInput: + type: object + required: + - action + - reason + properties: + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceActionCreate' + description: The action to take on the voided line items. + reason: + type: string + description: The reason for voiding the invoice. + overrides: + type: array + items: + $ref: '#/components/schemas/VoidInvoiceActionLineOverride' + nullable: true + description: |- + Per line item overrides for the action. + + If not specified, the `action` will be applied to all line items. + description: Request to void an invoice + VoidInvoiceActionLineOverride: + type: object + required: + - lineId + - action + properties: + lineId: + type: string + pattern: ^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$ + description: The line item ID to override. + example: 01G65Z755AFWAKHE12NY0CQ9FH + action: + allOf: + - $ref: '#/components/schemas/VoidInvoiceActionCreateItem' + description: The action to take on the line item. + description: VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding. + VoidInvoiceLineActionCreate: + type: object + oneOf: + - $ref: '#/components/schemas/VoidInvoiceLineDiscardAction' + - $ref: '#/components/schemas/VoidInvoiceLinePendingActionCreate' + discriminator: + propertyName: type + mapping: + discard: '#/components/schemas/VoidInvoiceLineDiscardAction' + pending: '#/components/schemas/VoidInvoiceLinePendingActionCreate' + description: VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. + VoidInvoiceLineActionCreateItem: + type: object + oneOf: + - $ref: '#/components/schemas/VoidInvoiceLineDiscardAction' + - $ref: '#/components/schemas/VoidInvoiceLinePendingActionCreateItem' + discriminator: + propertyName: type + mapping: + discard: '#/components/schemas/VoidInvoiceLineDiscardAction' + pending: '#/components/schemas/VoidInvoiceLinePendingActionCreateItem' + description: VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. + VoidInvoiceLineActionType: + type: string + enum: + - discard + - pending + description: VoidInvoiceLineActionType describes how to handle the voidied line item in the invoice. + VoidInvoiceLineDiscardAction: + type: object + required: + - type + properties: + type: + type: string + enum: + - discard + description: The action to take on the line item. + description: VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. + VoidInvoiceLinePendingActionCreate: + type: object + required: + - type + properties: + type: + type: string + enum: + - pending + description: The action to take on the line item. + nextInvoiceAt: + type: string + format: date-time + description: |- + The time at which the line item should be invoiced again. + + If not provided, the line item will be re-invoiced now. + example: '2023-01-01T01:01:01.001Z' + description: VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. + VoidInvoiceLinePendingActionCreateItem: + type: object + required: + - type + properties: + type: + type: string + enum: + - pending + description: The action to take on the line item. + nextInvoiceAt: + type: string + format: date-time + description: |- + The time at which the line item should be invoiced again. + + If not provided, the line item will be re-invoiced now. + example: '2023-01-01T01:01:01.001Z' + description: VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. + WindowSize: + type: string + enum: + - MINUTE + - HOUR + - DAY + - MONTH + description: Aggregation window size. + x-enum-varnames: + - Minute + - Hour + - Day + - Month + WindowedBalanceHistory: + type: object + required: + - windowedHistory + - burndownHistory + properties: + windowedHistory: + type: array + items: + $ref: '#/components/schemas/BalanceHistoryWindow' + description: |- + The windowed balance history. + - It only returns rows for windows where there was usage. + - The windows are inclusive at their start and exclusive at their end. + - The last window may be smaller than the window size and is inclusive at both ends. + burndownHistory: + type: array + items: + $ref: '#/components/schemas/GrantBurnDownHistorySegment' + description: Grant burndown history. + description: The windowed balance history. + securitySchemes: + PortalTokenAuth: + type: http + scheme: Bearer + description: Consumer portal token. +servers: + - url: https://127.0.0.1 + description: Local + variables: {} diff --git a/api/spec/.gitignore b/api/spec/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..601e6a6b715e5286f9cd0f631a1c58f495f56dd2 --- /dev/null +++ b/api/spec/.gitignore @@ -0,0 +1,7 @@ +# TypeSpec output (all packages) +**/output/ +**/dist/ + +# Dependency directories +node_modules/ +tsconfig.tsbuildinfo diff --git a/api/spec/.npmrc b/api/spec/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..79faa9a3086732fb9880fae48a7ea6d554d4af49 --- /dev/null +++ b/api/spec/.npmrc @@ -0,0 +1,2 @@ +save-exact=true +side-effects-cache=false diff --git a/api/spec/.prettierignore b/api/spec/.prettierignore new file mode 100644 index 0000000000000000000000000000000000000000..2a2a7e65f4b33e06fc93d29d3763f34fd392c3f1 --- /dev/null +++ b/api/spec/.prettierignore @@ -0,0 +1,7 @@ +.npmrc +pnpm-lock.yaml +packages/**/output/ +packages/**/dist/ +packages/**/coverage/ +packages/typespec-typescript/src/static-helpers/lib-files-data.gen.ts +packages/aip-client-go/ diff --git a/api/spec/.prettierrc.json b/api/spec/.prettierrc.json new file mode 100644 index 0000000000000000000000000000000000000000..f184d41325446c1914caabff3ffb30a979809650 --- /dev/null +++ b/api/spec/.prettierrc.json @@ -0,0 +1,11 @@ +{ + "arrowParens": "always", + "bracketSameLine": false, + "tabWidth": 2, + "printWidth": 80, + "semi": false, + "singleQuote": true, + "trailingComma": "all", + "plugins": ["@typespec/prettier-plugin-typespec"], + "overrides": [{ "files": ".tsp", "options": { "parser": "typespec" } }] +} diff --git a/api/spec/AGENTS.md b/api/spec/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..ddb4d39a68fa79e8a4aafed095e569d709a1773f --- /dev/null +++ b/api/spec/AGENTS.md @@ -0,0 +1,857 @@ +# OpenMeter API Spec & SDK Generator + +This workspace holds the TypeSpec API definitions and SDK generators. For +repo-wide guidance see the root [AGENTS.md](../../AGENTS.md); this +file covers only what is specific to `api/spec`. + +## Layout + +``` +packages/ + aip/ # AIP TypeSpec source (api definitions, linter rules) + legacy/ # legacy OpenAPI output + typespec-typescript/ # the SDK generator (TypeSpec emitter, Alloy-based) + typespec-go/ # the Go SDK generator (TypeSpec emitter, Alloy-based) + aip-client-javascript/ # generator OUTPUT: the emitted TypeScript SDK +``` + +The **runtime templates** (the fixed SDK runtime files + conformance tests the +generator reproduces verbatim) live as real, reviewable files under +`typespec-typescript/templates/` — not embedded blobs and not a separate +baseline directory. `typespec-typescript/src/runtime-templates.ts` reads them +via `readFileSync` at build time and emits them into the generated SDK. To +edit the runtime templates or tests, edit the files under `templates/` +directly, then run `make -C api/spec generate`. + +- `typespec-typescript` is a TypeSpec **emitter** built on `@alloy-js` + + `@typespec/emitter-framework`. It walks HTTP operations and emits the full + SDK. +- `aip-client-javascript` is its **output directory** (`emitter-output-dir` in + `packages/aip/tspconfig.yaml` points here). Everything it contains is + regenerable — never hand-edit it. A single `generate` emits the complete SDK + (schemas, runtime, per-namespace surface, barrel) plus the conformance tests. +- `typespec-go` is a TypeSpec **emitter** built on `@alloy-js/go` + + `@typespec/emitter-framework`. It emits the Go SDK into `api/v3/client`, which + is also fully regenerable generated output. + +### How the emitter is structured + +- `emitter.tsx` — `$onEmit`: emits `schemas.ts` (Alloy components, the original + path), the static runtime files, and the per-namespace surface files, all as + sibling `` children of one ``. +- `runtime-templates.ts` — reads the fixed runtime files (`core.ts`, `lib/*`, + `models/errors.ts`) and the conformance tests verbatim, via `readFileSync`, + from the committed `templates/runtime/` and `templates/tests/` directories + at build time. Edit those files directly to change the runtime or tests; + `templates/` is excluded from this package's own `tsconfig.json` `include` + (only checked downstream, as part of the generated `aip-client-javascript` + package's typecheck/test suite). +- New runtime helpers that don't fit the fixed `templates/` set (e.g. + `lib/wire.ts`) are authored as a real `.ts` file under `src/runtime/` + instead (type-checked and unit-tested by the emitter package's own tooling) + and embedded verbatim via `readFileSync` at build time (see + `src/wire-runtime.ts`), not as a template-string constant — backticks/`${` + inside the runtime source collide with the template-literal delimiters. +- `sdk-operations.ts` — operation discovery: namespace grouping, per-op metadata + (path/query/body/response), and naming (func name, facade method name via + resource-noun stripping, namespace names). +- `pagination.ts` — structural detection of page-number vs cursor list + operations (see "Pagination companions" below). +- `sdk-files.ts` — string generators for the spec-derived surface files + (operations types, funcs, facades, root client, barrels). +- `readme.ts` — builds the package `README.md` (emitted at the package root, not + under `src/`) from the same grouped `SdkOperation[]` the SDK files use, so its + documented call paths and routes always match the emitted client. + +### Grouping (reproduce this) + +The `OpenMeter` service surfaces every operation through an `*Endpoints` +interface that `extends` the resource's interface in its **source** namespace +(e.g. `OpenMeter.PlansEndpoints extends ProductCatalog.PlanOperations`). The op +walked lives on the `*Endpoints` interface, so its own `namespace` is +`OpenMeter` — the meaningful grouping is on `op.interface.sourceInterfaces[0]`. + +Group by the **top of the source namespace chain** so multi-interface +namespaces stay one client: `MetersEndpoints` + `MetersQueryEndpoints` → +`meters` (keeps `meters.query`); all `Customer*Endpoints` → `customers`. +`ProductCatalog` is the exception (in `SPLIT_BY_INTERFACE`): it splits by source +interface → `plans`, `addons`, `planAddons`. Do NOT group by `@tag` (the tag is +a display string like "Metering Events" → stutter) or by `op.namespace` (always +`OpenMeter`). + +### Nested sub-clients (reproduce this) + +The SDK nests sub-clients (`customers.charges.list()`, +`customers.credits.grants.list()`) from the **source namespace chain** below the +group's top namespace. Walking `sourceInterfaces[0].namespace` up to the global +root yields e.g. `['Customers', 'Charges']` → group `customers`, nest path +`['charges']`; `['Customers', 'Credits', 'Grants']` → `customers.credits.grants`. +`facadeFile` builds a tree from these paths, emitting one class per node with +lazy sub-client getters that share the parent's `Client`. + +Because grouping follows the source namespace (not the route), an operation +routed under one resource but defined in another's namespace lands under the +latter — by design. `list-customer-entitlement-access` is routed under +`/customers/` but its interface lives in `Entitlements`, so it is +`entitlements.listCustomerAccess()`, NOT `customers.entitlements.*`. This is a +deliberate decision (the op is genuinely an Entitlements operation); do not +"fix" it to nest under customers. + +This nesting is **driven by the TypeSpec source structure, not API routes** — to +nest a resource, wrap its `*Operations` interface in a sub-namespace +(`namespace Charges { interface CustomerChargesOperations { … } }` inside a file +that declares `namespace Customers;`), and update the `extends` reference in +**both** `openmeter.tsp` and `konnect.tsp` to the nested path. Wrap ONLY the +operation interface — leave models in the parent namespace so their schema names +(and OpenAPI output) are unchanged. The method-name strip set includes the nest +segments, so `create-credit-grant` under `credits.grants` → `create`. + +**OpenAPI invariance is the hard gate** for any `.tsp` change: regenerate and +confirm the `output/definitions/.../*.yaml` hashes are unchanged. Namespace +nesting of operation interfaces is OpenAPI-neutral (paths/tags/operationIds are +explicit); moving a _model_ is not. Watch for namespace collisions — nesting +`Customers.Billing` shadows the global `Billing` namespace for unqualified refs +in `Customers`-scoped files; alias around it (`Common.BillingRoot`) rather than +renaming. + +### Naming rules (reproduce these) + +- **func name** = full camelCase operationId: `get-meter` → `getMeter`. +- **facade method** = operationId with the group's resource noun(s) and the + cross-cutting `metering` qualifier stripped: `get-meter` → `get`; + `get-customer-billing` → `getBilling`; `ingest-metering-events` → `ingest`. + Singular/plural folded. The resource name is split into strip-words on + separators **and** case boundaries — both camelCase (`PlanAddons` → `plan`, + `addons`) and acronym→word (`LLMCost` → `llm`, `cost`) — so multi-word and + acronym-prefixed namespaces strip fully (`create-plan-addon` → `create`, + `create-llm-cost-override` → `createOverride`). When the operationId noun is + not the namespace's own resource word it is kept as a disambiguator + (`llmCost.listPrices`/`listOverrides`, `subscriptions.listAddons`). +- **namespace** = source namespace (already plural, e.g. `Meters`, `Events`, + `Customers`) or a pluralized split interface resource (`Plan` → `Plans`); + PascalCase class / camelCase getter. +- **request type** composed from direct-TS parts (no `z.input`): query-only → + `Query`; body-only → the body interface (its `…Input` variant when the + body diverges on input); path-only → `{ id: string }`; path+body → + `{ id; body }`; path+query → `Query & { id }`; body+query → + `{ body } & Query` (body nested so query fields don't leak into the JSON + body). Path params are ULIDs, typed `string`. See "Request types" below. + +### TypeSpec style constraints + +- When adding query decorators (for example `@query`) to a TypeSpec file that + does not already use HTTP decorators, import `@typespec/http` and add + `using TypeSpec.Http;` in that file; otherwise compilation fails with + `Unknown decorator @query`. + +## Commands + +| Task | Command | +| ----------------------------- | ---------------------------------------------------- | +| Build all TypeSpec emitters | `pnpm run build` | +| Regenerate SDK from TypeSpec | `pnpm --filter @openmeter/api-spec-aip run generate` | +| Run the SDK conformance tests | `pnpm run test:sdk` | +| Install / refresh lockfile | `pnpm install --config.confirmModulesPurge=false` | + +The emitters are bound by **package name** (`@openmeter/typespec-typescript`, +`@openmeter/typespec-go`) in `packages/aip/tspconfig.yaml` (both the `emit:` list +and the `options:` keys). The internal lib names in each `src/lib.ts` and their +`…:` state keys are separate identities used for diagnostics/state and have no +cross-package references. + +## The emitted SDK: conventions the generator must reproduce + +The hand-written runtime files and conformance tests under +`typespec-typescript/templates/` define the exact shape the generator must +reproduce. The tests are the conformance target — the generated SDK is "done" +when it passes them. + +### Casing: camelCase public surface, snake_case wire + +The AIP API is **snake_case on the wire** (TypeSpec, OpenAPI, and the casing lint +rule stay snake). The generated JS SDK exposes a **camelCase** public surface — the +TS interfaces and zod schemas are camelCase — and a boundary mapper +(`src/lib/wire.ts`) translates at the edge: `toWire` (camelCase → snake_case) on +request bodies and query objects, `fromWire` (snake_case → camelCase) on responses. + +camelCase is the **TypeScript-specific** public surface, not a wire change — the +wire stays snake_case for every SDK. Other language generators are expected to apply +their own idiomatic surface transformation over the same snake_case wire: a Go SDK +would use exported UpperCamelCase fields with `json:"snake_case"` tags, a Python SDK +would keep snake_case (already idiomatic), etc. Keep casing decisions in the +per-language emitter; do not push a language's casing into TypeSpec, OpenAPI, or the +wire. + +The translation is a **deterministic casing rule**, not a per-field map: every wire +name round-trips through `toSnakeCase(toCamelCase(name))`, enforced at codegen by a +gate (`assertCasingDerivable`) that fails the build for any non-derivable name. The +public key is `toCamelCase(resolveEncodedName(...))`, so the wire key the mapper +emits is exactly the OpenAPI name. The mapper is **schema-driven**: it walks the zod +schema alongside the data so `Record` keys that are user data (label +names, meter dimension names) are preserved verbatim, while typed field keys +(including AIP `filter[field]` names and `sort.by`) are translated. + +The same gate (`assertCasingDerivable`) also **fails the build for a non-discriminated +union with two or more object variants reachable from a request body or success +response** — the mapper cannot pick a variant without a discriminator, and does not +guess. Use `@discriminated` for such unions (scalar-vs-object unions, and `T | T[]` +single-or-batch bodies, are fine — distinguished at runtime by JS type). Discriminated +unions dispatch via a memoized literal→variant map keyed on the (camel public / snake +wire) discriminator value. + +### Dates: `Date` public surface, RFC 3339 wire, requests also take strings + +Every date-time in the AIP spec is the shared `DateTime` scalar (`utcDateTime` with +`@encode(rfc3339)`). The wire stays the RFC 3339 string; the generated TS surface +types these fields **`Date`** — in interfaces, query types, and the camelCase zod +schemas (`z.date()`) — while the `…Wire` schemas keep `z.string().datetime()`. +The boundary mapper converts alongside the casing pass: `toWire` serializes any +`Date` instance to `toISOString()` wherever it sits (bodies and query objects alike, +and before `…Wire` validation, so `validate` checks the wire form), and `fromWire` +revives strings into `Date`s at date-typed schema nodes, including record/array +values. A datetime behind a union (`DateTime | null` on `event.time`, +enum-or-`DateTime` on subscription `timing`) is revived only when the date variant is +the string's sole plausible owner — enum literals, matching string literals, and +plain-string variants pass through untouched (fail-open, same policy as unmatched +union variants). + +**Requests additionally accept RFC 3339 strings**: each body/query-bearing +`…Request` alias is wrapped in `AcceptDateStrings` (exported from `lib/wire.ts`), +a recursive mapped type turning every `Date` into `Date | DateString`, where +`DateString = string & Record` — assignable from any string but +immune to union absorption, so literal siblings of a `Date` (subscription +`timing`'s `'immediate' | 'next_billing_cycle'`) keep their autocomplete instead +of collapsing into `string`. The widening +lives on the request alias only — domain interfaces and `…Query` interfaces stay +`Date`, because they also describe responses and are pinned to the schemas by the +model conformance guard and the per-op query input guards; widening them (or forking +input variants per model) is exactly what this avoids. At runtime a request string +passes through the mapper verbatim (never re-parsed or normalized — a non-UTC +offset or malformed string reaches the server as-is unless `validate` is on, where +the wire schema's UTC `datetime()` check rejects it). + +### Response/request mapping drops unknown fields + +`fromWire`/`toWire` **rename keys and map date values only** (`Date` ↔ RFC 3339 +string, see above) — they never call `schema.parse()`, never apply zod defaults, and +never coerce any other value. A field not present in the schema shape +is **dropped**, so the mapped object exactly matches the typed interface (a +server-added field is not in the type and does not survive). This is a deliberate +choice for strict typing over forward-compatibility. zod is retained for type +derivation (`z.input`/`z.output`), query/path coercion, mapper structure, and the +one `baseError.safeParse` in the error path. Error responses bypass the mapper +(`toError` reads the raw snake body; `HTTPError.getField` is a raw, untyped escape +hatch). + +### Optional wire-payload validation (`validate` option) + +`SDKOptions.validate` (default **off**) turns on schema validation of the actual +`snake_case` wire payload: the request body after `toWire` (before sending) and the +raw response body before `fromWire`. Validation uses the generated **`…Wire` +schemas** in `models/schemas.ts` — every model and per-op body/response is emitted a +second time in a `snake_case` "wire" pass (`WireModeContext` in the emitter), keyed by +the raw JSON wire name and made `z.strictObject`, so a wrong-shaped or +leaked-camelCase wire field is **rejected, not silently stripped**. Open models +(record spread, `emitsAsIntersection`, e.g. `baseError`) stay non-strict — strict +would defeat the record arm that exists to accept them. The wire pass uses the same +emitter walk as the camelCase pass (parameterized by direction + key-casing + +strictness + a separate refkey namespace), but it must describe the value **after** +transport encoding: date-time values are strings, SDK-coded query parameters use +their declared transport type, and defaults are absent. A failure throws +`ValidationError`, which `request()` surfaces as `Result.error` (request validation +runs _inside_ the `request()` closure so it does not throw synchronously). +**Enabling `validate` re-introduces exactly the rejection the default policy +avoids**: a strict wire schema rejects additive/unknown server fields and unknown +enum values. It is opt-in defense-in-depth, not the default, precisely because the +default contract must not break on additive fields. + +Models decorated with `@useRef` still need a local TypeSpec shape that matches the +referenced OpenAPI schema. The TypeScript and Go emitters walk the local TypeSpec +AST; `@useRef` only changes the emitted OpenAPI reference and does not import the +referenced schema's requiredness or nullability into language-specific SDKs. + +TypeSpec defaults belong only on public schemas. `toWire` reads the public schema to +materialize required request defaults before wire validation; `…Wire` schemas must +not use Zod `.default(...)`, because the same schema validates responses and a +default wrapper would accept a required field the server omitted. The query +parameter name `sort` is reserved: it must use `Common.SortQuery` directly (not an +alias), enforced by the AIP `sort-query-type` linter rule. Both SDK emitters select +the sort codec from that validated HTTP parameter name. The TypeScript emitter must +validate the public property schema before encoding and the encoded value against +the operation's wire schema afterward. +Generated path-parameter schemas are part of the same boundary: in strict mode, +map path values to their transport representation, validate the mapped object, +then interpolate and URL-encode it. Preserve path binding names during mapping; +unlike JSON object keys, they must not be snake-cased. Keep mapping conditional so +`validate: false` retains its established runtime behavior. + +### Documented types: generated from TypeSpec, verified against zod + +**zod schemas and TypeScript types are separate artifacts with one source.** Both +are generated from the same TypeSpec, but neither is derived from the other at the +type level: + +- `models/schemas.ts` — zod schemas (runtime validation in the error path, query/ + path coercion). The runtime artifact. +- `models/types.ts` — concrete TypeScript interfaces (the public surface that + `.json()` is typed against). **Self-contained: it imports neither `zod` nor + `schemas.ts`.** Field types are walked directly from the TypeSpec AST by + `tsTypeOf` in `ts-types.ts`, which mirrors the leaf decisions of + `zodBaseSchemaParts` (the zod walker) so the two stay type-equivalent. +- `models/types.assert.ts` — the inferred types are used **only for verification**: + a mutual-assignability guard ties `types.ts` to `schemas.ts` at build time. + +Why not infer `types.ts` from `z.output`? zod strips `.describe()` +at the type level, so an inferred type has the shape but no docs; and indexed +access (`Meter['name']`) couples the public types to the runtime schemas. Walking +TypeSpec directly gives clean concrete types (`id: string`, +`aggregation: "sum" | "count" | …`, `labels?: Labels`) with `/** … */` JSDoc from +the TypeSpec `@doc`, decoupled from zod. + +`tsTypeOf` leaf mapping (must match `zodBaseSchemaParts` or the guard fails): + +- scalars → `string` / `number` / `boolean`; **int64/uint64 → `bigint`** (zod uses + `z.coerce.bigint()`); everything else numeric → `number`. +- **dates/times/durations → `string`** (wire-native; RFC 3339, never `Date`). +- enums → inlined literal unions (`"a" | "b"`); never collected as named + interfaces. A **named** TypeSpec `union` (`union Price { free: PriceFree, … }`) + refs its own `types.ts` alias when reachable (see "Named union aliases" + below); an anonymous union expression (`A | B` written inline) still inlines + its variants. +- named models (incl. named records like `Labels`) → ref the interface; anonymous + models → inlined object literal; arrays → `T[]` (parenthesized when `T` is a + union: `(A | B)[]`); open records → `Record`. + +Structural rules the interface emitter follows: + +- **Optionality follows OUTPUT**: a defaulted field is optional-in / required-out, + so `prop.optional && prop.defaultValue === undefined` decides the `?`. +- **No-wire-prop models alias** to their mapped structure + (`export type Labels = Record`), never an empty permissive + `interface {}`. The alias excludes the model from its own ref resolution so it + does not become `type Labels = Labels`. +- **`extends`** the base interface when the model has a `baseModel`, so inherited + fields/docs propagate (`BadRequest extends BaseError`). +- **Open records** (`...Record<…>`) get an index signature (`[key: string]: V`). +- **Named union aliases.** Every named TypeSpec `union` that is reachable from + an operation on an included service gets its own + `export type = | | …` in `types.ts` (`interface-types.ts`, + `unionVariantsType` in `ts-types.ts`) — variants resolve through the same + `RefName`/`refNameInput` machinery as model properties, so a model-variant is + named (`PriceFree`) and an anonymous-object variant inlines. The alias gets the + same conformance guard as a model interface, and an `…Input` variant + (`computeDivergentUnions` in `input-variants.ts`) only when at least one variant + is itself a divergent model (e.g. `WorkflowPaymentSettingsInput`, because + `WorkflowPaymentSendInvoiceSettings` has a defaulted field) — a union with no + divergent variant (e.g. `WorkflowCollectionAlignment`) has no `…Input` alias. + **Reachability gate:** a union can be declared in TypeSpec (and still get a zod + schema, since `getAllDataTypes` walks the whole namespace tree) without + anything in the actual SDK surface referencing it — `computeReachableUnions` in + `emitter.tsx` walks every collected operation's request body, query + parameters, and response body (success and error) and only aliases unions it + reaches. Every operation counts as a reachability root: `x-internal` and + `x-private` operations are emitted under the `client.internal.*` surface, so + the unions they reach are aliased too (`Invoice`/`InvoiceLine`/ + `UpdateInvoiceRequest` via the `x-private` invoice operations, `Currency` via + the `x-internal` currency operations). `PriceUsageBased`, + `ULIDOrResourceKey`, and `ULIDOrExternalResourceKey` are declared but never + referenced by anything, so they stay zod-only (aliasing them would export a + degenerate type like `string | string`); models are never reachability-gated + — only the union alias pass is. This is a deliberately narrower policy + than models', to avoid exporting unions nothing in the shipped client can + ever produce or accept. +- **Response wiring picks up named unions too.** Because a named union now + resolves through the same `resolveInterface`/`emittedInterfaceNames` path as a + model, an operation whose success body is directly a reachable named union + (e.g. `get-app` → `App`) wires its `…Response` alias to the union alias instead + of falling back to `z.output` — see "Response wiring" below. + +**Conformance guard (the oracle).** Every emitted type — both `interface`s **and** +the no-wire-prop `type` aliases — is paired with a mutual-assignability check in +`models/types.assert.ts` +(`[X] extends [z.output<…>] ? [z.output<…>] extends [X] ? true : {__error}`). This +is the _only_ place `types.ts` and `schemas.ts` meet: it proves the directly-walked +TS type is type-equivalent to the zod schema, turning any divergence (wrong leaf, +wrong optionality, header leak, open-record gap) into a **build error**. `tsc` is +the oracle. The alias branch must guard too: unlike a former `z.output` alias +(tautological), a `tsTypeOf`-walked alias like `LabelsFieldFilter` is an +independent claim that can diverge. One blind spot remains by nature: the check is +vacuous when either side is `any` — so the output is also grepped for `: any` (the +AIP spec uses `unknown`, never `any`, so no field hits it). + +**Response wiring.** Per-operation `…Response` aliases point at the documented +interface when the success body resolves to a named model **or named union** +(e.g. `get-app` → `App`; see "Named union aliases" above). The extracted HTTP body +of a list endpoint is **anonymous** (TypeSpec strips the envelope identity during +body extraction), so `sdkOperation` falls back to the 2xx **response envelope** +(`HttpOperationResponse.type`), whose `@friendlyName` survives — e.g. +`PagePaginatedResponse` → `MeterPagePaginatedResponse`. This reuses the +already-emitted, already-guarded paginated interfaces (no synthesis). Net: ~70/81 +responses wired to interfaces, 10 void, 1 text (CSV) — none fall back to +`z.output` now that a directly-returned named union resolves +to its own alias instead. + +Compared to the `zod-to-ts` npm package (which also walks a zod schema to a TS +type with JSDoc from `.describe()`): that lib **inlines** nested objects and emits +`prop?: T | undefined` for optionals, sourcing docs from `.describe()`. This +generator instead **refs** named interfaces (better for a published SDK), emits +clean `prop?: T` output-shaped optionality (defaulted fields required, no +`| undefined`), and sources docs from TypeSpec `@doc` — so the emitter does not +depend on `.describe()` surviving into the runtime schemas. + +### Factoring: what the generator emits, and how often + +- **ONCE** (shared runtime in `lib/` + `core.ts`): the base `Client`/transport + (one `ky.create`), the `request()` envelope, `Result`/`ok`/`err`/`unwrap`, + the curated `RequestOptions`, the encoders (`encodePath`, `toURLSearchParams`, + `encodeSort`, `querySerializer`), `toError`, and the `HTTPError` class. +- **PER-NAMESPACE** (per resource/tag): one façade class that **composes** a + `Client` (holds a reference — it does **not** `extends Client`) plus one + memoized lazy getter on the root `OpenMeter`. +- **PER-OPERATION** (×~83): one standalone func = path/query/body assembly + + `request(() => http(client).(…).json())`, plus a one-line façade + wrapper. The request/response type aliases and per-op `…Query` types live in + `models/operations/.ts` (their guards in `models/operations/.assert.ts`); + `funcs/.ts` imports `…Request`/`…Response` from there and holds only + functions, so the funcs modules stay free of type declarations and guards. + +### Void responses must not call `.json()` + +The 10 operations whose `Response` is `void` (`!op.hasResponse` — every +`delete*` plus `events.ingest`, which return `204 No Content` / `202 Accepted` +with an empty body) terminate with `request(async () => { await http(client).(…) })`, +**not** `.json()`. ky's `.json()` throws `SyntaxError: Unexpected end of JSON input` +on an empty body (and explicitly on `204`), so calling it on a successful +void response rejects a request that actually succeeded server-side — `ingest` +(the product's hot path) and every delete. Awaiting the `ResponsePromise` +without parsing still rejects on non-2xx (ky's `throwHttpErrors` default is on), +so error propagation is preserved. `funcBody` branches on `op.hasResponse` for +this; non-void funcs keep the `.json()` terminal unchanged. +`tests/void-responses.spec.ts` is the regression guard: success on empty +202/204, still-rejects on a 500 (status-only fallback), and **full problem+json +error fidelity** preserved on a void op (the ky fork populates `e.data` at throw +time regardless of `.json()`, so `to-error.ts` recovers `title`/`detail`/`type` +identically to non-void ops). Note `baseError.safeParse` requires `instance`, so +a problem+json mock without it falls through to the status-only error — include +`instance` to exercise the structured branch. The test is **hand-maintained** +(it isn't part of the `templates/tests/` set `runtime-templates.ts` emits), so +it lives directly in `tests/` and is not re-emitted by `generate` — do not +delete it expecting a regen to restore it. + +### Request types: direct TS, input-variant interfaces + +Request/response types are direct TS, not `z.input`/`z.output`, and live in +`models/operations/.ts` (re-exported from the barrel under their existing +public names). The split mirrors the model types: + +- **Response** → the documented output interface (a model or, since named + unions are aliased too, a union like `App`), `void`, or `string` (text/CSV). +- **Request body** → the body model's (or named union's) interface, or its + **`…Input` variant** when the body's input shape diverges from its output. A + model diverges iff a defaulted field — anywhere in its reachable subtree — + flips from required (output) to optional (input); `computeDivergentModels` (in + `input-variants.ts`) is the transitive fixpoint. A union diverges iff at least + one of its own variants is a divergent model (`computeDivergentUnions`, same + file — shallow, not transitive, since a union carries no properties of its + own). `interface-types.ts` emits an `XInput` interface/alias (relaxed + optionality, refing child `YInput` variants) for each divergent model or union + — e.g. `create-customer-charges`'s body resolves to the union alias + `CreateChargeRequest`. ~12 request bodies diverge directly; their closure is + ~51 `…Input` interfaces. +- **Query** → a per-op `Query` interface walked from the query parameter + leaves in input mode (in `models/operations/.ts`). +- **Path** params are ULIDs → `string`. +- **Shared-route JSON body override** → a `@sharedRoute` endpoint declares one + operation per content type (e.g. `events.ingest`: a single-event + `cloudevents+json`, a batch `cloudevents-batch+json`, and a single-or-batch + `application/json` union). `collectHttpOperations` keeps the **first** variant + (for its doc/summary/response/202), which is the single-event one — so without + intervention the request body would be `EventInput` only. `jsonBodyOverrides` + (in `sdk-operations.ts`) maps such an endpoint to its `application/json` body + type when that differs from the kept variant's; `request-types.ts` then renders + the body with `tsTypeOf(..., 'input')` (→ `EventInput | EventInput[]`) instead + of a single named-interface import. Trigger is narrow (only ingest today); the + func/facade are unchanged — `json: req` serializes an object or array + identically, so widening only the request **type** is sufficient. + +Two traps the generator handles: + +- **Name collision**: the op request type `Request` collides with a body + model interface of the same name (e.g. `CreateMeterRequest`). The body is + imported under a `Body` alias so the local request declaration owns the + name (`import type { CreateMeterRequest as CreateMeterRequestBody }`). +- **Coerced leaves**: `z.input` of a `z.coerce.*` leaf is the loose `unknown` + (zod 4). The emitted input type deliberately keeps the **strict** leaf + (`bigint`/`number`/…) rather than propagate the `unknown` wart. So input + variants and `…Query` types are guarded **one-directionally** + (`[XInput] extends [z.input<…>]` — "is a valid input"), not bidirectionally. + Output interfaces keep the full bidirectional guard. The `…Query` guards live + in a sibling `models/operations/.assert.ts`, matching how model guards live + in `types.assert.ts`. + +**Selection is unguarded by the shipped guards — verify it separately.** A +too-strict request type (refing the output `X` where `XInput` was needed) still +satisfies the one-directional `[X] extends [z.input]`, so the shipped guards +can't catch picking the wrong variant or `computeDivergentModels` under-marking. +Two independent checks close this: + +- The 20 conformance tests construct real requests (end-to-end). +- **Coverage probe** (the authoritative recipe — do NOT use a regex reachability + tracer; it false-matches identifiers inside `.regex(/…/)` and `.describe()`): + for every model reachable from a `*Body` schema that has an output interface, + assert `[X] extends [z.input]`. If `X` is too strict (an + `XInput` was needed but missing), this fails. Run it as a temporary probe file + compiled by tsc; zero failures = every request-reachable model is covered. + +### Dual surface + +Every operation exists twice: a standalone func in `funcs/` returning +`Result` (tree-shakeable, non-throwing) and a thin method on the namespace +façade in `sdk/` that `unwrap`s and throws. Both call the same func. + +### Pagination companions (`All`) + +Every page-number or cursor **list** operation gets a companion facade method +— `All` alongside `` (e.g. `client.meters.listAll()` next to +`client.meters.list()`) — that returns `AsyncIterable` and fetches +following pages lazily as the iterable is consumed. This is purely additive: +existing `list()`/`funcs.listX()` signatures and behavior are untouched; only +the facade layer (`sdk-files.ts`) gains the extra method. No standalone-func +equivalent is emitted — the companion is facade-only, matching the "thin +codegen, shared runtime" split below. + +**Detection is structural, by AST node identity, not by name.** Both +pagination styles are TypeSpec generic response templates in +`shared/responses.tsp`: `Shared.PagePaginatedResponse` (`meta: +Common.PageMeta`, i.e. `{ page: { number, size, total } }`) and +`Shared.CursorPaginatedResponse` (`meta: Common.CursorMeta`, i.e. `{ page: +{ next?, previous?, first?, last?, size? } }`). `pagination.ts` resolves +these two template declarations once per emit +(`program.getGlobalNamespaceType().namespaces.get('Shared')`, then +`.models.get('PagePaginatedResponse'|'CursorPaginatedResponse')`) and matches +each operation's success response envelope (`successResponseEnvelope`, +exported from `sdk-operations.ts`) against them by `.node` identity — every +instantiation of a TypeSpec generic model shares the declaration's syntax +node, so this is exact regardless of the instantiation's own +(`@friendlyName`-interpolated) name. `getPagingOperation`/`@pageItems` from +`@typespec/compiler` was evaluated and rejected: in this spec `@pageItems` is +the only paging decorator actually used, so it can confirm "this operation is +paginated" but cannot distinguish the two styles — node identity subsumes it +and is the only structural signal that does distinguish them. The item type +`T` comes from `envelope.templateMapper.args[0]`, resolved to its documented +interface name via the same `resolveInterface` every other response uses — an +item type with no documented interface (should never happen for a real list +op) gets no companion rather than an untyped one. `Shared` is looked up by +name because TypeSpec has no other way to name "the two templates this +emitter builds pagination around" (same precedent as `SPLIT_BY_INTERFACE`); +the per-operation match itself is never name-based. + +**Runtime helpers, not per-operation loop bodies.** The iteration logic lives +once in `templates/runtime/paginate.ts` → generated `src/lib/paginate.ts`: +`paginatePages` advances `request.page.number`, stopping on a page shorter +than the server's own reported `meta.page.size` (including an empty page) or +once the running item count reaches `meta.page.total`; `paginateCursor` +follows `meta.page.next` — an **opaque cursor token** fed back verbatim as +`page.after` (despite `next`/`previous`/`first`/`last` carrying a `format: +uri` annotation in the spec — confirmed against the server's own handlers, +e.g. `api/v3/handlers/customers/credits/list_transactions.go`: "We +intentionally expose opaque cursor tokens instead of URI links" — do not +"fix" this by having the helper fetch `next` as a URL). Both helpers accept a +generic `fetchPage: (req, options) => Promise>` and unwrap +each page internally (facades throw `HTTPError`, matching every other +facade method), cap iteration at `MAX_PAGINATION_PAGES` (10,000) and throw +`PaginationLimitExceededError` rather than loop forever on a misbehaving +server (mirroring `DepthLimitExceededError` in `wire.ts`), and forward the +caller's `RequestOptions` (including `signal`) to every page fetch. The +generated companion only wires the right helper to the right func, binding +`this._client` in a closure — `sdk-files.ts`'s `emitPaginationMethod`; no +per-operation loop code is emitted. `PaginationLimitExceededError` is +exported from the package root (`indexFile` in `sdk-files.ts`) alongside the +other typed runtime errors. + +Coverage: `paginate.ts` joins `wire.ts` in the generated package's +`vitest.config.ts` coverage `include` at the same 100% +statement/function/line threshold (85% branch, matching `wire.ts`) — it has +no compile-time guard either, so its behavior must be covered entirely by +`tests/paginate.spec.ts` (both helpers: multi-page iteration, early-break +fires no extra requests, empty/short/exact-total page termination, absent- +next-cursor termination, filter/sort/page-size preserved across pages, +`AbortSignal` propagation, and the `PaginationLimitExceededError` cap for +both styles — the cap tests drive `paginatePages`/`paginateCursor` directly +with an in-memory stub `fetchPage`, not through `fetch-mock`, so 10,000 +iterations stay fast). + +### Method/function JSDoc + +Every emitted facade method (`sdk/*.ts`) and standalone function (`funcs/*.ts`) +carries a JSDoc comment, built by `operationJsDoc` in `sdk-operations.ts`: the +`@summary` decorator text (`SdkOperation.summary`, short one-liner) followed by +the `@doc` description body (`SdkOperation.doc`, longer prose) when it differs +from the summary, and always a final line naming the HTTP route +(`POST /openmeter/meters`). The route line is unconditional, so every operation +gets a useful IDE hover even the rare one with neither a TypeSpec `@doc` nor a +`@summary` — the generator never emits a hollow JSDoc block. Summary and +description appear only when the TypeSpec source declares them; the generator +never fabricates prose, so a method whose JSDoc lacks a description is a +spec-authoring gap (add `@doc` to the operation), not an emitter bug. `*Input` variant +interfaces in `models/types.ts` (`interface-types.ts`) inherit the base +interface's doc comment verbatim (no doc on the base → none on the variant). +The shared `jsdoc()` helper (`utils.tsx`) escapes any literal `*/` in +doc/summary text so it cannot prematurely close the emitted comment; do not +bypass this helper when adding new doc-emitting call sites. + +### README + +`readme.ts` emits the package `README.md` at the package root (`emitter-output-dir` +is the package root, so non-`src/` paths land there; `package.json`/`tests/` +survive because `writeOutput` only writes listed paths). It is built from the +same grouped `SdkOperation[]` as the SDK files, in `groupOperations` insertion +order (matching `index.ts`), so the "Available Resources and Operations" table's +call paths (`getter` + `nestPath` + `methodName`, e.g. `customers.credits.grants.create`), +HTTP routes, and per-op summaries (`$.type.getDoc(op)`, carried on `SdkOperation.doc`) +always equal the emitted client. The install/import package name comes from the +**required** `package-name` emitter option (`context.options['package-name']`, +declared in `lib.ts` with `required: ['package-name']` and set in `aip/tspconfig.yaml`) +— never hardcode it in `readme.ts`, and there is no fallback: omitting the option +fails the whole compile with an `invalid-schema` diagnostic (verified by removing +it from tspconfig), so a missing name can never leak `undefined` into the README. +The example client variable is `client` (matching the table prefix `client.`); +if you rename it, update both the fence declarations and `operationsTable`'s prefix +together. The table-of-contents anchors and the headings +are produced by one `slug()` so TOC links never break. Every code fence is +self-contained (constructs its own `client`) and typechecks against the real +generated types; the `meters.create` payload uses the camelCase public surface +(`eventType`, `valueProperty`) and the lowercase aggregation enum (`'sum'`), +matching `CreateMeterRequest`. The README is emitted raw (compact markdown +tables); the generated `aip-client-javascript` output and the emitter's own +`typespec-typescript/src` are **not** prettier-clean on HEAD (`prettier --check .` +is already red for both subtrees), so do not pre-align tables in the emitter or +single out the README in `.prettierignore`. + +### RequestOptions is curated + +`RequestOptions = Pick`. +Do not widen it to the full ky `Options` — exposing `searchParams`/`json`/`hooks`/ +`fetch`/`prefix` per call lets callers clobber transport internals. + +### Errors + +`toError` maps ky failures to the domain `HTTPError` (RFC7807 `problem+json`, +charset-tolerant Content-Type match; status-only fallback otherwise). `Result`'s +error type stays `Error` — the ky fork also throws `TimeoutError`/`NetworkError`, +so narrowing to `HTTPError` would be unsound. Callers narrow with +`instanceof HTTPError`. A single `HTTPError` class (no per-status hierarchy); +field-level validation errors are reachable via `getField('invalid_parameters')`. + +### Server URL templating + +`baseUrl` is **required** (no default). It may be a `ServerList` template with +`{region}`/`{port}` variables resolved via `encodePath(baseUrl, serverVariables)`, +a concrete URL, or a `URL` object. `region` is typed to the enumerated `Regions`. +Missing template variables throw (fail-loud, never a literal `{region}` on the +wire). The SDK owns URL construction: it pins `baseUrl` (trailing-slash +normalized) and `prefix: undefined` **after** spreading user options so a +user-supplied `prefix` cannot redirect requests; the auth hook is appended +**after** user `beforeRequest` hooks so SDK auth wins. + +### ky is a fork — preserve its option names + +The vendored `ky` uses `baseUrl`/`prefix`/`totalTimeout`/`retryOnTimeout` (not +mainline ky's `prefixUrl`). The emitter's runtime must use the fork's names; do +not "correct" them to mainline ky. + +## Query serialization (verified against the server) + +`api/v3/filters/parse.go` is the source of truth for filter encoding: + +- deep objects: `page[size]`, `filter[key][eq]` (bracketed) +- scalar `filter[key]=v` is shorthand for `filter[key][eq]=v` +- array operands (`oeq`/`ocontains`) are **comma-joined into one param**; the + server **rejects repeated** query params. Never emit `k=a&k=b`. +- `sort` serializes to a plain string `" [asc|desc]"` (single space) on the + wire; the SDK accepts a `{by, order}` object and `encodeSort` flattens it. `by` is + a **camelCase** field name in the SDK and is `toSnakeCase`-translated to the wire + field name (the server validates snake field names; see + `api/v3/handlers/.../convert.go`). Every query parameter named `sort` must use + `Common.SortQuery` directly; the AIP `sort-query-type` rule protects the + name-based codec selection used by both SDK emitters. + +## Tests + +The conformance tests (Vitest + `@fetch-mock/vitest`, matching the legacy SDK's +stack) live under `typespec-typescript/templates/tests/` and are emitted into +the generated SDK by `runtime-templates.ts`. They are the generator's spec: it +is "done" when these tests pass against the emitted `aip-client-javascript` +output. + +`pnpm run test:sdk` roots at `packages/aip-client-javascript` and runs the +**generated** tests against the **generated** SDK, so `generate` followed by +`test:sdk` is fully self-contained. The generated package is never +hand-edited; to change the runtime or tests, edit the files under +`typespec-typescript/templates/` and re-run `generate` (see the layout note +above). + +Vitest strips types without checking them, so the package `typecheck` script +runs twice: `tsc --noEmit` (the build tsconfig, `src/` only, keeps declaration +diagnostics) and `tsc -p tsconfig.tests.json` (adds `tests/`, no emit, +`skipLibCheck` because `@fetch-mock/vitest`'s own d.ts imports the undeclared +jest `expect` package). Without the second run, test files are never +type-checked by any gate — type-level probes placed in `tests/` prove nothing. +`tsconfig.tests.json` is hand-maintained at the package root (like +`package.json`/`vitest.config.ts`, it survives regeneration) and is +`.npmignore`d. + +The meters namespace is behaviorally verified end-to-end by these 19 tests. The +other namespaces are generated and type-checked (`tsc` clean across all 13) but +not yet behaviorally tested — add a smoke test per namespace if broader runtime +coverage is wanted. + +### Emitter-level tests (in-memory compile harness) + +`typespec-typescript/test/emit.ts` builds an `EmitterTester` with +`createTester` from `@typespec/compiler/testing`: it compiles a fixture +TypeSpec program in-memory, runs the emitter through the compiler's real emit +pipeline, and returns the emitted files as `outputs: Record` +(paths relative to the emitter output dir, e.g. `src/sdk/internal.ts`). Use it +to pin generator behavior that should be caught before regenerating the real +client — `test/internal-surface.test.ts` (the x-private/x-internal routing to +the `client.internal.*` surface) is the model. Constraints: + +- The tester resolves the emitter by its package name through `package.json` + exports, i.e. it runs the **built** `dist/` — the package `test` script runs + `alloy build` first for exactly this reason. A stale manual `vitest` run + tests stale code. +- Fixture specs must author operations via the same `extends` pattern the real + spec uses (`interface Endpoints extends Domain.Operations {}` inside a + `@service` namespace) or grouping falls into `ungrouped-operation`. + Pagination detection requires a top-level `Shared` namespace declaring + `PagePaginatedResponse`/`CursorPaginatedResponse`. +- The harness is what surfaced the unawaited-`writeOutput` race in + `$onEmit`: the tsp CLI keeps the process alive past the pending writes, but + in-memory compilation returns immediately, observing a partial output dir. + Keep `writeOutput` awaited. + +`make -C api/spec test` runs `pnpm --filter @openmeter/typespec-typescript run +check` (typecheck + these tests) alongside `test:sdk:coverage`, and the +`aip-npm-release` workflow runs that target before publishing. + +## Go SDK emitter + +### Output and wiring + +- `typespec-go` emits a single-package Go SDK (`package openmeter`) into + `api/v3/client` at the **repo root** — not under `api/spec/packages/`. It is + a standalone nested Go module, `github.com/openmeterio/openmeter/api/v3/client`, + with its own `go.mod`/`go.sum` (sole dependency: + `github.com/oapi-codegen/nullable`). The root `go test ./...` never reaches + it; use `make test-go-sdk` at the repo root. +- Wiring lives in `packages/aip/tspconfig.yaml` under `@openmeter/typespec-go`: + `emitter-output-dir: '{output-dir}/../../../v3/client'` plus the options + `module-path`, `package-name: 'openmeter'`, `include-services: ['OpenMeter']`, + `strip-name-prefixes`, and `readme-note`. `sdk-version` is deliberately not + set there, so day-to-day regeneration stamps the `0.0.0-dev` placeholder; the + release process sets it (see Releases below). The full option surface is + declared in `typespec-go/src/lib.ts`. +- Never hand-edit generated files in `api/v3/client`. Change `typespec-go` + emitter components or `src/runtime-templates.ts`, then regenerate. The output + cleaner deletes previously generated entries before emission (so file renames + cannot leave duplicate declarations) but preserves `*_test.go` files and + `testdata/`: hand-written Go wire tests live in `api/v3/client` alongside the + generated files and survive regeneration. +- Grouping and nesting follow the same TypeSpec source-namespace rules as the + TypeScript SDK. Public Go names use PascalCase fields and methods with + `json:"snake_case"` tags; there is no runtime casing mapper. +- Static Go runtime files live as reviewable TypeScript template strings in + `typespec-go/src/runtime-templates.ts`. Do not place Go files, `go.mod`, or + `go.sum` under a `typespec-go/runtime/` directory; that makes the emitter + source tree look like a standalone Go package. +- Every generated `.go` file carries the + `// Code generated by @openmeter/typespec-go. DO NOT EDIT.` header **before** + the package clause, and generation gofmt-formats the output (a runnable + `gofmt` on PATH is a hard requirement of generation). + +### Model projection rules + +- Model emission is payload-context aware. The response reachability walk + filters properties by `Lifecycle.Read` visibility, so create-only fields do + not leak into read models. A model reachable only from requests emits its + input projection under its natural name (e.g. `CreateMeterRequest`); a model + reachable from both requests and responses emits one declaration when the + projections agree, or a read declaration plus an `Input` twin when they + diverge (e.g. `Event` and `EventInput`). See `src/projections.ts`. +- Structural dedupe collapses visibility-projection twins onto canonical types: + a `Create`/`Update`/`Upsert`-prefixed declaration whose rendered shape is + structurally identical to another emitted declaration is dropped and every + reference is redirected to the canonical name, so read-modify-write flows + need no type mapping (`computeStructuralAliases` in `src/projections.ts`). +- Anonymous inline models are promoted to deterministic names derived from the + enclosing type plus field (`SubscriptionCreate.customer` → + `SubscriptionCreateCustomer`); a promoted-name collision is a generation + error, resolved with `@friendlyName`. +- Named `*FieldFilter` unions (the `StringFieldFilter` family) are + runtime-backed: an exact-name map in `src/go-types.tsx` + (`runtimeFilterTypesByUnionName`) resolves them to the static runtime filter + types (`StringFilter`, `StringExactFilter`, `DateTimeFilter`, `NumericFilter`, + `BooleanFilter`), and they are excluded from the model reachability walk so + their variants never emit dead declarations. An unmapped `*FieldFilter` union + name fails generation instead of guessing. +- Formatless TypeSpec `integer` (and `safeint`) map to `int64`; neither fits a + narrower sized Go integer by declaration. + +### Wire-shape rules + +- Shared-route representations are retained when media type or body shape + differs. Events ingest intentionally emits `Events.IngestEvent`, + `Events.IngestEvents`, and `Events.IngestEventsJSON`, each with its own + request `Content-Type`. Response-only siblings such as meter CSV can reuse the + JSON request body while keeping a distinct response `Accept`. +- TypeSpec `T | null` emits value-typed `Nullable[T]` backed by + `github.com/oapi-codegen/nullable`, not `*Nullable[T]`. Optional nullable + fields rely on `omitempty` for the unspecified state while still preserving + explicit `null` and concrete values on marshal/unmarshal. +- Optional maps and slices in request input models emit as pointers + (`*map[...]...`, `*[]...`) so callers can distinguish omission from an explicit + empty object/array. Keep this input-only through the projection rules above + so response models remain ergonomic value maps/slices. +- Go string enum constants stay prefixed as `` and every generated + enum exposes `Valid() bool`; unknown wire values must still decode and + re-encode unchanged for forward compatibility. +- Union wrappers are raw-preserving: `UnmarshalJSON` and `MarshalJSON` copy the + payload with cloned buffers (`append([]byte(nil), ...)`), the zero-value + union marshals as JSON `null`, and unknown discriminator values round-trip + unchanged. `From` constructors stamp the variant's + discriminator field before marshaling, keeping request construction ergonomic + without weakening unknown-discriminator round-tripping. +- `All` iterator methods are emitted only for list responses with the + canonical `{data, meta}` page envelope. A paginated response carrying any + extra top-level field gets only the plain method returning the full envelope, + because the iterator surfaces page elements alone. + +### Releases + +- The `sdk-version` emitter option stamps `const Version` in + `api/v3/client/option.go` (also the default `User-Agent` version); it + defaults to `0.0.0-dev`. +- A release is an `api/v3/client/vX.Y.Z` git tag (`-dev.N`/`-beta.N` prerelease + suffixes are also accepted). `.github/workflows/release-go-sdk.yaml` gates + the tag: it verifies the stamped `Version` constant matches the tag version, + runs `make test-go-sdk`, and creates a GitHub release for visibility. +- Release steps: set `sdk-version` under the `@openmeter/typespec-go` options + in `packages/aip/tspconfig.yaml`, regenerate (`make gen-api`), commit the + stamped output, then push the matching `api/v3/client/vX.Y.Z` tag. + +### Verification + +Verify Go emitter changes with (first two from `api/spec`, third from the repo +root): + +```bash +pnpm --filter @openmeter/typespec-go run check +pnpm --filter @openmeter/api-spec-aip run generate # or: make gen-api (repo root) +(cd api/v3/client && gofmt -l . && go build ./... && go vet ./... && go test ./...) +``` + +`make test-go-sdk` at the repo root is the build/vet/test part of the last +line. In CI, the `generators-openapi` job runs the generated-output drift check +(`make update-openapi` + clean git diff) and the emitter's `check` script, and +the `go-sdk` job runs `make test-go-sdk`. diff --git a/api/spec/Makefile b/api/spec/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..ae4ec740671294126bc8032cb28e38ca55ce2cb8 --- /dev/null +++ b/api/spec/Makefile @@ -0,0 +1,84 @@ +# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html + +.PHONY: generate +generate: ## Generate OpenAPI spec + $(call print-target) + pnpm --frozen-lockfile install + pnpm generate + # Replace inline filter definitions with $ref to common/definitions/aip_filters.yaml + @AIP_REF="../../../../common/definitions/aip_filters.yaml#/components/schemas"; \ + FILE="packages/aip/output/definitions/metering-and-billing/v3/openapi.MeteringAndBilling.yaml"; \ + for schema in SortQuery BooleanFieldFilter NumericFieldFilter StringFieldFilter StringFieldFilterExact DateTimeFieldFilter LabelsFieldFilter; do \ + if yq -e ".components.schemas | has(\"$$schema\")" "$$FILE" > /dev/null 2>&1; then \ + REF_VAL="$$AIP_REF/$$schema" SCHEMA="$$schema" yq -i '.components.schemas[strenv(SCHEMA)] = {"$$ref": strenv(REF_VAL)}' "$$FILE"; \ + fi; \ + done + # Prefix addon operationIds with `product-catalog-` for the v3 MeteringAndBilling output + @FILE="packages/aip/output/definitions/metering-and-billing/v3/openapi.MeteringAndBilling.yaml"; \ + for op in list-addons create-addon update-addon get-addon delete-addon archive-addon publish-addon; do \ + new_op="$$(printf '%s' "$$op" | sed 's/-addon/-product-catalog-addon/')"; \ + OLD_OP="$$op" NEW_OP="$$new_op" yq -i '(.paths[][] | select(.operationId == strenv(OLD_OP)) | .operationId) = strenv(NEW_OP)' "$$FILE"; \ + done + # Strip Go codegen vendor extensions from the v3 MeteringAndBilling output + @FILE="packages/aip/output/definitions/metering-and-billing/v3/openapi.MeteringAndBilling.yaml"; \ + yq -i 'del(.. | select(has("x-go-type"))["x-go-type"], .. | select(has("x-go-type-import"))["x-go-type-import"])' "$$FILE" + pnpm --filter @openmeter/api-spec-aip exec openapi bundle output/definitions/metering-and-billing/v3/openapi.OpenMeter.yaml -o ../../../v3/openapi.yaml + cp packages/legacy/output/openapi.OpenMeter.yaml ../openapi.yaml + cp packages/legacy/output/openapi.OpenMeterCloud.yaml ../openapi.cloud.yaml + cp packages/aip/output/definitions/metering-and-billing/v3/openapi.Test.yaml ../v3/test/openapi.test.yaml + +.PHONY: test +test: ## Run AIP TypeScript SDK and emitter tests + $(call print-target) + pnpm --frozen-lockfile install + pnpm --filter @openmeter/api-spec-aip run test + pnpm run test:sdk:coverage + pnpm --filter @openmeter/typespec-typescript run check + +.PHONY: publish-aip-sdk +publish-aip-sdk: ## Publish the AIP TypeScript SDK (@openmeter/client) to npm + $(call print-target) + @if [ -z "$$AIP_SDK_RELEASE_VERSION" ]; then \ + echo "ERROR: AIP_SDK_RELEASE_VERSION is required"; \ + echo "Usage: AIP_SDK_RELEASE_VERSION=1.2.3 make publish-aip-sdk [AIP_SDK_RELEASE_TAG=beta]"; \ + exit 1; \ + fi + + @if [ -z "$$AIP_SDK_RELEASE_TAG" ]; then \ + echo "ERROR: AIP_SDK_RELEASE_TAG is required"; \ + echo "Usage: AIP_SDK_RELEASE_VERSION=1.2.3 make publish-aip-sdk [AIP_SDK_RELEASE_TAG=beta]"; \ + exit 1; \ + fi + + pnpm --frozen-lockfile install + + cd packages/aip-client-javascript && \ + pnpm version "$${AIP_SDK_RELEASE_VERSION}" --no-git-tag-version && \ + node -e "const fs=require('node:fs');const p='src/lib/version.ts';const v=process.env.AIP_SDK_RELEASE_VERSION;const src=fs.readFileSync(p,'utf8');const out=src.replace(/SDK_VERSION = '[^']*'/, \"SDK_VERSION = '\" + v + \"'\");if(out===src){throw new Error('SDK_VERSION pattern not found in '+p)}fs.writeFileSync(p, out)" && \ + CACHE_BUSTER="$$(date --rfc-3339=seconds)" pnpm publish --no-git-checks --access public --tag "$${AIP_SDK_RELEASE_TAG}" + @echo "✅ Published $${AIP_SDK_RELEASE_TAG} AIP TypeScript SDK (@openmeter/client) version $${AIP_SDK_RELEASE_VERSION} with tag $${AIP_SDK_RELEASE_TAG}" + +.PHONY: lint +lint: ## Lint OpenAPI spec + $(call print-target) + pnpm --frozen-lockfile install + pnpm lint + +.PHONY: format +format: ## Format OpenAPI spec + $(call print-target) + pnpm --frozen-lockfile install + pnpm format + +.PHONY: help +.DEFAULT_GOAL := help +help: + @grep -h -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' + +# Variable outputting/exporting rules +var-%: ; @echo $($*) +varexport-%: ; @echo $*=$($*) + +define print-target + @printf "Executing target: \033[36m$@\033[0m\n" +endef diff --git a/api/spec/README.md b/api/spec/README.md new file mode 100644 index 0000000000000000000000000000000000000000..469e54abf3818bc29e066038d77bc680e440e101 --- /dev/null +++ b/api/spec/README.md @@ -0,0 +1,25 @@ +# OpenMeter API specs + +This workspace contains two TypeSpec packages that generate OpenAPI specs: + +| Package | Description | Output | +| ------------------------------ | ------------------------------------------------------------- | ------------------------------------------------------- | +| **Legacy** (`packages/legacy`) | OpenMeter API (v1-v2) and OpenMeter Cloud API | `openapi.OpenMeter.yaml`, `openapi.OpenMeterCloud.yaml` | +| **AIP** (`packages/aip`) | OpenMeter and Konnect metering & billing APIs (v3), AIP-style | `openapi.MeteringAndBilling.yaml` (OpenMeter + Konnect) | + +From the repo root, run `make gen-api` (or `make -C api/spec generate`) to build both packages and copy/bundle artifacts into `api/`. + +--- + +## Legacy API (`packages/legacy`) + +Legacy specs follow OpenMeter’s existing TypeSpec conventions. See [`packages/legacy/README.md`](packages/legacy/README.md) for patterns and guidelines. + +--- + +## AIP (`packages/aip`) + +The AIP package defines v3 metering and billing APIs in line with [Kong’s AIP (API Improvement Proposals)](https://kong-aip.netlify.app/list/). + +- **OpenMeter** (`openmeter.tsp`): OpenMeter v3 API. +- **Konnect** (`konnect.tsp`): Konnect metering & billing API, same surface with Konnect-specific auth and servers. diff --git a/api/spec/package.json b/api/spec/package.json new file mode 100644 index 0000000000000000000000000000000000000000..48ba2f43d9209d157a857ed9a60e46312d908ebf --- /dev/null +++ b/api/spec/package.json @@ -0,0 +1,29 @@ +{ + "name": "@openmeter/api-spec", + "version": "0.1.0", + "type": "module", + "scripts": { + "build": "pnpm --filter @openmeter/typespec-typescript run build && pnpm --filter @openmeter/typespec-go run build", + "generate": "pnpm run build && pnpm --filter @openmeter/api-spec-legacy run generate && pnpm --filter @openmeter/api-spec-aip run generate && pnpm run format", + "format": "prettier --list-different --find-config-path --write . && pnpm --filter @openmeter/api-spec-aip run format", + "lint": "prettier --check . && pnpm --filter @openmeter/api-spec-legacy run lint && pnpm --filter @openmeter/api-spec-aip run lint && pnpm --filter @openmeter/client run typecheck", + "lint:fix": "prettier --write .", + "test:sdk": "vitest --run --root packages/aip-client-javascript", + "test:sdk:coverage": "vitest --run --coverage --root packages/aip-client-javascript" + }, + "devDependencies": { + "@fetch-mock/vitest": "0.2.18", + "@typespec/prettier-plugin-typespec": "1.12.0", + "@vitest/coverage-v8": "4.1.8", + "prettier": "3.8.3", + "vitest": "4.1.8" + }, + "exports": { + "./openapi.yaml": "./packages/legacy/output/openapi.OpenMeterCloud.yaml", + "./openapi.cloud.yaml": "./packages/legacy/output/openapi.OpenMeterCloud.yaml", + "./openapi.legacy.yaml": "./packages/legacy/output/openapi.OpenMeter.yaml", + "./v3/openapi.yaml": "./packages/aip/output/definitions/metering-and-billing/v3/openapi.MeteringAndBilling.yaml" + }, + "private": true, + "packageManager": "pnpm@11.1.2+sha512.415a1cc25974731e75455c1468371be74c5aa5fb7621b50d4056d222451609f11412f23fd602e6169f1e060466641f798597e1be961a10688836a67b16569499" +} diff --git a/api/spec/packages/aip/common/definitions/aip_filters.yaml b/api/spec/packages/aip/common/definitions/aip_filters.yaml new file mode 100644 index 0000000000000000000000000000000000000000..80aaa3fe049b6e72e5fa02603999aa69f5f3b7a8 --- /dev/null +++ b/api/spec/packages/aip/common/definitions/aip_filters.yaml @@ -0,0 +1,300 @@ +components: + schemas: + BooleanFieldFilter: + title: BooleanFieldFilter + description: Filter by a boolean value (true/false). + type: boolean + x-examples: + example-1: true + NumericFieldFilter: + description: Filter by a numeric value. + oneOf: + - type: number + description: Value strictly equals the given numeric value. + example: 21 + - type: object + title: NumericFieldEqualsFilter + additionalProperties: false + properties: + eq: + type: number + description: Value strictly equals the given numeric value. + example: 3.14 + required: [eq] + - type: object + title: NumericFieldLTFilter + additionalProperties: false + properties: + lt: + type: number + description: Value is less than the given numeric value. + example: 10 + required: [lt] + - type: object + title: NumericFieldLTEFilter + additionalProperties: false + properties: + lte: + type: number + description: Value is less than or equal to the given numeric value. + example: 10 + required: [lte] + - type: object + title: NumericFieldGTFilter + additionalProperties: false + properties: + gt: + type: number + description: Value is greater than the given numeric value. + example: 1.85 + required: [gt] + - type: object + title: NumericFieldGTEFilter + additionalProperties: false + properties: + gte: + type: number + description: Value is greater than or equal to the given numeric value. + example: 1.85 + required: [gte] + x-examples: + numeric_field_1: 11 + numeric_field_2: + eq: 11 + numeric_field_3: + lt: 15.85 + numeric_field_4: + lte: 15.85 + numeric_field_5: + gt: 3.14 + numeric_field_6: + gte: 3.14 + SortQuery: + title: SortQuery + type: string + example: 'created_at desc' + description: | + The `asc` suffix is optional as the default sort order is ascending. + The `desc` suffix is used to specify a descending order. + Multiple sort attributes may be provided via a comma separated list. + JSONPath notation may be used to specify a sub-attribute (eg: 'foo.bar desc'). + UuidFieldFilter: + title: UuidFieldFilter + description: Filters on the given UUID field value by exact match. + oneOf: + - $ref: '#/components/schemas/StringFieldEqualsFilter' + - $ref: '#/components/schemas/StringFieldOEQFilter' + - $ref: '#/components/schemas/StringFieldNEQFilter' + x-examples: + example-1: '3bbfd3a-e9ab-48a9-9881-ed589e4615d1' + example-2: + eq: '3bbfd3a-e9ab-48a9-9881-ed589e4615d1' + example-3: + oeq: '3bbfd3a-e9ab-48a9-9881-ed589e4615d1' + example-4: + neq: '3bbfd3a-e9ab-48a9-9881-ed589e4615d1' + StringFieldFilter: + title: StringFieldFilter + description: Filters on the given string field value by either exact or fuzzy match. + oneOf: + - $ref: '#/components/schemas/StringFieldEqualsFilter' + - $ref: '#/components/schemas/StringFieldContainsFilter' + - $ref: '#/components/schemas/StringFieldOContainsFilter' + - $ref: '#/components/schemas/StringFieldOEQFilter' + - $ref: '#/components/schemas/StringFieldNEQFilter' + x-examples: + example-1: 'equals-some-value' + example-2: + eq: 'some-value' + example-3: + contains: 'some-value' + example-4: + ocontains: 'some-potential,value' + example-5: + oeq: 'some-potential,value' + example-6: + neq: 'not-this-value' + StringFieldFilterExact: + title: StringFieldFilterExact + description: Filters on the given string field value by exact match. + oneOf: + - $ref: '#/components/schemas/StringFieldEqualsFilter' + - $ref: '#/components/schemas/StringFieldOEQFilter' + - $ref: '#/components/schemas/StringFieldNEQFilter' + x-examples: + example-1: 'equals-some-value' + example-2: + eq: 'some-value' + example-3: + oeq: 'some-potential,value' + example-4: + neq: 'not-this-value' + StringFieldEqualsFilter: + title: StringFieldEqualsFilter + description: Filters on the given string field value by exact match. + oneOf: + - type: string + - type: object + title: StringFieldEqualsComparison + additionalProperties: false + properties: + eq: + type: string + required: [eq] + x-examples: + example-1: 'equals-some-value' + example-2: + eq: 'some-value' + StringFieldContainsFilter: + title: StringFieldContainsFilter + description: Filters on the given string field value by fuzzy match. + type: object + additionalProperties: false + properties: + contains: + type: string + required: [contains] + x-examples: + example-1: + contains: 'some-value' + StringFieldOContainsFilter: + title: StringFieldOContainsFilter + description: Returns entities that fuzzy-match any of the comma-delimited phrases in the filter string. + type: object + additionalProperties: false + properties: + ocontains: + type: string + required: [ocontains] + x-examples: + example-1: + ocontains: 'this-value,or-that-value' + StringFieldOEQFilter: + title: StringFieldOEQFilter + description: Returns entities that exact match any of the comma-delimited phrases in the filter string. + type: object + additionalProperties: false + properties: + oeq: + type: string + required: [oeq] + x-examples: + example-1: + oeq: 'some-value,some-other-value' + StringFieldNEQFilter: + title: StringFieldNEQFilter + description: Filters on the given string field value by exact match inequality. + type: object + additionalProperties: false + properties: + neq: + type: string + required: [neq] + x-examples: + example-1: + neq: 'not-this-value' + DateTimeFieldFilter: + title: DateTimeFieldFilter + description: Filters on the given datetime (RFC-3339) field value. + oneOf: + - type: string + title: DateTimeFieldImplicitEqualsFilter + format: date-time + description: Value strictly equals given RFC-3339 formatted timestamp in UTC + example: 2022-03-30T07:20:50Z + - type: object + title: DateTimeFieldEqualsFilter + additionalProperties: false + properties: + eq: + type: string + format: date-time + description: Value strictly equals given RFC-3339 formatted timestamp in UTC + example: 2022-03-30T07:20:50Z + required: [eq] + - type: object + title: DateTimeFieldLTFilter + additionalProperties: false + properties: + lt: + type: string + format: date-time + description: Value is less than the given RFC-3339 formatted timestamp in UTC + example: 2022-03-30T07:20:50Z + required: [lt] + - type: object + title: DateTimeFieldLTEFilter + additionalProperties: false + properties: + lte: + type: string + format: date-time + description: Value is less than or equal to the given RFC-3339 formatted timestamp in UTC + example: 2022-03-30T07:20:50Z + required: [lte] + - type: object + title: DateTimeFieldGTFilter + additionalProperties: false + properties: + gt: + type: string + format: date-time + description: Value is greater than the given RFC-3339 formatted timestamp in UTC + example: 2022-03-30T07:20:50Z + required: [gt] + - type: object + title: DateTimeFieldGTEFilter + additionalProperties: false + properties: + gte: + type: string + format: date-time + description: Value is greater than or equal to the given RFC-3339 formatted timestamp in UTC + example: 2022-03-30T07:20:50Z + required: [gte] + x-examples: + datetime_field_1: '2022-03-30T07:20:50Z' + datetime_field_2: + eq: '2022-03-30T07:20:50Z' + datetime_field_3: + lt: '2022-03-30T07:20:50Z' + datetime_field_4: + lte: '2022-03-30T07:20:50Z' + datetime_field_5: + gt: '2022-03-30T07:20:50Z' + datetime_field_6: + gte: '2022-03-30T07:20:50Z' + LabelsFieldFilter: + allOf: + - title: LabelsFieldFilter + description: | + Filters on the resource's `labels` field. Filters must use dot-notation to identify + the label key that will be used to filter the results. For example: + - `filter[labels.owner]` + - `filter[labels.owner][neq]=kong` + - `filter[labels.env]=dev` + - `filter[labels.env][ocontains]=dev,test` + - $ref: '#/components/schemas/StringFieldFilter' + PublicLabelsFieldFilter: + x-flatten-allOf: true + allOf: + - title: PublicLabelsFieldFilter + description: | + Filters on the resource's `public_labels` field. Filters must use dot-notation to identify + the label key that will be used to filter the results. For example: + - `filter[public_labels.collection]` + - `filter[public_labels.collection][neq]=accounts` + - `filter[public_labels.collection]=accounts` + - `filter[public_labels.collection][ocontains]=accounts,invoices` + - $ref: '#/components/schemas/StringFieldFilter' + AttributesFieldFilter: + allOf: + - title: AttributesFieldFilter + description: | + Filters on the resource's `attributes` field. Filters must use dot-notation to identify + the attribute key that will be used to filter the results. For example: + - `filter[attributes.owner]` + - `filter[attributes.owner][neq]=kong` + - `filter[attributes.env]=dev` + - `filter[attributes.env][ocontains]=dev,test` + - $ref: '#/components/schemas/StringFieldFilter' diff --git a/api/spec/packages/aip/common/definitions/errors.yaml b/api/spec/packages/aip/common/definitions/errors.yaml new file mode 100644 index 0000000000000000000000000000000000000000..782042b4d01efd6a2c89a9e94b5f9c919de6c9b3 --- /dev/null +++ b/api/spec/packages/aip/common/definitions/errors.yaml @@ -0,0 +1,670 @@ +components: + responses: + ErrorResponse: + description: api error response + content: + application/problem+json: + schema: + oneOf: + - $ref: '#/components/responses/BadRequest' + - $ref: '#/components/responses/Unauthorized' + - $ref: '#/components/responses/Forbidden' + - $ref: '#/components/responses/NotFound' + - $ref: '#/components/responses/Conflict' + - $ref: '#/components/responses/Gone' + - $ref: '#/components/responses/Internal' + - $ref: '#/components/responses/NotAvailable' + discriminator: + propertyName: status + mapping: + '400': '#/components/responses/BadRequest' + '401': '#/components/responses/Unauthorized' + '403': '#/components/responses/Forbidden' + '404': '#/components/responses/NotFound' + '409': '#/components/responses/Conflict' + '410': '#/components/responses/Gone' + '500': '#/components/responses/Internal' + '503': '#/components/responses/NotAvailable' + # 400 + BadRequest: + description: Bad Request + content: + application/problem+json: + schema: + $ref: '#/components/schemas/BadRequestError' + KonnectCPLegacyBadRequest: + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/KonnectCPLegacyBadRequestError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/KonnectCPLegacyBadRequestExample' + # 401 + Unauthorized: + description: Unauthorized + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnauthorizedError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/UnauthorizedExample' + KonnectCPLegacyUnauthorized: + description: Unauthorized + content: + application/json: + schema: + $ref: '#/components/schemas/KonnectCPLegacyUnauthorizedError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/KonnectCPLegacyUnauthorizedExample' + # 403 + Forbidden: + description: Forbidden + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ForbiddenError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/ForbiddenExample' + KonnectCPLegacyForbidden: + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/KonnectCPLegacyForbiddenError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/KonnectCPLegacyForbiddenExample' + # 404 + NotFound: + description: Not Found + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotFoundError' + examples: + NotFoundExample: + $ref: '#/components/examples/NotFoundExample' + KonnectCPLegacyNotFound: + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/KonnectCPLegacyNotFoundError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/KonnectCPLegacyNotFoundExample' + # 409 + Conflict: + description: Conflict + content: + application/problem+json: + schema: + $ref: '#/components/schemas/ConflictError' + KonnectCPLegacyConflict: + description: Forbidden + content: + application/json: + schema: + $ref: '#/components/schemas/KonnectCPLegacyConflictError' + examples: + UnauthorizedExample: + $ref: '#/components/examples/KonnectCPLegacyConflictExample' + # 410 + Gone: + description: Gone + content: + application/problem+json: + schema: + $ref: '#/components/schemas/GoneError' + # 413 + PayloadTooLarge: + description: Payload Too Large + content: + application/problem+json: + schema: + $ref: '#/components/schemas/PayloadTooLargeError' + # 415 + UnsupportedMediaType: + description: Unsupported Media Type + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnsupportedMediaTypeError' + examples: + UnsupportedMediaTypeExample: + $ref: '#/components/examples/UnsupportedMediaTypeExample' + UnprocessableContent: + description: Unprocessable Content + content: + application/problem+json: + schema: + $ref: '#/components/schemas/UnprocessableContentError' + examples: + UnprocessableContentExample: + $ref: '#/components/examples/UnprocessableContentExample' + # 429 + TooManyRequests: + description: Too Many Requests + content: + application/problem+json: + schema: + $ref: '#/components/schemas/TooManyRequestsError' + # 500 + Internal: + description: Internal + content: + application/problem+json: + schema: + $ref: '#/components/schemas/InternalError' + # 503 + NotAvailable: + description: Service not available + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotAvailableError' + NotImplemented: + description: Not Implemented + content: + application/problem+json: + schema: + $ref: '#/components/schemas/NotImplementedError' + schemas: + InvalidRules: + description: invalid parameters rules + type: string + readOnly: true + nullable: true + enum: + - required + - is_array + - is_base64 + - is_boolean + - is_date_time + - is_integer + - is_null + - is_number + - is_object + - is_string + - is_uuid + - is_fqdn + - is_arn + - unknown_property + - missing_reference + - is_label + - matches_regex + - invalid + - is_supported_network_availability_zone_list + - is_supported_network_cidr_block + - is_supported_provider_region + - type + InvalidParameters: + type: array + nullable: false + uniqueItems: true + minItems: 1 + description: invalid parameters + items: + oneOf: + - $ref: '#/components/schemas/InvalidParameterStandard' + - $ref: '#/components/schemas/InvalidParameterMinimumLength' + - $ref: '#/components/schemas/InvalidParameterMaximumLength' + - $ref: '#/components/schemas/InvalidParameterChoiceItem' + - $ref: '#/components/schemas/InvalidParameterDependentItem' + InvalidParameterStandard: + type: object + additionalProperties: false + properties: + field: + type: string + example: name + readOnly: true + rule: + $ref: '#/components/schemas/InvalidRules' + source: + type: string + example: body + reason: + type: string + example: is a required field + readOnly: true + required: + - field + - reason + InvalidParameterMinimumLength: + type: object + additionalProperties: false + properties: + field: + type: string + example: name + readOnly: true + rule: + description: invalid parameters rules + type: string + readOnly: true + nullable: false + enum: + - min_length + - min_digits + - min_lowercase + - min_uppercase + - min_symbols + - min_items + - min + minimum: + type: integer + example: 8 + source: + type: string + example: body + reason: + type: string + example: must have at least 8 characters + readOnly: true + required: + - field + - reason + - rule + - minimum + InvalidParameterMaximumLength: + type: object + additionalProperties: false + properties: + field: + type: string + example: name + readOnly: true + rule: + description: invalid parameters rules + type: string + readOnly: true + nullable: false + enum: + - max_length + - max_items + - max + maximum: + type: integer + example: 8 + source: + type: string + example: body + reason: + type: string + example: must not have more than 8 characters + readOnly: true + required: + - field + - reason + - rule + - maximum + InvalidParameterChoiceItem: + type: object + additionalProperties: false + properties: + field: + type: string + example: name + readOnly: true + rule: + description: invalid parameters rules + type: string + readOnly: true + nullable: false + enum: + - enum + reason: + type: string + example: is a required field + readOnly: true + choices: + type: array + uniqueItems: true + readOnly: true + nullable: false + minItems: 1 + items: {} + source: + type: string + example: body + required: + - field + - reason + - rule + - choices + InvalidParameterDependentItem: + type: object + additionalProperties: false + properties: + field: + type: string + example: name + readOnly: true + rule: + description: invalid parameters rules + type: string + readOnly: true + nullable: true + enum: + - dependent_fields + reason: + type: string + example: is a required field + readOnly: true + dependents: + type: array + uniqueItems: true + nullable: true + items: {} + readOnly: true + source: + type: string + example: body + required: + - field + - rule + - reason + - dependents + KonnectCPLegacyBaseError: + type: object + title: Error + description: standard error + properties: + message: + type: string + description: | + A short summary of the problem. + readOnly: true + BaseError: + type: object + title: Error + description: standard error + required: + - status + - title + - instance + - detail + properties: + status: + type: integer + description: | + The HTTP status code of the error. Useful when passing the response + body to child properties in a frontend UI. Must be returned as an integer. + readOnly: true + title: + type: string + description: | + A short, human-readable summary of the problem. It should not + change between occurences of a problem, except for localization. + Should be provided as "Sentence case" for direct use in the UI. + readOnly: true + type: + type: string + description: The error type. + readOnly: true + instance: + type: string + description: | + Used to return the correlation ID back to the user, in the format + kong:trace:. This helps us find the relevant logs + when a customer reports an issue. + readOnly: true + detail: + type: string + description: | + A human readable explanation specific to this occurence of the problem. + This field may contain request/entity data to help the user understand + what went wrong. Enclose variable values in square brackets. Should be + provided as "Sentence case" for direct use in the UI. + readOnly: true + BadRequestError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + required: + - invalid_parameters + properties: + invalid_parameters: + $ref: '#/components/schemas/InvalidParameters' + KonnectCPLegacyBadRequestError: + allOf: + - $ref: '#/components/schemas/KonnectCPLegacyBaseError' + - type: object + properties: + message: + example: Bad Request + UnauthorizedError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 401 + title: + example: Unauthorized + type: + example: https://httpstatuses.com/401 + instance: + example: kong:trace:1234567890 + detail: + example: Invalid credentials + + KonnectCPLegacyUnauthorizedError: + allOf: + - $ref: '#/components/schemas/KonnectCPLegacyBaseError' + - type: object + properties: + message: + example: Unauthorized + KonnectCPLegacyForbiddenError: + allOf: + - $ref: '#/components/schemas/KonnectCPLegacyBaseError' + - type: object + properties: + message: + example: Forbidden + KonnectCPLegacyNotFoundError: + allOf: + - $ref: '#/components/schemas/KonnectCPLegacyBaseError' + - type: object + properties: + message: + example: Not Found + ForbiddenError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 403 + title: + example: Forbidden + type: + example: https://httpstatuses.com/403 + instance: + example: kong:trace:1234567890 + detail: + example: Forbidden + NotFoundError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 404 + title: + example: Not Found + type: + example: https://httpstatuses.com/404 + instance: + example: kong:trace:1234567890 + detail: + example: Not found + NotImplementedError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 501 + title: + example: Not Implemented + type: + example: https://httpstatuses.com/501 + instance: + example: kong:trace:1234567890 + detail: + example: Not Implemented + ConflictError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 409 + title: + example: Conflict + type: + example: https://httpstatuses.com/409 + instance: + example: kong:trace:1234567890 + detail: + example: Conflict + KonnectCPLegacyConflictError: + allOf: + - $ref: '#/components/schemas/KonnectCPLegacyBaseError' + - type: object + properties: + message: + example: Conflict + PayloadTooLargeError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 413 + title: + example: Payload Too Large + type: + example: https://httpstatuses.com/413 + instance: + example: kong:trace:1234567890 + detail: + example: Payload Too Large + UnsupportedMediaTypeError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 415 + title: + example: UnsupportedMediaType + type: + example: https://httpstatuses.com/415 + instance: + example: kong:trace:1234567890 + detail: + example: UnsupportedMediaType + UnprocessableContentError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 422 + title: + example: Unprocessable Content + type: + example: https://httpstatuses.com/422 + instance: + example: kong:trace:1234567891 + detail: + example: Unprocessable Content + TooManyRequestsError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 429 + title: + example: Too Many Requests + type: + example: https://httpstatuses.com/429 + instance: + example: kong:trace:1234567890 + detail: + example: Too Many Requests + GoneError: + allOf: + - $ref: '#/components/schemas/BaseError' + - type: object + properties: + status: + example: 410 + title: + example: Gone + type: + example: https://httpstatuses.com/410 + instance: + example: kong:trace:1234567890 + detail: + example: Gone + InternalError: + $ref: '#/components/schemas/BaseError' + NotAvailableError: + $ref: '#/components/schemas/BaseError' + examples: + ForbiddenExample: + value: + status: 403 + title: Forbidden + instance: kong:trace:2723154947768991354 + detail: You do not have permission to perform this action + KonnectCPLegacyBadRequestExample: + value: + message: Bad Request + KonnectCPLegacyUnauthorizedExample: + value: + message: Unauthorized + KonnectCPLegacyForbiddenExample: + value: + message: Forbidden + KonnectCPLegacyNotFoundExample: + value: + message: Not Found + KonnectCPLegacyConflictExample: + value: + message: Conflict + NotFoundExample: + value: + status: 404 + title: Not Found + instance: kong:trace:6816496025408232265 + detail: Not Found + UnsupportedMediaTypeExample: + value: + status: 415 + title: Unsupported Media Type + instance: kong:trace:8347343766220159418 + detail: 'This API only supports requests with `Content-Type: application/json`' + UnprocessableContentExample: + value: + status: 422 + title: Unprocessable Content + instance: kong:trace:8347343766220159419 + detail: 'The requested operation cannot be performed with the provided data' + UnauthorizedExample: + value: + status: 401 + title: Unauthorized + instance: kong:trace:8347343766220159418 + detail: Unauthorized diff --git a/api/spec/packages/aip/common/definitions/konnect_properties.yaml b/api/spec/packages/aip/common/definitions/konnect_properties.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c1bb23573019e6d82545c95b9c811d4fdc5a13e4 --- /dev/null +++ b/api/spec/packages/aip/common/definitions/konnect_properties.yaml @@ -0,0 +1,105 @@ +components: + schemas: + NullableUUID: + type: string + format: uuid + example: 5f9fd312-a987-4628-b4c5-bb4f4fddd5f7 + description: Contains a unique identifier for a resource. + nullable: true + Labels: + title: Labels + type: object + example: + env: test + maxProperties: 50 + description: | + Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. + + Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "_". + additionalProperties: + type: string + pattern: '^[a-z0-9A-Z]{1}([a-z0-9A-Z-._]*[a-z0-9A-Z]+)?$' + minLength: 1 + maxLength: 63 + LabelsUpdate: + type: object + nullable: true + description: | + Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. + + Labels are intended to store **INTERNAL** metadata. + + Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "_". + example: + env: test + maxProperties: 50 + additionalProperties: + type: string + pattern: '^[a-z0-9A-Z]{1}([a-z0-9A-Z-._]*[a-z0-9A-Z]+)?$' + minLength: 1 + maxLength: 63 + nullable: true + writeOnly: true + PublicLabels: + title: PublicLabels + type: object + example: + category: finance + maxProperties: 50 + description: | + Public labels store information about an entity that can be used for filtering a list of objects. + + Public labels are intended to store **PUBLIC** metadata. + + Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "_". + additionalProperties: + type: string + pattern: '^[a-z0-9A-Z]{1}([a-z0-9A-Z-._]*[a-z0-9A-Z]+)?$' + minLength: 1 + maxLength: 63 + PublicLabelsUpdate: + title: PublicLabelsUpdate + type: object + example: + category: finance + maxProperties: 50 + description: | + Public labels store information about an entity that can be used for filtering a list of objects. + + Public labels are intended to store **PUBLIC** metadata. + + Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "_". + additionalProperties: + type: string + pattern: '^[a-z0-9A-Z]{1}([a-z0-9A-Z-._]*[a-z0-9A-Z]+)?$' + minLength: 1 + maxLength: 63 + nullable: true + writeOnly: true + EntityType: + title: Entity Type + type: string + enum: + - api + - api_package + description: The type of entity that is being published. Can be either an API or an API Package. + example: api + parameters: + AuditLogDestinationId: + schema: + type: string + format: uuid + name: auditLogDestinationId + in: path + required: true + description: ID of the Audit Log Destination. + x-speakeasy-match: id + Workspace: + description: The name of the workspace + in: path + name: workspace + required: true + schema: + type: string + format: string + example: team-payments diff --git a/api/spec/packages/aip/common/definitions/metadatas.yaml b/api/spec/packages/aip/common/definitions/metadatas.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7f7d3d03c805edc679555c33772d979454e31b36 --- /dev/null +++ b/api/spec/packages/aip/common/definitions/metadatas.yaml @@ -0,0 +1,224 @@ +components: + schemas: + PaginationNextResponse: + description: URI to the next page (may be null) + type: string + PaginationOffsetResponse: + description: Offset is used to paginate through the API. Provide this value to the next list operation to fetch the next page + type: string + PaginatedMeta: + type: object + title: PaginatedMeta + x-speakeasy-terraform-ignore: true + description: returns the pagination information + properties: + page: + $ref: '#/components/schemas/PageMeta' + required: + - page + PageMeta: + type: object + description: Contains pagination query parameters and the total number of objects returned. + required: + - number + - size + - total + properties: + number: + type: number + example: 1 + x-speakeasy-terraform-ignore: true + size: + type: number + example: 10 + x-speakeasy-terraform-ignore: true + total: + type: number + example: 100 + x-speakeasy-terraform-ignore: true + CursorPageParameters: + type: object + properties: + size: + type: integer + description: The number of items included per page. + example: 10 + after: + type: string + description: Cursor param specifying the page (i.e. the next page) of data returned. + example: ewogICJpZCI6ICJoZWxsbyB3b3JsZCIKfQ + before: + type: string + description: Cursor param specifying the page (i.e. the previous page) of data returned. + example: ewogICJpZCI6ICJoZWxsbyB3b3JsZCIKfQ + CursorMetaPage: + type: object + required: + - size + - next + - previous + properties: + first: + description: URI to the first page + type: string + format: path + last: + description: URI to the last page + type: string + format: path + next: + description: URI to the next page + type: string + format: path + nullable: true + previous: + description: URI to the previous page + type: string + format: path + nullable: true + size: + description: Requested page size + type: number + example: 10 + CursorPaginatedMetaWithSizeAndTotal: + type: object + title: CursorPaginatedMetaWithSizeAndTotal + description: returns the pagination information + properties: + page: + $ref: '#/components/schemas/CursorMetaWithSizeAndTotal' + required: + - page + CursorMetaWithSizeAndTotal: + type: object + required: + - size + - next + - total + properties: + next: + description: URI to the next page + type: string + format: path + nullable: true + size: + description: Requested page size + type: number + example: 10 + total: + description: Total number of objects in the collection; will only be present on the first page + type: number + example: 974 + nullable: true + CursorMeta: + type: object + description: Pagination metadata. + required: + - page + properties: + page: + $ref: '#/components/schemas/CursorMetaPage' + CursorMetaWithTotal: + type: object + description: Pagination metadata with exact total. Useful when the collection size is inexpensive to provide. + required: + - page + properties: + page: + allOf: + - $ref: '#/components/schemas/CursorMetaPage' + - type: object + required: + - total + properties: + total: + description: Total number of objects in the collection + type: number + example: 974 + CursorMetaWithEstimatedTotal: + type: object + description: Pagination metadata with estimated total. Useful when exact total cannot be computed in reasonable time. + required: + - page + properties: + page: + allOf: + - $ref: '#/components/schemas/CursorMetaPage' + - type: object + required: + - estimated_total + properties: + estimated_total: + description: Approximate number of objects in the collection + type: number + example: 1000000000 + parameters: + CursorPageQuery: + name: page + description: Determines which page of the collection to retrieve. + required: false + in: query + schema: + $ref: '#/components/schemas/CursorPageParameters' + PageBefore: + name: 'page[before]' + description: Request the next page of data, starting with the item before this parameter. + required: false + in: query + allowEmptyValue: true + schema: + type: string + example: 'ewogICJpZCI6ICJoZWxsbyB3b3JsZCIKfQ' + PageAfter: + name: 'page[after]' + description: Request the next page of data, starting with the item after this parameter. + required: false + in: query + allowEmptyValue: true + schema: + type: string + example: 'ewogICJpZCI6ICJoZWxsbyB3b3JsZCIKfQ' + PageSize: + name: 'page[size]' + description: The maximum number of items to include per page. The last page of a collection may include fewer items. + required: false + in: query + allowEmptyValue: true + schema: + type: integer + example: 10 + x-speakeasy-terraform-ignore: true + PageNumber: + name: 'page[number]' + description: Determines which page of the entities to retrieve. + required: false + in: query + allowEmptyValue: true + schema: + type: integer + example: 1 + x-speakeasy-terraform-ignore: true + PaginationOffset: + allowEmptyValue: true + description: Offset from which to return the next set of resources. Use the value of the 'offset' field from the response of a list operation as input here to paginate through all the resources + in: query + name: offset + schema: + type: string + PaginationSize: + description: Number of resources to be returned. + in: query + name: size + schema: + type: integer + default: 100 + maximum: 1000 + minimum: 1 + PaginationTagsFilter: + allowEmptyValue: true + description: "A list of tags to filter the list of resources on. Multiple tags can be concatenated using ',' to mean AND or using '/' to mean OR." + example: 'tag1,tag2' + in: query + name: tags + schema: + type: string diff --git a/api/spec/packages/aip/common/definitions/properties.yaml b/api/spec/packages/aip/common/definitions/properties.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8cbe9b200f8eddbf72df6ed19843361f8c4f771 --- /dev/null +++ b/api/spec/packages/aip/common/definitions/properties.yaml @@ -0,0 +1,73 @@ +components: + parameters: + OrganizationIdParameter: + name: organizationId + in: path + description: UUID representing an organization. + required: true + schema: + $ref: '#/components/schemas/OrganizationId' + schemas: + UUID: + type: string + format: uuid + example: 5f9fd312-a987-4628-b4c5-bb4f4fddd5f7 + description: Contains a unique identifier used for this resource. + readOnly: true + # UUID_RW defines a ReadWrite UUID, as UUID defines a UUID readonly + UUID_RW: + type: string + format: uuid + example: 5f9fd312-a987-4628-b4c5-bb4f4fddd5f7 + description: Contains a unique identifier used for this resource. + CreatedAt: + type: string + format: date-time + example: '2022-11-04T20:10:06.927Z' + description: An ISO-8601 timestamp representation of entity creation date. + readOnly: true + x-speakeasy-param-suppress-computed-diff: true + UpdatedAt: + type: string + format: date-time + example: '2022-11-04T20:10:06.927Z' + description: An ISO-8601 timestamp representation of entity update date. + readOnly: true + x-speakeasy-param-suppress-computed-diff: true + ExpiresAt: + type: string + format: date-time + example: '2022-11-04T20:10:06.927Z' + description: An ISO-8601 timestamp representation of entity expiration date. + nullable: true + ExpiresAtNullable: + type: string + format: date-time + example: '2022-11-04T20:10:06.927Z' + nullable: true + description: An ISO-8601 timestamp representation of entity expiration date. + NullableTimestamp: + x-flatten-allOf: true + allOf: + - $ref: 'properties.yaml#/components/schemas/UpdatedAt' + - nullable: true + UserId: + x-flatten-allOf: true + allOf: + - $ref: 'properties.yaml#/components/schemas/UUID' + - description: Contains a unique identifier used for a user. + PrincipalId: + x-flatten-allOf: true + allOf: + - $ref: 'properties.yaml#/components/schemas/UUID' + - description: Contains a unique identifier used for a principal (user, system account, portal developer, etc.). + TeamId: + x-flatten-allOf: true + allOf: + - $ref: 'properties.yaml#/components/schemas/UUID' + - description: Contains a unique identifier used for a team. + OrganizationId: + x-flatten-allOf: true + allOf: + - $ref: 'properties.yaml#/components/schemas/UUID' + - description: UUID representing an organization. diff --git a/api/spec/packages/aip/common/definitions/security.yaml b/api/spec/packages/aip/common/definitions/security.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1df96066059090b6eaadccd632cc16a41729961a --- /dev/null +++ b/api/spec/packages/aip/common/definitions/security.yaml @@ -0,0 +1,45 @@ +components: + securitySchemes: + personalAccessToken: + type: http + scheme: bearer + bearerFormat: Token + description: | + The personal access token is meant to be used as an alternative to basic-auth when accessing Konnect via APIs. + You can generate a Personal Access Token (PAT) from the [personal access token page](https://cloud.konghq.com/global/account/tokens/) in the Konnect dashboard. + The PAT token must be passed in the header of a request, for example: + `curl -X GET 'https://global.api.konghq.com/v2/users/' --header 'Authorization: Bearer kpat_xgfT...'` + systemAccountAccessToken: + type: http + scheme: bearer + bearerFormat: Token + description: | + The system account access token is meant for automations and integrations that are not directly associated with a human identity. + You can generate a system account Access Token by creating a system account and then obtaining a system account access token for that account. + The access token must be passed in the header of a request, for example: + `curl -X GET 'https://global.api.konghq.com/v2/users/' --header 'Authorization: Bearer spat_i2Ej...'` + konnectAccessToken: + type: http + scheme: bearer + bearerFormat: JWT + description: | + The Konnect access token is meant to be used by the Konnect dashboard and the decK CLI authenticate with. + portalAccessToken: + type: apiKey + in: cookie + name: portalaccesstoken + description: | + The Developer portal cookie is meant to be used by the Developer API to authenticate with. + serviceAccessToken: + type: http + scheme: bearer + bearerFormat: JWT + description: | + The Service access token is meant to be used between internal services. + clientToken: + x-internal: true + type: http + scheme: bearer + bearerFormat: Token + description: | + The Client token is meant to be used by internal service clients for the MinK integration. diff --git a/api/spec/packages/aip/lib/index.js b/api/spec/packages/aip/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8c0d9b17ada02b561327eb240ccd907b884aaa03 --- /dev/null +++ b/api/spec/packages/aip/lib/index.js @@ -0,0 +1,29 @@ +import { defineLinter } from '@typespec/compiler' +import { casingErrorsRule, casingRule } from './rules/casing.js' +import { docDecoratorRule, docFormatRule } from './rules/docs.js' +import { friendlyNameRule } from './rules/friendly-name.js' +import { operationSummaryRule } from './rules/operation-summary.js' +import { operationIdKebabCaseRule } from './rules/operation-id.js' +import { noNullableRule } from './rules/no-nullable.js' +import { compositionOverInheritanceRule } from './rules/composition-over-inheritance.js' +import { repeatedPrefixGroupingRule } from './rules/field-prefix.js' +import { sortQueryTypeRule } from './rules/sort-query-type.js' + +// See example rules: https://github.com/Azure/typespec-azure/tree/main/packages/typespec-azure-core/src/rules +const rules = [ + casingRule, + casingErrorsRule, + docDecoratorRule, + docFormatRule, + friendlyNameRule, + noNullableRule, + operationSummaryRule, + operationIdKebabCaseRule, + compositionOverInheritanceRule, + repeatedPrefixGroupingRule, + sortQueryTypeRule, +] + +export const $linter = defineLinter({ + rules, +}) diff --git a/api/spec/packages/aip/lib/rules/casing.js b/api/spec/packages/aip/lib/rules/casing.js new file mode 100644 index 0000000000000000000000000000000000000000..523e25b3ac09f93fcdebfb6e9ba55f5b30451856 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/casing.js @@ -0,0 +1,100 @@ +import { createRule, paramMessage } from '@typespec/compiler' +import { + isCamelCaseNoAcronyms, + isPascalCaseNoAcronyms, + isSnakeCase, +} from './utils.js' + +export const casingRule = createRule({ + name: 'casing', + severity: 'warning', + description: 'Ensure proper casing style for AIP naming conventions.', + messages: { + name: paramMessage`The names of ${'type'} types must use ${'casing'}`, + }, + create: (context) => ({ + model: (model) => { + if (!isPascalCaseNoAcronyms(model.name)) { + context.reportDiagnostic({ + format: { type: 'Model', casing: 'PascalCase' }, + target: model, + messageId: 'name', + }) + } + }, + modelProperty: (property) => { + const isPath = property.decorators.find( + (d) => d.decorator.name === '$path', + ) + + if (isPath) { + if (!isCamelCaseNoAcronyms(property.name)) { + context.reportDiagnostic({ + format: { type: 'Model Property', casing: 'camelCase' }, + target: property, + messageId: 'name', + }) + } + + return + } + + if ( + !['_', 'contentType'].includes(property.name) && + !isSnakeCase(property.name) + ) { + context.reportDiagnostic({ + format: { type: 'Model Property', casing: 'snake_case' }, + target: property, + messageId: 'name', + }) + } + }, + enum: (model) => { + // Check enum name is PascalCase + if (!isPascalCaseNoAcronyms(model.name)) { + context.reportDiagnostic({ + format: { type: 'Enum', casing: 'PascalCase' }, + target: model, + messageId: 'name', + }) + } + + // Check enum member names are PascalCase + for (const member of model.members.values()) { + if (!isPascalCaseNoAcronyms(member.name)) { + context.reportDiagnostic({ + format: { type: 'Enum Member', casing: 'PascalCase' }, + target: member, + messageId: 'name', + }) + } + } + }, + }), +}) + +export const casingErrorsRule = createRule({ + name: 'casing-aip-errors', + severity: 'error', + description: 'Ensure proper casing style for AIP naming conventions.', + messages: { + value: paramMessage`The values of ${'type'} types must use ${'casing'}`, + }, + create: (context) => ({ + enum: (model) => { + // Check enum member values are snake_case + for (const member of model.members.values()) { + if (member.value && typeof member.value === 'string') { + if (!isSnakeCase(member.value)) { + context.reportDiagnostic({ + format: { type: 'Enum Value', casing: 'snake_case' }, + target: member, + messageId: 'value', + }) + } + } + } + }, + }), +}) diff --git a/api/spec/packages/aip/lib/rules/composition-over-inheritance.js b/api/spec/packages/aip/lib/rules/composition-over-inheritance.js new file mode 100644 index 0000000000000000000000000000000000000000..fd04ff867c8134bb75f134590cac7271f0a8395b --- /dev/null +++ b/api/spec/packages/aip/lib/rules/composition-over-inheritance.js @@ -0,0 +1,44 @@ +import { + createRule, + getDiscriminator, + getTypeName, + isTemplateInstance, + paramMessage, +} from '@typespec/compiler' +import { SyntaxKind } from '@typespec/compiler/ast' + +export const compositionOverInheritanceRule = createRule({ + name: 'composition-over-inheritance', + description: + 'Check that if a model is used in an operation and has derived models that it has a discriminator or recommend to use composition via spread or `is`.', + severity: 'warning', + messages: { + default: paramMessage`Model '${'name'}' is extending '${'baseModel'}' that doesn't define a discriminator. If '${'baseModel'}' is meant to be used: + - For composition consider using spread \`...\` or \`model is\` instead. + - As a polymorphic relation, add the \`@discriminator\` decorator on the base model.`, + instance: paramMessage`Model '${'name'}' is extending a template '${'baseModel'}'. Consider using composition with spread \`...\` or \`model is\` instead.`, + }, + create(context) { + return { + model: (model) => { + if ( + model.baseModel && + model.node?.kind === SyntaxKind.ModelStatement && + model.node.extends && + getDiscriminator(context.program, model.baseModel) === undefined + ) { + context.reportDiagnostic({ + messageId: isTemplateInstance(model.baseModel) + ? 'instance' + : 'default', + format: { + name: model.name, + baseModel: getTypeName(model.baseModel), + }, + target: model.node.extends, + }) + } + }, + } + }, +}) diff --git a/api/spec/packages/aip/lib/rules/docs.js b/api/spec/packages/aip/lib/rules/docs.js new file mode 100644 index 0000000000000000000000000000000000000000..c4b7c78b2bc8bbb694bf564d4ffd85645230cc92 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/docs.js @@ -0,0 +1,205 @@ +import { + createRule, + defineCodeFix, + getDoc, + getSourceLocation, + paramMessage, +} from '@typespec/compiler' +import * as prettier from 'prettier' +import { + detectNewline, + extractMarkdownFromDocComment, + getIndentBefore, + wrapMarkdownAsDocComment, +} from './utils.js' + +export const docDecoratorRule = createRule({ + name: 'doc-decorator', + severity: 'warning', + description: 'Ensure documentation.', + messages: { + default: paramMessage`Missing documentation for ${'name'} ${'type'}`, + }, + create: (context) => ({ + model: (target) => { + if (target.name && !getDoc(context.program, target)) { + context.reportDiagnostic({ + target, + format: { + name: target.name, + }, + }) + } + + if (target.name.endsWith('Response')) { + return + } + + for (const [name, property] of target.properties) { + if ( + target.name && + name && + !['_', 'contentType'].includes(name) && + !getDoc(context.program, property) + ) { + context.reportDiagnostic({ + target: property, + format: { + name: `${target.name}.${name}`, + }, + }) + } + } + }, + enum: (target) => { + if (target.name && !getDoc(context.program, target)) { + context.reportDiagnostic({ + target, + format: { + name: target.name, + }, + }) + } + }, + union: (target) => { + if (target.name && !getDoc(context.program, target)) { + context.reportDiagnostic({ + target, + format: { + name: target.name, + }, + }) + } + }, + }), +}) + +/** + * Format a doc-comment Markdown body through Prettier. + * Returns the formatted Markdown body (no `/** *\/` framing). + * @param {string} markdown + * @param {{ printWidth?: number, proseWrap?: 'always' | 'never' | 'preserve' }} [options] + */ +async function formatDocMarkdown(markdown, options = {}) { + if (markdown.trim() === '') return '' + return await prettier.format(markdown, { + parser: 'markdown', + printWidth: options.printWidth ?? 80, + proseWrap: options.proseWrap ?? 'always', + }) +} + +/** + * Build a code fix that replaces a doc comment with a precomputed string. + * The Prettier work happens before this is constructed; the fix callback is + * sync and just emits the replacement. + * + * @param {import('@typespec/compiler').SourceLocation} location + * The full `/** ... *\/` source range. + * @param {string} newText The replacement text, including `/**` and `*\/`. + */ +function createFormatDocCommentCodeFix(location, newText) { + return defineCodeFix({ + id: 'format-doc-comment', + label: 'Format doc comment', + fix(context) { + return context.replaceText(location, newText) + }, + }) +} + +/** + * Collect every `DocNode` reachable from the program by walking semantic + * targets that can carry doc comments. We use the existing semantic listener + * surface (model/property/enum/etc.) rather than a private AST walker. + */ +function collectDocNodes(target, sink) { + const node = target.node + if (!node || !node.docs || node.docs.length === 0) return + for (const doc of node.docs) sink.push(doc) +} + +export const docFormatRule = createRule({ + name: 'doc-format', + severity: 'warning', + description: + 'Format doc comment bodies as Markdown using Prettier (proseWrap=always).', + messages: { + default: + 'Doc comment is not formatted. Apply the suggested fix to reformat as Markdown.', + }, + // Async because Prettier 3.x's `format` is async. + async: true, + create: (context) => { + /** @type {import('@typespec/compiler').DocNode[]} */ + const docNodes = [] + + const collect = (target) => collectDocNodes(target, docNodes) + + return { + model: collect, + modelProperty: collect, + enum: collect, + enumMember: collect, + union: collect, + unionVariant: collect, + operation: collect, + interface: collect, + scalar: collect, + namespace: collect, + + async exit() { + // Deduplicate: a doc may be visited via multiple semantic kinds. + const seen = new Set() + const work = [] + for (const doc of docNodes) { + if (seen.has(doc)) continue + seen.add(doc) + work.push(processDoc(doc, context)) + } + await Promise.all(work) + }, + } + }, +}) + +/** + * Compute a formatted replacement for a single DocNode and, if it differs + * from the source, report a diagnostic with an attached code fix. + * @param {import('@typespec/compiler').DocNode} doc + * @param {import('@typespec/compiler').LinterRuleContext} context + */ +async function processDoc(doc, context) { + const location = getSourceLocation(doc) + const source = location.file.text + const raw = source.slice(location.pos, location.end) + + // Defensive: only format actual `/** ... */` blocks. + if (!raw.startsWith('/**') || !raw.endsWith('*/')) return + + const indent = getIndentBefore(source, location.pos) + const newline = detectNewline(source) + + let markdown + try { + markdown = extractMarkdownFromDocComment(raw) + } catch { + return + } + + let formatted + try { + formatted = await formatDocMarkdown(markdown) + } catch { + // If Prettier can't parse the body, leave it alone. + return + } + + const replacement = wrapMarkdownAsDocComment(formatted, indent, newline) + if (replacement === raw) return + + context.reportDiagnostic({ + target: doc, + codefixes: [createFormatDocCommentCodeFix(location, replacement)], + }) +} diff --git a/api/spec/packages/aip/lib/rules/field-prefix.js b/api/spec/packages/aip/lib/rules/field-prefix.js new file mode 100644 index 0000000000000000000000000000000000000000..e7943b91c701dfac21870bc8e7eb9c96d37b2136 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/field-prefix.js @@ -0,0 +1,73 @@ +import { createRule, paramMessage } from '@typespec/compiler' + +// List of prefixes that are excluded from the rule. +// These prefixes are defined in the AIP. +const EXCLUDED_PREFIXES = [ + 'allow', + 'custom', + 'default', + 'disable', + 'enable', + 'include_in', + 'initial', + 'is', + 'last', + 'primary', +] + +export const repeatedPrefixGroupingRule = createRule({ + name: 'repeated-prefix-grouping', + severity: 'warning', + description: 'Disallow repeated _* field prefixes within a model.', + messages: { + default: paramMessage`Repeated "${'prefix'}_" field prefix detected (${`fields`}). Group them under a "${'prefix'}" object.`, + }, + create(context) { + return { + model: (model) => { + if (!model?.properties || model.properties.size === 0) { + return + } + + const byPrefix = new Map() + + for (const prop of model.properties.values()) { + const name = prop?.name + if (!name) { + continue + } + + // "prefix" is everything before the first underscore. + const underscoreIndex = name.indexOf('_') + if (underscoreIndex <= 0) { + continue + } + + const prefix = name.slice(0, underscoreIndex) + const list = byPrefix.get(prefix) ?? [] + list.push(name) + byPrefix.set(prefix, list) + } + + for (const [prefix, fields] of byPrefix.entries()) { + if (EXCLUDED_PREFIXES.includes(prefix)) { + continue + } + + if (fields.length <= 1) { + continue + } + + context.reportDiagnostic({ + target: model, + messageId: 'default', + format: { + prefix, + fields: fields.sort().join(', '), + }, + }) + } + }, + } + }, +}) diff --git a/api/spec/packages/aip/lib/rules/friendly-name.js b/api/spec/packages/aip/lib/rules/friendly-name.js new file mode 100644 index 0000000000000000000000000000000000000000..fb38e5c10e5bf6014ba8c31cd59834155b32f752 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/friendly-name.js @@ -0,0 +1,77 @@ +import { createRule, getFriendlyName, paramMessage } from '@typespec/compiler' + +export const friendlyNameRule = createRule({ + name: 'friendly-name', + severity: 'error', + description: 'Ensure friendlyName decorator.', + messages: { + default: paramMessage`The ${'type'} ${'name'} must have a friendlyName decorator.`, + avoid: paramMessage`The ${'type'} ${'name'} should not have a friendlyName decorator.`, + }, + create: (context) => ({ + interface: (node) => { + const hasFriendlyName = !!getFriendlyName(context.program, node) + const isEndpointsOrOperations = + node.name.endsWith('Endpoints') || node.name.endsWith('Operations') + + if (isEndpointsOrOperations && hasFriendlyName) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'avoid', + }) + return + } + + if (!isEndpointsOrOperations && !hasFriendlyName) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + model: (node) => { + if (node.name && !getFriendlyName(context.program, node)) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + enum: (node) => { + if (node.name && !getFriendlyName(context.program, node)) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + union: (node) => { + if (node.name && !getFriendlyName(context.program, node)) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + }), +}) diff --git a/api/spec/packages/aip/lib/rules/no-nullable.js b/api/spec/packages/aip/lib/rules/no-nullable.js new file mode 100644 index 0000000000000000000000000000000000000000..f8232d898f3e87416fe32948d5468a6bff74a5f9 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/no-nullable.js @@ -0,0 +1,29 @@ +import { createRule, isNullType } from '@typespec/compiler' + +export const noNullableRule = createRule({ + name: 'no-nullable', + description: 'Use `?` for optional properties.', + severity: 'warning', + messages: { + default: + "Don't use `| null`. If you meant to have an optional property, use `?`. (e.g. `myProp?: string`)", + }, + create(context) { + return { + modelProperty: (property) => { + if (property.type.kind !== 'Union') { + return + } + + if ( + !property.node?.optional && + [...property.type.variants.values()].some((x) => isNullType(x.type)) + ) { + context.reportDiagnostic({ + target: property, + }) + } + }, + } + }, +}) diff --git a/api/spec/packages/aip/lib/rules/operation-id.js b/api/spec/packages/aip/lib/rules/operation-id.js new file mode 100644 index 0000000000000000000000000000000000000000..7134e0a663ea72a20595c711159b0979cf5f6250 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/operation-id.js @@ -0,0 +1,35 @@ +import { createRule, paramMessage } from '@typespec/compiler' +import { isKebabCase } from './utils.js' + +export const operationIdKebabCaseRule = createRule({ + name: 'operation-id-kebab-case', + severity: 'error', + description: 'Ensure @operationId values are in kebab-case.', + messages: { + default: paramMessage`The operationId "${'operationId'}" should be in kebab-case.`, + }, + create: (context) => ({ + operation: (node) => { + const operationIdDecorator = node.decorators.find( + (d) => d.decorator.name === '$operationId', + ) + + if (operationIdDecorator) { + const operationId = operationIdDecorator.args[0]?.jsValue + if ( + operationId && + typeof operationId === 'string' && + !isKebabCase(operationId) + ) { + context.reportDiagnostic({ + format: { + operationId, + }, + target: node, + messageId: 'default', + }) + } + } + }, + }), +}) diff --git a/api/spec/packages/aip/lib/rules/operation-summary.js b/api/spec/packages/aip/lib/rules/operation-summary.js new file mode 100644 index 0000000000000000000000000000000000000000..6005c0c8e938740489fa194c25e684b8f77e014e --- /dev/null +++ b/api/spec/packages/aip/lib/rules/operation-summary.js @@ -0,0 +1,27 @@ +import { createRule, paramMessage } from '@typespec/compiler' + +export const operationSummaryRule = createRule({ + name: 'operation-summary', + severity: 'warning', + description: 'Ensure operation summary.', + messages: { + default: paramMessage`The ${'type'} ${'name'} must have a summary decorator.`, + }, + create: (context) => ({ + operation: (node) => { + if ( + node.name && + !node.decorators.some((d) => d.decorator.name === '$summary') + ) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + }), +}) diff --git a/api/spec/packages/aip/lib/rules/sort-query-type.js b/api/spec/packages/aip/lib/rules/sort-query-type.js new file mode 100644 index 0000000000000000000000000000000000000000..83626dd1b447708bab74c73026e5df77dac6d8f4 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/sort-query-type.js @@ -0,0 +1,33 @@ +import { createRule, getNamespaceFullName } from '@typespec/compiler' +import { getQueryParamName } from '@typespec/http' + +export const sortQueryTypeRule = createRule({ + name: 'sort-query-type', + severity: 'warning', + description: + 'Require query parameters named `sort` to use `Common.SortQuery`.', + messages: { + default: 'Query parameters named `sort` must use `Common.SortQuery`.', + }, + create(context) { + return { + modelProperty: (property) => { + if (getQueryParamName(context.program, property) !== 'sort') { + return + } + + const type = property.type + if ( + type.kind === 'Model' && + type.name === 'SortQuery' && + type.namespace && + getNamespaceFullName(type.namespace) === 'Common' + ) { + return + } + + context.reportDiagnostic({ target: property }) + }, + } + }, +}) diff --git a/api/spec/packages/aip/lib/rules/utils.js b/api/spec/packages/aip/lib/rules/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..4a5872be4cf41eb83a57907db461ecce2a6b2a55 --- /dev/null +++ b/api/spec/packages/aip/lib/rules/utils.js @@ -0,0 +1,124 @@ +/** + * Exceptions for PascalCase naming convention. + */ +const pascalCaseExceptions = ['OAuth2', 'URL', 'API', 'UI', 'ID'] + +/** + * Checks whether a given value is in PascalCase + * @param value the value to check + * @returns true if the value is in PascalCase + */ +export function isPascalCaseNoAcronyms(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return new RegExp( + `^(?:[A-Z][a-z0-9]+|${pascalCaseExceptions.join('|')})+[A-Z]?$|^[A-Z]+$`, + ).test(value) +} + +/** + * Checks whether a given value is in camelCase + * @param value the value to check + * @returns true if the value is in camelCase + */ +export function isCamelCaseNoAcronyms(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return /^[^a-zA-Z0-9]?[a-z][a-z0-9]*([A-Z][a-z0-9]+)*[A-Z]?$/.test(value) +} + +/** + * Checks whether a given value is in snake_case + * @param value the value to check + * @returns true if the value is in snake_case + */ +export function isSnakeCase(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return /^([a-z0-9]+_)*[a-z0-9]+$/.test(value) +} + +/** + * Checks whether a given value is in kebab-case + * @param value the value to check + * @returns true if the value is in kebab-case + */ +export function isKebabCase(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return /^([a-z0-9]+(-[a-z0-9]+)*)$/.test(value) +} + +/** + * Detect the dominant line separator in a source string. + * @param {string} source + * @returns {'\n' | '\r\n'} + */ +export function detectNewline(source) { + return source.includes('\r\n') ? '\r\n' : '\n' +} + +/** + * Return the indentation (whitespace from start of line) preceding `position`. + * @param {string} source + * @param {number} position + */ +export function getIndentBefore(source, position) { + const lineStart = source.lastIndexOf('\n', position - 1) + 1 + const between = source.slice(lineStart, position) + const match = between.match(/^[ \t]*/) + return match ? match[0] : '' +} + +/** + * Strip `/** ... *\/` framing and per-line `*` decoration from a doc comment, + * returning the inner Markdown body. Trims leading/trailing blank lines. + * @param {string} raw the full comment text including `/** ... *\/` + */ +export function extractMarkdownFromDocComment(raw) { + let body = raw + if (body.startsWith('/**')) body = body.slice(3) + if (body.endsWith('*/')) body = body.slice(0, -2) + + const lines = body.split(/\r?\n/).map((line) => { + // Strip leading whitespace + a single `*` + an optional space. + return line.replace(/^[ \t]*\*[ \t]?/, '').replace(/[ \t]+$/, '') + }) + + let start = 0 + let end = lines.length + while (start < end && lines[start].trim() === '') start++ + while (end > start && lines[end - 1].trim() === '') end-- + return lines.slice(start, end).join('\n') +} + +/** + * Re-wrap a Markdown body as a TypeSpec doc comment, applying `indent` on each + * line and using `newline` between lines. + * @param {string} markdown + * @param {string} indent + * @param {'\n' | '\r\n'} newline + */ +export function wrapMarkdownAsDocComment(markdown, indent, newline) { + const trimmed = markdown.replace(/\n+$/, '') + if (trimmed === '') { + return `/**${newline}${indent} */` + } + const lines = trimmed.split('\n') + const out = [ + '/**', + ...lines.map((line) => + line.length === 0 ? `${indent} *` : `${indent} * ${line}`, + ), + `${indent} */`, + ] + return out.join(newline) +} diff --git a/api/spec/packages/aip/package.json b/api/spec/packages/aip/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fd195eebb6782a0a977921e60debb9367efac90a --- /dev/null +++ b/api/spec/packages/aip/package.json @@ -0,0 +1,37 @@ +{ + "name": "@openmeter/api-spec-aip", + "version": "0.1.0", + "type": "module", + "scripts": { + "generate": "tsp compile --config tspconfig.yaml ./src && node ./scripts/flatten-allof.mjs ./output/definitions/metering-and-billing/v3/openapi.MeteringAndBilling.yaml && node ./scripts/seal-object-schemas.mjs ./output/definitions/metering-and-billing/v3/*.yaml", + "bundle": "openapi bundle output/definitions/metering-and-billing/v3/openapi.OpenMeter.yaml", + "watch": "tsp compile --watch --config tspconfig.yaml ./src", + "test": "node --test test/*.test.js", + "format": "node ./scripts/apply-doc-fixes.mjs && prettier --ignore-path ../../.prettierignore --list-different --find-config-path --write .", + "lint": "prettier --ignore-path ../../.prettierignore --check .", + "lint:fix": "prettier --ignore-path ../../.prettierignore --write ." + }, + "main": "./lib/index.js", + "exports": { + ".": { + "typespec": "./src/main.tsp" + } + }, + "devDependencies": { + "@openmeter/typespec-go": "workspace:*", + "@openmeter/typespec-typescript": "workspace:*", + "@redocly/cli": "2.31.6", + "@types/node": "25.9.2", + "@typespec/compiler": "1.11.0", + "@typespec/http": "1.11.0", + "@typespec/json-schema": "1.11.0", + "@typespec/openapi": "1.11.0", + "@typespec/openapi3": "1.11.0", + "@typespec/prettier-plugin-typespec": "1.12.0", + "@typespec/rest": "0.81.0", + "prettier": "3.8.3", + "yaml": "2.9.0" + }, + "private": true, + "packageManager": "pnpm@10.28.0+sha512.05df71d1421f21399e053fde567cea34d446fa02c76571441bfc1c7956e98e363088982d940465fd34480d4d90a0668bc12362f8aa88000a64e83d0b0e47be48" +} diff --git a/api/spec/packages/aip/scripts/apply-doc-fixes.mjs b/api/spec/packages/aip/scripts/apply-doc-fixes.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3c0a9da4a894d5922b183aeec1edd60387266bf4 --- /dev/null +++ b/api/spec/packages/aip/scripts/apply-doc-fixes.mjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +import { readFile } from 'node:fs/promises' +import path from 'node:path' +import process from 'node:process' +import { applyCodeFixes, compile, NodeHost } from '@typespec/compiler' + +const CODEFIX_ID = 'format-doc-comment' +const RULE_NAME = 'doc-format' + +const cwd = process.cwd() +const pkg = JSON.parse( + await readFile(path.resolve(cwd, 'package.json'), 'utf8'), +) + +// Derive the linter ruleset id from `package.json#name` (e.g. +// `@openmeter/api-spec-aip/all`) so renaming the package doesn't break this. +const RULE_ID = `${pkg.name}/${RULE_NAME}` +const RULESET = `${pkg.name}/all` + +// Derive the TypeSpec entrypoint from `package.json#exports['.'].typespec`, +// matching how `tsp compile ./src` resolves it. +const entryRel = pkg.exports?.['.']?.typespec +if (!entryRel) { + console.error( + "apply-doc-fixes: package.json must declare exports['.'].typespec", + ) + process.exit(1) +} +const entry = path.resolve(cwd, entryRel) + +// `compile()` doesn't read `tspconfig.yaml`, so the linter ruleset has to be +// passed explicitly here. Mirror what `tspconfig.yaml` configures. +const program = await compile(NodeHost, entry, { + noEmit: true, + linterRuleSet: { extends: [RULESET] }, +}) + +// Each lint diagnostic carries our `format-doc-comment` codefix plus an +// auto-attached `suppress` codefix from the compiler. Apply only ours. +const matching = program.diagnostics.filter((d) => d.code === RULE_ID) +const fixes = matching.flatMap( + (d) => d.codefixes?.filter((c) => c.id === CODEFIX_ID) ?? [], +) + +if (fixes.length === 0) { + console.error('apply-doc-fixes: no doc-format codefixes to apply') + process.exit(0) +} + +await applyCodeFixes(NodeHost, fixes) + +console.error( + `apply-doc-fixes: applied ${fixes.length} fix(es) across ${matching.length} diagnostic(s)`, +) diff --git a/api/spec/packages/aip/scripts/flatten-allof.mjs b/api/spec/packages/aip/scripts/flatten-allof.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5cf4d4a711f5e8bd275f0db07f37ec3ba4a8f7c7 --- /dev/null +++ b/api/spec/packages/aip/scripts/flatten-allof.mjs @@ -0,0 +1,152 @@ +#!/usr/bin/env node + +import fs from 'node:fs/promises' +import process from 'node:process' +import YAML from 'yaml' + +const FLATTEN_MARKER = 'x-flatten-allOf' +const YAML_OPTIONS = { + indent: 2, + lineWidth: 0, +} + +function isPlainObject(value) { + return value != null && typeof value === 'object' && !Array.isArray(value) +} + +function isRefObject(value) { + return isPlainObject(value) && typeof value.$ref === 'string' +} + +function getMovableKeys(node) { + return Object.keys(node).filter( + (key) => key !== 'allOf' && key !== FLATTEN_MARKER && !key.startsWith('x-'), + ) +} + +function moveSiblingPropertiesIntoAllOf(node) { + const movableKeys = getMovableKeys(node) + + if (movableKeys.length === 0) { + if (node[FLATTEN_MARKER] !== true) { + node[FLATTEN_MARKER] = true + return true + } + + return false + } + + const moved = {} + for (const key of movableKeys) { + moved[key] = node[key] + delete node[key] + } + + node.allOf.push(moved) + node[FLATTEN_MARKER] = true + + return true +} + +/** + * Move sibling properties into an allOf branch when the schema contains a + * referenced member. This keeps flattening hints consistent across the file. + */ +function flattenAllOf(node) { + if (Array.isArray(node)) { + let changed = false + + for (const item of node) { + changed = flattenAllOf(item) || changed + } + + return changed + } + + if (!isPlainObject(node)) { + return false + } + + let changed = false + const { allOf } = node + + const hasRefInAllOf = + Array.isArray(allOf) && allOf.some((item) => isRefObject(item)) + + if (hasRefInAllOf) { + changed = moveSiblingPropertiesIntoAllOf(node) || changed + } + + for (const value of Object.values(node)) { + changed = flattenAllOf(value) || changed + } + + return changed +} + +async function pathExists(path) { + try { + await fs.access(path) + return true + } catch { + return false + } +} + +async function validateInputFile(filePath) { + if (!(await pathExists(filePath))) { + throw new Error(`file not found: ${filePath}`) + } + + const stat = await fs.stat(filePath) + if (!stat.isFile()) { + throw new Error(`not a file: ${filePath}`) + } +} + +async function readYamlFile(filePath) { + const raw = await fs.readFile(filePath, 'utf8') + + try { + return YAML.parse(raw) + } catch (error) { + throw new Error(`parse error: ${error.message}`) + } +} + +async function writeYamlFile(filePath, document) { + const output = YAML.stringify(document, YAML_OPTIONS) + const normalized = output.endsWith('\n') ? output : `${output}\n` + + await fs.writeFile(filePath, normalized, 'utf8') +} + +function printUsage() { + process.stderr.write('Usage: flatten-allof.mjs \n') +} + +async function main() { + const [filePath] = process.argv.slice(2) + + if (!filePath) { + printUsage() + process.exitCode = 1 + return + } + + try { + await validateInputFile(filePath) + + const parsed = await readYamlFile(filePath) + const changed = flattenAllOf(parsed) + + if (changed) { + await writeYamlFile(filePath, parsed) + } + } catch (error) { + process.stderr.write(`flatten-allof: ${error.message}\n`) + process.exitCode = 1 + } +} + +await main() diff --git a/api/spec/packages/aip/scripts/seal-object-schemas.mjs b/api/spec/packages/aip/scripts/seal-object-schemas.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7a4d4daceca238c3906840ebd63c94f02adc24e4 --- /dev/null +++ b/api/spec/packages/aip/scripts/seal-object-schemas.mjs @@ -0,0 +1,168 @@ +#!/usr/bin/env node + +import fs from 'node:fs/promises' +import process from 'node:process' +import YAML from 'yaml' + +const YAML_OPTIONS = { + indent: 2, + lineWidth: 0, +} + +function isPlainObject(value) { + return value != null && typeof value === 'object' && !Array.isArray(value) +} + +// `@typespec/openapi3` with `seal-object-schemas: true` emits +// `additionalProperties: { not: {} }` to forbid extra properties. +// kin-openapi's deepObject decoder cannot pick the matching branch of a +// `oneOf` when the branch carries that form, so every nested-object +// query (e.g. `filter[boolean][eq]=true`) becomes "path is not +// convertible to primitive". `additionalProperties: false` is +// semantically equivalent and accepted by kin-openapi, so rewrite it. +function isNotEmptyObject(value) { + if (!isPlainObject(value)) { + return false + } + + const keys = Object.keys(value) + if (keys.length !== 1 || keys[0] !== 'not') { + return false + } + + return isPlainObject(value.not) && Object.keys(value.not).length === 0 +} + +function rewriteAdditionalProperties(node) { + if (Array.isArray(node)) { + let changed = false + + for (const item of node) { + changed = rewriteAdditionalProperties(item) || changed + } + + return changed + } + + if (!isPlainObject(node)) { + return false + } + + let changed = false + + if (isNotEmptyObject(node.additionalProperties)) { + node.additionalProperties = false + changed = true + } + + for (const value of Object.values(node)) { + changed = rewriteAdditionalProperties(value) || changed + } + + return changed +} + +async function pathExists(path) { + try { + await fs.access(path) + return true + } catch { + return false + } +} + +async function validateInputFile(filePath) { + if (!(await pathExists(filePath))) { + throw new Error(`file not found: ${filePath}`) + } + + const stat = await fs.stat(filePath) + if (!stat.isFile()) { + throw new Error(`not a file: ${filePath}`) + } +} + +async function readYamlFile(filePath) { + const raw = await fs.readFile(filePath, 'utf8') + + try { + return YAML.parse(raw) + } catch (error) { + throw new Error(`parse error: ${error.message}`) + } +} + +async function writeYamlFile(filePath, document) { + const output = YAML.stringify(document, YAML_OPTIONS) + const normalized = output.endsWith('\n') ? output : `${output}\n` + + await fs.writeFile(filePath, normalized, 'utf8') +} + +function printUsage() { + process.stderr.write( + 'Usage: seal-object-schemas.mjs [ ...]\n', + ) +} + +async function processFile(filePath) { + await validateInputFile(filePath) + + const parsed = await readYamlFile(filePath) + const changed = rewriteAdditionalProperties(parsed) + + if (changed) { + await writeYamlFile(filePath, parsed) + } +} + +function looksLikeGlob(pattern) { + return /[*?[]/.test(pattern) +} + +async function expandPattern(pattern) { + if (!looksLikeGlob(pattern)) { + return [pattern] + } + + const matches = [] + for await (const match of fs.glob(pattern)) { + matches.push(match) + } + matches.sort() + + if (matches.length === 0) { + throw new Error(`no files matched pattern: ${pattern}`) + } + + return matches +} + +async function main() { + const patterns = process.argv.slice(2) + + if (patterns.length === 0) { + printUsage() + process.exitCode = 1 + return + } + + try { + const seen = new Set() + for (const pattern of patterns) { + const filePaths = await expandPattern(pattern) + for (const filePath of filePaths) { + if (seen.has(filePath)) { + continue + } + seen.add(filePath) + await processFile(filePath) + } + } + } catch (error) { + process.stderr.write(`seal-object-schemas: ${error.message}\n`) + process.exitCode = 1 + } +} + +await main() diff --git a/api/spec/packages/aip/src/apps/app.tsp b/api/spec/packages/aip/src/apps/app.tsp new file mode 100644 index 0000000000000000000000000000000000000000..612e5b0ef5f470a03ae05dc6ee61539c540a3fe2 --- /dev/null +++ b/api/spec/packages/aip/src/apps/app.tsp @@ -0,0 +1,99 @@ +import "../shared/index.tsp"; +import "./catalog.tsp"; +import "./sandbox.tsp"; +import "./stripe.tsp"; +import "./external_invoicing.tsp"; + +namespace Apps; + +/** + * The type of the app. + */ +@friendlyName("BillingAppType") +enum AppType { + /** + * Built-in sandbox integration for testing and development. + */ + Sandbox: "sandbox", + + /** + * The Stripe app synchronizes invoices to Stripe Invoicing, enabling automated revenue collection with Stripe Payments and Stripe Tax. + */ + Stripe: "stripe", + + /** + * The external invoicing app enables synchronizing invoices with finance systems that are not natively supported, such as ERPs, in-house invoicing solutions, or local e-invoicing and payment providers. + */ + ExternalInvoicing: "external_invoicing", +} + +/** + * Connection status of an installed app. + */ +@friendlyName("BillingAppStatus") +enum AppStatus { + /** + * The app is ready to be used. + */ + Ready: "ready", + + /** + * The app is unauthorized. + * This usually happens when the app's credentials are revoked or expired. + * To resolve this, the user must re-authorize the app. + */ + Unauthorized: "unauthorized", +} + +/** + * Base model for installed apps, with its own configuration and credentials. + */ +@friendlyName("BillingAppBase") +model AppBase { + ...Shared.Resource; + + /** + * The app type. + */ + @visibility(Lifecycle.Read) + type: T; + + /** + * The app catalog definition that this installed app is based on. + */ + @visibility(Lifecycle.Read) + definition: AppCatalogItem; + + /** + * Status of the app connection. + */ + @visibility(Lifecycle.Read) + status: AppStatus; +} + +/** + * Installed application. + */ +@friendlyName("BillingApp") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union App { + @summary("Stripe") + stripe: AppStripe, + + @summary("Sandbox") + sandbox: AppSandbox, + + @summary("External Invoicing") + external_invoicing: AppExternalInvoicing, +} + +/** + * App reference. + */ +@friendlyName("BillingAppReference") +model AppReference { + /** + * The ID of the app. + */ + id: Shared.ULID; +} diff --git a/api/spec/packages/aip/src/apps/capability.tsp b/api/spec/packages/aip/src/apps/capability.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6ef5489a6da5bee83f3cce6e9542c626a641de2d --- /dev/null +++ b/api/spec/packages/aip/src/apps/capability.tsp @@ -0,0 +1,68 @@ +import "../shared/index.tsp"; + +namespace Apps; + +/** + * Supported capability types for an App. + * + * Each capability defines an integration function that an App can perform. + */ +@friendlyName("BillingAppCapabilityType") +enum AppCapabilityType { + /** + * The app can report aggregated usage. + */ + ReportUsage: "report_usage", + + /** + * The app can report raw events. + */ + ReportEvents: "report_events", + + /** + * The app can calculate tax for invoices. + */ + CalculateTax: "calculate_tax", + + /** + * The app can issue invoices to customers. + */ + InvoiceCustomers: "invoice_customers", + + /** + * The app can collect payments from customers. + */ + CollectPayments: "collect_payments", +} + +/** + * App capability describes a function that an App can perform. + */ +@friendlyName("BillingAppCapability") +@example(#{ + type: AppCapabilityType.CollectPayments, + key: "stripe_collect_payment", + name: "Collect Payments", + description: "Stripe payments collects outstanding revenue with Stripe customer's default payment method.", +}) +model AppCapability { + /** + * Type of the capability. + */ + type: AppCapabilityType; + + /** + * Key of the capability. + */ + key: Shared.ResourceKey; + + /** + * Name of the capability. + */ + name: string; + + /** + * Description of the capability. + */ + description: string; +} diff --git a/api/spec/packages/aip/src/apps/catalog.tsp b/api/spec/packages/aip/src/apps/catalog.tsp new file mode 100644 index 0000000000000000000000000000000000000000..f86607c3ebe50b0fcf2d709b4bc43dfa304a8360 --- /dev/null +++ b/api/spec/packages/aip/src/apps/catalog.tsp @@ -0,0 +1,157 @@ +import "../shared/index.tsp"; +import "./capability.tsp"; +import "./app.tsp"; + +namespace Apps; + +/** + * Supported installation methods for an app. + */ +@friendlyName("BillingAppInstallMethods") +enum AppInstallMethods { + /** + * Install by completing an OAuth 2.0 authorization flow. + */ + WithOAuth2: "with_oauth2", + + /** + * Install by providing an API key. + */ + WithAPIKey: "with_api_key", + + /** + * Install without providing any credentials. + */ + NoCredentialsRequired: "no_credentials_required", +} + +/** + * Available apps for billing integrations to connect with third-party services. + * Apps can have various capabilities like syncing data from or to external + * systems, integrating with third-party services for tax calculation, delivery of + * invoices, collection of payments, etc. + */ +@friendlyName("BillingAppCatalogItem") +@example(#{ + type: AppType.Stripe, + name: "Stripe", + description: "Stripe integration allows you to collect payments with Stripe.", + capabilities: #[ + #{ + type: AppCapabilityType.CalculateTax, + key: "stripe_calculate_tax", + name: "Calculate Tax", + description: "Stripe Tax calculates tax portion of the invoices.", + }, + #{ + type: AppCapabilityType.InvoiceCustomers, + key: "stripe_invoice_customers", + name: "Invoice Customers", + description: "Stripe invoices customers with due amount.", + }, + #{ + type: AppCapabilityType.CollectPayments, + key: "stripe_collect_payments", + name: "Collect Payments", + description: "Stripe payments collects outstanding revenue with Stripe customer's default payment method.", + } + ], + install_methods: #[ + AppInstallMethods.WithOAuth2, + AppInstallMethods.WithAPIKey + ], +}) +model AppCatalogItem { + /** + * Type of the app. + */ + @visibility(Lifecycle.Read) + type: AppType; + + /** + * Name of the app. + */ + @visibility(Lifecycle.Read) + name: string; + + /** + * Description of the app. + */ + @visibility(Lifecycle.Read) + description: string; + + /** + * Capabilities of the app. + */ + @visibility(Lifecycle.Read) + capabilities: AppCapability[]; + + /** + * Available install methods of the app. + */ + @visibility(Lifecycle.Read) + install_methods: AppInstallMethods[]; +} + +/** + * Request to install an app from the catalog. + */ +@friendlyName("BillingInstallAppRequest") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union InstallAppRequest { + @summary("Stripe") + stripe: InstallAppWithApiKey, + + @summary("Sandbox") + sandbox: InstallAppBase, + + @summary("External Invoicing") + external_invoicing: InstallAppBase, +} + +/** + * Base model for installing an app from the catalog. + */ +@friendlyName("BillingInstallApp{name}", T) +model InstallAppBase { + /** + * Type of the app. + */ + type: T; + + /** + * Name of the app. + */ + name: string; + + /** + * If true, a billing profile will be created for the app. The Stripe app will be + * also set as the default billing profile if the current default is a Sandbox app. + */ + create_billing_profile: boolean; +} + +/** + * Model for installing an app from the catalog with an API key. + */ +@friendlyName("BillingInstallApp{name}WithApiKey", T) +model InstallAppWithApiKey { + ...InstallAppBase; + + /** + * API key for the app. + */ + api_key: string; +} + +/** + * Response of the app install. + */ +@friendlyName("BillingInstallAppResponse") +model InstallAppResponse { + @visibility(Lifecycle.Read) + app: App; + + @visibility(Lifecycle.Read) + default_for_capability_types: AppCapabilityType[]; +} diff --git a/api/spec/packages/aip/src/apps/customer.tsp b/api/spec/packages/aip/src/apps/customer.tsp new file mode 100644 index 0000000000000000000000000000000000000000..ad0575270960f86f71fdf03e5e52eebf89a4c8ba --- /dev/null +++ b/api/spec/packages/aip/src/apps/customer.tsp @@ -0,0 +1,63 @@ +import "./app.tsp"; + +namespace Apps; + +/** + * App customer data. + */ +@friendlyName("BillingAppCustomerData") +model AppCustomerData { + /** + * Used if the customer has a linked Stripe app. + */ + @summary("Stripe") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + stripe?: Apps.AppCustomerDataStripe; + + /** + * Used if the customer has a linked external invoicing app. + */ + @summary("External invoicing") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + external_invoicing?: Apps.AppCustomerDataExternalInvoicing; +} + +/** + * Stripe customer data. + */ +@friendlyName("BillingAppCustomerDataStripe") +model AppCustomerDataStripe { + /** + * The Stripe customer ID used. + */ + @summary("Stripe customer ID") + @example("cus_1234567890") + customer_id?: string; + + /** + * The Stripe default payment method ID. + */ + @summary("Stripe default payment method ID") + @example("pm_1234567890") + default_payment_method_id?: string; + + /** + * Labels for this Stripe integration on the customer. + */ + @summary("Labels") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + labels?: Common.Labels; +} + +/** + * External invoicing customer data. + */ +@friendlyName("BillingAppCustomerDataExternalInvoicing") +model AppCustomerDataExternalInvoicing { + /** + * Labels for this external invoicing integration on the customer. + */ + @summary("Labels") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + labels?: Common.Labels; +} diff --git a/api/spec/packages/aip/src/apps/external_invoicing.tsp b/api/spec/packages/aip/src/apps/external_invoicing.tsp new file mode 100644 index 0000000000000000000000000000000000000000..60a45d6237669014a9ae8d7ff370a1c089ba1604 --- /dev/null +++ b/api/spec/packages/aip/src/apps/external_invoicing.tsp @@ -0,0 +1,55 @@ +import "../shared/index.tsp"; +import "./app.tsp"; +import "../invoices/index.tsp"; + +namespace Apps; + +/** + * External Invoicing app enables integration with third-party invoicing or payment + * system. + * + * The app supports a bi-directional synchronization pattern where OpenMeter + * Billing manages the invoice lifecycle while the external system handles invoice + * presentation and payment collection. + * + * Integration workflow: + * + * 1. The billing system creates invoices and transitions them through lifecycle + * states (draft → issuing → issued) + * 2. The integration receives webhook notifications about invoice state changes + * 3. The integration calls back to provide external system IDs and metadata + * 4. The integration reports payment events back via the payment status API + * + * State synchronization is controlled by hooks that pause invoice progression + * until the external system confirms synchronization via API callbacks. + */ +@friendlyName("BillingAppExternalInvoicing") +model AppExternalInvoicing { + ...AppBase; + + /** + * Enable draft synchronization hook. + * + * When enabled, invoices will pause at the draft state and wait for the + * integration to call the draft synchronized endpoint before progressing to the + * issuing state. This allows the external system to validate and prepare the + * invoice data. + * + * When disabled, invoices automatically progress through the draft state based on + * the configured workflow timing. + */ + enable_draft_sync_hook: boolean; + + /** + * Enable issuing synchronization hook. + * + * When enabled, invoices will pause at the issuing state and wait for the + * integration to call the issuing synchronized endpoint before progressing to the + * issued state. This ensures the external invoicing system has successfully + * created and finalized the invoice before it is marked as issued. + * + * When disabled, invoices automatically progress through the issuing state and are + * immediately marked as issued. + */ + enable_issuing_sync_hook: boolean; +} diff --git a/api/spec/packages/aip/src/apps/index.tsp b/api/spec/packages/aip/src/apps/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..d8208a48f9e4116dcddf813017ac9b3334041c2a --- /dev/null +++ b/api/spec/packages/aip/src/apps/index.tsp @@ -0,0 +1,7 @@ +import "./app.tsp"; +import "./catalog.tsp"; +import "./customer.tsp"; +import "./external_invoicing.tsp"; +import "./sandbox.tsp"; +import "./stripe.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/apps/operations.tsp b/api/spec/packages/aip/src/apps/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..842d27436a63dcfdb788f486b34c780c2e408172 --- /dev/null +++ b/api/spec/packages/aip/src/apps/operations.tsp @@ -0,0 +1,76 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./app.tsp"; +import "./external_invoicing.tsp"; +import "./stripe.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Apps; + +interface AppsOperations { + /** + * List installed apps. + */ + @get + @operationId("list-apps") + @summary("List apps") + list(...Common.PagePaginationQuery): + | Shared.PagePaginatedResponse + | Common.ErrorResponses; + + /** + * Get an installed app. + */ + @get + @operationId("get-app") + @summary("Get app") + get(@path appId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; +} + +interface AppCatalogOperations { + /** + * List available apps. + */ + @get + @operationId("list-app-catalog") + @summary("List app catalog") + list(...Common.PagePaginationQuery): + | Shared.PagePaginatedResponse + | Common.ErrorResponses; + + /** + * Get an app catalog item by type. + */ + @get + @route("/{appType}") + @operationId("get-app-catalog-item") + @summary("Get app catalog item by type") + get(@path appType: AppType): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Install an app from the catalog. + * + * @returns App installed successfully. + */ + @post + @route("/install") + @operationId("install-app") + @summary("Install app from the catalog") + install(@body body: InstallAppRequest): + | Shared.CreateResponse + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/apps/sandbox.tsp b/api/spec/packages/aip/src/apps/sandbox.tsp new file mode 100644 index 0000000000000000000000000000000000000000..375af8b76780562da186eff76f587d7247d69eac --- /dev/null +++ b/api/spec/packages/aip/src/apps/sandbox.tsp @@ -0,0 +1,11 @@ +import "./app.tsp"; + +namespace Apps; + +/** + * Sandbox app can be used for testing billing features. + */ +@friendlyName("BillingAppSandbox") +model AppSandbox { + ...AppBase; +} diff --git a/api/spec/packages/aip/src/apps/stripe.tsp b/api/spec/packages/aip/src/apps/stripe.tsp new file mode 100644 index 0000000000000000000000000000000000000000..c4b9ba47766c58c67c7be2a8d7e3de4521953b33 --- /dev/null +++ b/api/spec/packages/aip/src/apps/stripe.tsp @@ -0,0 +1,643 @@ +import "../shared/index.tsp"; +import "./app.tsp"; +import "../customers/customer.tsp"; + +namespace Apps; + +/** + * Stripe app. + */ +@friendlyName("BillingAppStripe") +model AppStripe { + ...AppBase; + + /** + * The Stripe account ID associated with the connected Stripe account. + */ + @visibility(Lifecycle.Read) + account_id: string; + + /** + * Indicates whether the app is connected to a live Stripe account. + */ + @visibility(Lifecycle.Read) + livemode: boolean; + + /** + * The masked Stripe API key that only exposes the first and last few characters. + */ + @visibility(Lifecycle.Read) + masked_api_key: string; + + /** + * The Stripe secret API key used to authenticate API requests. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @secret + secret_api_key?: string; +} + +/** + * Configuration options for creating a Stripe Checkout Session. + * + * Based on Stripe's + * [Checkout Session API parameters](https://docs.stripe.com/api/checkout/sessions/create). + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionRequestOptions") +model CreateStripeCheckoutSessionRequestOptions { + /** + * Whether to collect the customer's billing address. + * + * Defaults to auto, which only collects the address when necessary for tax + * calculation. + */ + billing_address_collection?: CreateStripeCheckoutSessionBillingAddressCollection = CreateStripeCheckoutSessionBillingAddressCollection.Auto; + + /** + * URL to redirect customers who cancel the checkout session. + * + * Not allowed when ui_mode is "embedded". + */ + cancel_url?: string; + + /** + * Unique reference string for reconciling sessions with internal systems. + * + * Can be a customer ID, cart ID, or any other identifier. + */ + client_reference_id?: string; + + /** + * Controls which customer fields can be updated by the checkout session. + */ + customer_update?: CreateStripeCheckoutSessionCustomerUpdate; + + /** + * Configuration for collecting customer consent during checkout. + */ + consent_collection?: CreateStripeCheckoutSessionConsentCollection; + + /** + * Three-letter ISO 4217 currency code in uppercase. + * + * Required for payment mode sessions. Optional for setup mode sessions. + */ + currency?: Shared.CurrencyCode; + + /** + * Custom text to display during checkout at various stages. + */ + custom_text?: CheckoutSessionCustomTextParams; + + /** + * Unix timestamp when the checkout session expires. + * + * Can be 30 minutes to 24 hours from creation. Defaults to 24 hours. + */ + expires_at?: int64; + + /** + * IETF language tag for the checkout UI locale. + * + * If blank or "auto", uses the browser's locale. Example: "en", "fr", "de". + */ + locale?: string; + + /** + * Set of key-value pairs to attach to the checkout session. + * + * Useful for storing additional structured information. + */ + metadata?: Record; + + /** + * Return URL for embedded checkout sessions after payment authentication. + * + * Required if ui_mode is "embedded" and redirect-based payment methods are + * enabled. + */ + return_url?: string; + + /** + * Success URL to redirect customers after completing payment or setup. + * + * Not allowed when ui_mode is "embedded". See: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + success_url?: string; + + /** + * The UI mode for the checkout session. + * + * "hosted" displays a Stripe-hosted page. "embedded" integrates directly into your + * app. Defaults to "hosted". + */ + ui_mode?: CheckoutSessionUIMode = CheckoutSessionUIMode.Hosted; + + /** + * List of payment method types to enable (e.g., "card", "us_bank_account"). + * + * If not specified, Stripe enables all relevant payment methods. + */ + payment_method_types?: string[]; + + /** + * Redirect behavior for embedded checkout sessions. + * + * Controls when to redirect users after completion. See: + * https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + */ + redirect_on_completion?: CreateStripeCheckoutSessionRedirectOnCompletion; + + /** + * Configuration for collecting tax IDs during checkout. + */ + tax_id_collection?: CreateCheckoutSessionTaxIdCollection; +} + +/** + * Controls whether Checkout collects the customer's billing address. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionBillingAddressCollection") +enum CreateStripeCheckoutSessionBillingAddressCollection { + /** + * Collect billing address only when necessary (e.g., for tax calculation). + */ + Auto: "auto", + + /** + * Always collect the customer's billing address. + */ + Required: "required", +} + +/** + * Checkout Session consent collection configuration. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionConsentCollection") +model CreateStripeCheckoutSessionConsentCollection { + /** + * Controls the visibility of payment method reuse agreement. + */ + payment_method_reuse_agreement?: CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement; + + /** + * Enables collection of promotional communication consent. + * + * Only available to US merchants. When set to "auto", Checkout determines whether + * to show the option based on the customer's locale. + */ + promotions?: CreateStripeCheckoutSessionConsentCollectionPromotions; + + /** + * Requires customers to accept terms of service before payment. + * + * Requires a valid terms of service URL in your Stripe Dashboard settings. + */ + terms_of_service?: CreateStripeCheckoutSessionConsentCollectionTermsOfService; +} + +/** + * Controls which customer fields can be updated by the checkout session. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionCustomerUpdate") +model CreateStripeCheckoutSessionCustomerUpdate { + /** + * Whether to save the billing address to customer.address. + * + * Defaults to "never". + */ + address?: CreateStripeCheckoutSessionCustomerUpdateBehavior = CreateStripeCheckoutSessionCustomerUpdateBehavior.Never; + + /** + * Whether to save the customer name to customer.name. + * + * Defaults to "never". + */ + name?: CreateStripeCheckoutSessionCustomerUpdateBehavior = CreateStripeCheckoutSessionCustomerUpdateBehavior.Never; + + /** + * Whether to save shipping information to customer.shipping. + * + * Defaults to "never". + */ + shipping?: CreateStripeCheckoutSessionCustomerUpdateBehavior = CreateStripeCheckoutSessionCustomerUpdateBehavior.Never; +} + +/** + * Behavior for updating customer fields from checkout session. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionCustomerUpdateBehavior") +enum CreateStripeCheckoutSessionCustomerUpdateBehavior { + /** + * Automatically determine whether to update the customer using session details. + */ + Auto: "auto", + + /** + * Never update the customer object. + */ + Never: "never", +} + +/** + * Payment method reuse agreement configuration. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement") +model CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement { + /** + * Position and visibility of the payment method reuse agreement. + */ + position?: CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition; +} + +/** + * Position of payment method reuse agreement in the UI. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition") +enum CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition { + /** + * Use Stripe defaults for visibility and position. + */ + Auto: "auto", + + /** + * Hide the payment method reuse agreement. + */ + Hidden: "hidden", +} + +/** + * Promotional communication consent collection setting. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionConsentCollectionPromotions") +enum CreateStripeCheckoutSessionConsentCollectionPromotions { + /** + * Show promotional consent option based on customer context and locale. + */ + Auto: "auto", + + /** + * Do not collect promotional communication consent. + */ + None: "none", +} + +/** + * Terms of service acceptance requirement. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionConsentCollectionTermsOfService") +enum CreateStripeCheckoutSessionConsentCollectionTermsOfService { + /** + * Do not display terms of service checkbox. + */ + None: "none", + + /** + * Require customers to accept terms of service before payment. + */ + Required: "required", +} + +/** + * Redirect behavior for embedded checkout sessions. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionRedirectOnCompletion") +enum CreateStripeCheckoutSessionRedirectOnCompletion { + /** + * Always redirect to return_url after successful confirmation. + */ + Always: "always", + + /** + * Redirect only when a redirect-based payment method is used. + */ + IfRequired: "if_required", + + /** + * Never redirect, and disable redirect-based payment methods. + */ + Never: "never", +} + +/** + * Tax ID collection configuration for checkout sessions. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionTaxIdCollection") +model CreateCheckoutSessionTaxIdCollection { + /** + * Enable tax ID collection during checkout. + * + * Defaults to false. + */ + enabled?: boolean = false; + + /** + * Whether tax ID collection is required. + * + * Defaults to "never". + */ + required?: CreateCheckoutSessionTaxIdCollectionRequired = CreateCheckoutSessionTaxIdCollectionRequired.Never; +} + +/** + * Tax ID collection requirement level. + */ +@friendlyName("BillingAppStripeCreateCheckoutSessionTaxIdCollectionRequired") +enum CreateCheckoutSessionTaxIdCollectionRequired { + /** + * Require tax ID if collection is supported for the billing address country. + * + * See: https://docs.stripe.com/tax/checkout/tax-ids#supported-types + */ + IfSupported: "if_supported", + + /** + * Tax ID collection is never required. + */ + Never: "never", +} + +/** + * Checkout Session UI mode. + */ +@friendlyName("BillingAppStripeCheckoutSessionUIMode") +enum CheckoutSessionUIMode { + /** + * Checkout UI embedded directly in your application. + */ + Embedded: "embedded", + + /** + * Checkout UI hosted on a Stripe-provided page. + */ + Hosted: "hosted", +} + +/** + * Custom text displayed at various stages of the checkout flow. + */ +@friendlyName("BillingAppStripeCheckoutSessionCustomTextParams") +model CheckoutSessionCustomTextParams { + /** + * Text displayed after the payment confirmation button. + */ + after_submit?: { + /** + * The custom message text (max 1200 characters). + */ + @maxLength(1200) + message?: string; + }; + + /** + * Text displayed alongside shipping address collection. + */ + shipping_address?: { + /** + * The custom message text (max 1200 characters). + */ + @maxLength(1200) + message?: string; + }; + + /** + * Text displayed alongside the payment confirmation button. + */ + submit?: { + /** + * The custom message text (max 1200 characters). + */ + @maxLength(1200) + message?: string; + }; + + /** + * Text replacing the default terms of service agreement text. + */ + terms_of_service_acceptance?: { + /** + * The custom message text (max 1200 characters). + */ + @maxLength(1200) + message?: string; + }; +} + +/** + * Result of creating a Stripe Checkout Session. + * + * Contains all the information needed to redirect customers to the checkout or + * initialize an embedded checkout flow. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "Field names match Stripe API response structure" +@friendlyName("BillingAppStripeCreateCheckoutSessionResult") +model CreateStripeCheckoutSessionResult { + /** + * The customer ID in the billing system. + */ + customer_id: Shared.ULID; + + /** + * The Stripe customer ID. + */ + stripe_customer_id: string; + + /** + * The Stripe checkout session ID. + */ + session_id: string; + + /** + * The setup intent ID created for collecting the payment method. + */ + setup_intent_id: string; + + /** + * Client secret for initializing Stripe.js on the client side. + * + * Required for embedded checkout sessions. See: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + client_secret?: string; + + /** + * The client reference ID provided in the request. + * + * Useful for reconciling the session with your internal systems. + */ + client_reference_id?: string; + + /** + * Customer's email address if provided to Stripe. + */ + customer_email?: string; + + /** + * Currency code for the checkout session. + */ + currency?: Shared.CurrencyCode; + + /** + * Timestamp when the checkout session was created. + */ + created_at: Shared.DateTime; + + /** + * Timestamp when the checkout session will expire. + */ + expires_at?: Shared.DateTime; + + /** + * Metadata attached to the checkout session. + */ + metadata?: Record; + + /** + * The status of the checkout session. + * + * See: + * https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status + */ + status?: string; + + /** + * URL to redirect customers to the checkout page (for hosted mode). + */ + url?: string; + + /** + * Mode of the checkout session. + * + * Currently only "setup" mode is supported for collecting payment methods. + */ + mode: StripeCheckoutSessionMode; + + /** + * The cancel URL where customers are redirected if they cancel. + */ + cancel_url?: string; + + /** + * The success URL where customers are redirected after completion. + */ + success_url?: string; + + /** + * The return URL for embedded sessions after authentication. + */ + return_url?: string; +} + +/** + * Stripe Checkout Session mode. + * + * Determines the primary purpose of the checkout session. + */ +@friendlyName("BillingAppStripeCheckoutSessionMode") +enum StripeCheckoutSessionMode { + /** + * Collect payment method information for later use. + * + * Used for subscription billing where the payment method is charged later. + */ + Setup: "setup", +} + +/** + * Request to create a Stripe Customer Portal Session. + */ +@friendlyName("BillingAppStripeCreateCustomerPortalSessionOptions") +model CreateStripeCustomerPortalSessionOptions { + /** + * The ID of an existing + * [Stripe configuration](https://docs.stripe.com/api/customer_portal/configurations) + * to use for this session, describing its functionality and features. If not + * specified, the session uses the default configuration. + */ + configuration_id?: string; + + /** + * The IETF + * [language tag](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale) + * of the locale customer portal is displayed in. If blank or `auto`, the + * customer's preferred_locales or browser's locale is used. + */ + locale?: string; + + /** + * The + * [URL to redirect](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url) + * the customer to after they have completed their requested actions. + */ + return_url?: string; +} + +/** + * Result of creating a + * [Stripe Customer Portal Session](https://docs.stripe.com/api/customer_portal/sessions/object). + * + * Contains all the information needed to redirect the customer to the Stripe + * Customer Portal. + */ +@friendlyName("BillingAppStripeCreateCustomerPortalSessionResult") +model CreateStripeCustomerPortalSessionResult { + /** + * The ID of the customer portal session. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + */ + id: string; + + /** + * The ID of the stripe customer. + */ + stripe_customer_id: string; + + /** + * Configuration used to customize the customer portal. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + */ + configuration_id: string; + + /** + * Livemode. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + */ + livemode: boolean; + + /** + * Created at. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + */ + created_at: Shared.DateTime; + + /** + * Return URL. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + */ + return_url: string; + + /** + * The IETF language tag of the locale customer portal is displayed in. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + */ + locale: string; + + /** + * The URL to redirect the customer to after they have completed their requested + * actions. + */ + url: string; +} diff --git a/api/spec/packages/aip/src/billing/index.tsp b/api/spec/packages/aip/src/billing/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..36045af6e437d73f8f39c53202a67c23414bcc21 --- /dev/null +++ b/api/spec/packages/aip/src/billing/index.tsp @@ -0,0 +1,4 @@ +import "./profile.tsp"; +import "./tax.tsp"; +import "./operations.tsp"; +import "./totals.tsp"; diff --git a/api/spec/packages/aip/src/billing/operations.tsp b/api/spec/packages/aip/src/billing/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..288d2c9fb71daa9ab0377df709c2abd475095be1 --- /dev/null +++ b/api/spec/packages/aip/src/billing/operations.tsp @@ -0,0 +1,82 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./profile.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Billing; + +interface BillingProfilesOperations { + /** + * List billing profiles. + */ + @get + @operationId("list-billing-profiles") + @summary("List billing profiles") + list(...Common.PagePaginationQuery): + | Shared.PagePaginatedResponse + | Common.ErrorResponses; + + /** + * Create a new billing profile. + * + * Billing profiles contain the settings for billing and controls invoice + * generation. An organization can have multiple billing profiles defined. A + * billing profile is linked to a specific app. This association is established + * during the billing profile's creation and remains immutable. + */ + @post + @operationId("create-billing-profile") + @summary("Create a new billing profile") + create(@body profile: Shared.CreateRequest): + | Shared.CreateResponse + | Common.ErrorResponses; + + /** + * Get a billing profile. + */ + @get + @operationId("get-billing-profile") + @summary("Get a billing profile") + get(@path id: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Update a billing profile. + */ + @put + @operationId("update-billing-profile") + @summary("Update a billing profile") + update( + @path id: Shared.ULID, + @body profile: Shared.UpsertRequest, + ): + | Shared.UpdateResponse + | Common.NotFound + | Common.ErrorResponses; + /** + * Delete a billing profile. + * + * Only such billing profiles can be deleted that are: + * + * - not the default profile + * - not pinned to any customer using customer overrides + * - only have finalized invoices + */ + @delete + @operationId("delete-billing-profile") + @summary("Delete a billing profile") + delete(@path id: Shared.ULID): + | Shared.DeleteResponse + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/billing/profile.tsp b/api/spec/packages/aip/src/billing/profile.tsp new file mode 100644 index 0000000000000000000000000000000000000000..962fdaa5a779968c1ef209dbee8bd61f6a19aeeb --- /dev/null +++ b/api/spec/packages/aip/src/billing/profile.tsp @@ -0,0 +1,369 @@ +import "../shared/index.tsp"; +import "../invoices/index.tsp"; +import "../apps/index.tsp"; +import "./tax.tsp"; + +namespace Billing; + +/** + * Billing profiles contain the settings for billing and controls invoice + * generation. + */ +@friendlyName("BillingProfile") +model BillingProfile { + ...Shared.Resource; + + /** + * The name and contact information for the supplier this billing profile + * represents + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + supplier: Invoices.BillingParty; + + /** + * The billing workflow settings for this profile + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + workflow: BillingWorkflow; + + /** + * The applications used by this billing profile. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + apps: BillingProfileAppReferences; + + /** + * Whether this is the default profile. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + default: boolean; +} + +/** + * Billing profile reference. + */ +@friendlyName("BillingProfileReference") +model BillingProfileReference { + /** + * The ID of the billing profile. + */ + id: Shared.ULID; +} + +/** + * Billing workflow settings. + */ +@friendlyName("BillingWorkflow") +model BillingWorkflow { + /** + * The collection settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + collection?: BillingWorkflowCollectionSettings; + + /** + * The invoicing settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + invoicing?: BillingWorkflowInvoicingSettings; + + /** + * The payment settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + payment?: BillingWorkflowPaymentSettings; + + /** + * The tax settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + tax?: BillingWorkflowTaxSettings; +} + +/** + * Workflow collection specifies how to collect the pending line items for an + * invoice. + */ +@summary("Workflow collection settings") +@friendlyName("BillingWorkflowCollectionSettings") +model BillingWorkflowCollectionSettings { + /** + * The alignment for collecting the pending line items into an invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + alignment?: BillingWorkflowCollectionAlignment = DefaultBillingWorkflowCollectionAlignment; + + /** + * This grace period can be used to delay the collection of the pending line items + * specified in alignment. + * + * This is useful, in case of multiple subscriptions having slightly different + * billing periods. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P1D") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + interval?: string = "PT1H"; +} + +/** + * BillingCollectionAlignment specifies when the pending line items should be + * collected into an invoice. + */ +@friendlyName("BillingCollectionAlignment") +@summary("Collection alignment") +enum BillingCollectionAlignmentType { + /** + * Align the collection to the start of the subscription period. + */ + Subscription: "subscription", + + /** + * Align the collection to the anchor time and cadence. + */ + Anchored: "anchored", +} + +const DefaultBillingWorkflowCollectionAlignment: BillingWorkflowCollectionAlignmentSubscription = #{ + type: BillingCollectionAlignmentType.Subscription, +}; + +/** + * The alignment for collecting the pending line items into an invoice. + * + * Defaults to subscription, which means that we are to create a new invoice every + * time the a subscription period starts (for in advance items) or ends (for in + * arrears items). + */ +@friendlyName("BillingWorkflowCollectionAlignment") +@discriminated(#{ discriminatorPropertyName: "type", envelope: "none" }) +union BillingWorkflowCollectionAlignment { + subscription: BillingWorkflowCollectionAlignmentSubscription, + anchored: BillingWorkflowCollectionAlignmentAnchored, +} + +/** + * BillingWorkflowCollectionAlignmentAnchored specifies the alignment for + * collecting the pending line items into an invoice. + */ +@friendlyName("BillingWorkflowCollectionAlignmentAnchored") +model BillingWorkflowCollectionAlignmentAnchored { + /** + * The type of alignment. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: BillingCollectionAlignmentType.Anchored; + + /** + * The recurring period for the alignment. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + recurring_period: Shared.RecurringPeriod; +} + +/** + * BillingWorkflowCollectionAlignmentSubscription specifies the alignment for + * collecting the pending line items into an invoice. + */ +@friendlyName("BillingWorkflowCollectionAlignmentSubscription") +model BillingWorkflowCollectionAlignmentSubscription { + /** + * The type of alignment. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: BillingCollectionAlignmentType.Subscription; +} + +/** + * Invoice settings for a billing workflow. + */ +@summary("Workflow invoice settings") +@friendlyName("BillingWorkflowInvoicingSettings") +model BillingWorkflowInvoicingSettings { + /** + * Whether to automatically issue the invoice after the draftPeriod has passed. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + auto_advance?: boolean = true; + + /** + * The period for the invoice to be kept in draft status for manual reviews. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P1D") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + draft_period?: string = "P0D"; + + /** + * Should progressive billing be allowed for this workflow? + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + progressive_billing?: boolean = true; + + /** + * Controls how subscription-ending shortened service periods are billed. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + subscription_end_proration_mode?: BillingWorkflowInvoicingSubscriptionEndProrationMode = BillingWorkflowInvoicingSubscriptionEndProrationMode.BillActualPeriod; +} + +/** + * Billing workflow subscription end proration mode. + */ +@friendlyName("BillingWorkflowInvoicingSubscriptionEndProrationMode") +enum BillingWorkflowInvoicingSubscriptionEndProrationMode { + /** + * Bill the full billing period amount for terminal lines even when the actual + * service period is shorter. + */ + BillFullPeriod: "bill_full_period", + + /** + * Bill the amount for the actual terminal service period. + */ + BillActualPeriod: "bill_actual_period", +} + +/** + * Tax settings for a billing workflow. + */ +@summary("Workflow tax settings") +@friendlyName("BillingWorkflowTaxSettings") +model BillingWorkflowTaxSettings { + /** + * Enable automatic tax calculation when tax is supported by the app. For example, + * with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + enabled?: boolean = true; + + /** + * Enforce tax calculation when tax is supported by the app. When enabled, the + * billing system will not allow to create an invoice without tax calculation. + * Enforcement is different per apps, for example, Stripe app requires customer to + * have a tax location when starting a paid subscription. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + enforced?: boolean = false; + + /** + * Default tax configuration to apply to the invoices for line items. + * + * Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax + * config is deprecated and can no longer be added or changed: the organization + * default tax code is used instead. Existing tax-code values may still be removed, + * and `behavior` remains fully supported. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + default_tax_config?: TaxConfig; +} + +/** + * Applications used by a billing profile. + */ +@friendlyName("BillingProfileApps") +model BillingProfileApps { + /** + * The tax app used for this workflow. + */ + @visibility(Lifecycle.Read) + tax: Apps.App; + + /** + * The invoicing app used for this workflow. + */ + @visibility(Lifecycle.Read) + invoicing: Apps.App; + + /** + * The payment app used for this workflow. + */ + @visibility(Lifecycle.Read) + payment: Apps.App; +} + +/** + * References to the applications used by a billing profile. + */ +@friendlyName("BillingProfileAppReferences") +model BillingProfileAppReferences { + /** + * The tax app used for this workflow. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + tax: Apps.AppReference; + + /** + * The invoicing app used for this workflow. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + invoicing: Apps.AppReference; + + /** + * The payment app used for this workflow. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + payment: Apps.AppReference; +} + +/** + * Collection method specifies how the invoice should be collected (automatic or + * manual). + */ +@friendlyName("BillingCollectionMethod") +@summary("Collection method") +enum CollectionMethod { + @summary("Charge automatically") + ChargeAutomatically: "charge_automatically", + + @summary("Send invoice") + SendInvoice: "send_invoice", +} + +/** + * Payment settings for a billing workflow. + */ +@friendlyName("BillingWorkflowPaymentSettings") +@discriminated(#{ + discriminatorPropertyName: "collection_method", + envelope: "none", +}) +union BillingWorkflowPaymentSettings { + charge_automatically: BillingWorkflowPaymentChargeAutomaticallySettings, + send_invoice: BillingWorkflowPaymentSendInvoiceSettings, +} + +/** + * Payment settings for a billing workflow when the collection method is charge + * automatically. + */ +@friendlyName("BillingWorkflowPaymentChargeAutomaticallySettings") +model BillingWorkflowPaymentChargeAutomaticallySettings { + /** + * The collection method for the invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + collection_method: CollectionMethod.ChargeAutomatically; +} + +/** + * Payment settings for a billing workflow when the collection method is send + * invoice. + */ +@friendlyName("BillingWorkflowPaymentSendInvoiceSettings") +model BillingWorkflowPaymentSendInvoiceSettings { + /** + * The collection method for the invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + collection_method: CollectionMethod.SendInvoice; + + /** + * The period after which the invoice is due. With some payment solutions it's only + * applicable for manual collection method. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P30D") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + due_after?: string = "P30D"; +} diff --git a/api/spec/packages/aip/src/billing/tax.tsp b/api/spec/packages/aip/src/billing/tax.tsp new file mode 100644 index 0000000000000000000000000000000000000000..549a1f81fcc87023c8a381cb930e5dd69484098d --- /dev/null +++ b/api/spec/packages/aip/src/billing/tax.tsp @@ -0,0 +1,101 @@ +namespace Billing; + +/** + * Set of provider specific tax configs. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "tax_code_id is deprecated" +@friendlyName("BillingTaxConfig") +model TaxConfig { + /** + * Tax behavior. + * + * If not specified the billing profile is used to determine the tax behavior. If + * not specified in the billing profile, the provider's default behavior is used. + */ + @summary("Tax behavior") + behavior?: TaxBehavior; + + /** + * Stripe tax config. + * + * @deprecated Use `tax_code` instead. When both `stripe.code` and `tax_code` are + * provided, `tax_code` takes precedence and `stripe.code` is ignored. + */ + #deprecated "Use tax_code instead" + @summary("Stripe tax config") + stripe?: TaxConfigStripe; + + /** + * External invoicing tax config. + * + * @deprecated Use `tax_code` instead. + */ + #deprecated "Use tax_code instead" + @summary("External invoicing tax config") + external_invoicing?: TaxConfigExternalInvoicing; + + /** + * Tax code ID. + * + * @deprecated Use `tax_code` instead. + */ + #deprecated "Use tax_code instead" + @summary("Tax code ID") + tax_code_id?: Shared.ULID; + + /** + * Tax code reference. + * + * When both `tax_code` and `tax_code_id` are provided, `tax_code` takes + * precedence. When `stripe.code` is also provided, `tax_code` still wins and + * `stripe.code` is ignored. + */ + @summary("Tax code") + tax_code?: Shared.ResourceReference; +} + +/** + * Tax behavior. + * + * This enum is used to specify whether tax is included in the price or excluded + * from the price. + */ +@friendlyName("BillingTaxBehavior") +enum TaxBehavior { + /** + * Tax is included in the price. + */ + Inclusive: "inclusive", + + /** + * Tax is excluded from the price. + */ + Exclusive: "exclusive", +} + +/** + * The tax config for Stripe. + */ +@friendlyName("BillingTaxConfigStripe") +model TaxConfigStripe { + /** + * Product [tax code](https://docs.stripe.com/tax/tax-codes). + */ + @summary("Tax code") + @pattern("^txcd_\\d{8}$") + @example("txcd_10000000") + code: string; +} + +/** + * External invoicing tax config. + */ +@friendlyName("BillingTaxConfigExternalInvoicing") +model TaxConfigExternalInvoicing { + /** + * The tax code should be interpreted by the external invoicing provider. + */ + @summary("Tax code") + @maxLength(64) + code: string; +}